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

        // cekBiru($this->configPath);
        // cekBiru($configPath);
        // cekKuning(url_segment(3));
    }

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

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


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

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


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

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

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

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

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


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


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

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

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

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


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

        // cekMerah($this->jenisTr);

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

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

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

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

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

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

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


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

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

                        if (isset($row->ids_his)) {
                            $returnVal = showHistoriGlobalNumbers($row->ids_his, $hisStep, true);
                            if ($returnVal == "") {
                                $tmp[$fName] = "-";
                            }
                            else {
                                $tmp[$fName] = $returnVal;
                            }
                        }
                        else {
                            $tmp[$fName] = "-";
                        }
                    }
                    else {
                        $tmp[$fName] = isset($row->$fName) ? formatField_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);

    }

    public function preview()
    {

        // $this->jenisTr = $this->uri->segment(3);
        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        $configUi = $this->configUi;

        $stepNumber = isset($_SESSION[$cCode]['tableIn_master']['step_number']) ? $_SESSION[$cCode]['tableIn_master']['step_number'] : 1;
        $itemLabels = isset($configUi[$this->jenisTr]['shoppingCartFields'][$stepNumber]) ? $configUi[$this->jenisTr]['shoppingCartFields'][$stepNumber] : array();
        $itemLabels2 = isset($configUi[$this->jenisTr]['shoppingCartFields2'][$stepNumber]) ? $configUi[$this->jenisTr]['shoppingCartFields2'][$stepNumber] : array();
        $itemLabels3 = isset($configUi[$this->jenisTr]['shoppingCartFields3'][$stepNumber]) ? $configUi[$this->jenisTr]['shoppingCartFields3'][$stepNumber] : array();
        $itemSrcLabels = isset($configUi[$this->jenisTr]['shoppingCartFieldItemSrc'][$stepNumber]) ? $configUi[$this->jenisTr]['shoppingCartFieldItemSrc'][$stepNumber] : array();
        $itemNumLabels = isset($configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber]) ? $configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber] : array();
        $itemNumLabels2 = isset($configUi[$this->jenisTr]['shoppingCartNumFields2'][$stepNumber]) ? $configUi[$this->jenisTr]['shoppingCartNumFields2'][$stepNumber] : array();
        $itemNumLabels3 = isset($configUi[$this->jenisTr]['shoppingCartNumFields3'][$stepNumber]) ? $configUi[$this->jenisTr]['shoppingCartNumFields3'][$stepNumber] : array();
        $itemSrcNumLabels = isset($configUi[$this->jenisTr]['shoppingCartNumFieldItemSrc'][$stepNumber]) ? $configUi[$this->jenisTr]['shoppingCartNumFieldItemSrc'][$stepNumber] : array();

        $appletConfigs = isset($configUi[$this->jenisTr]['applets']) ? $configUi[$this->jenisTr]['applets'] : array();
        $elementConfigs = isset($configUi[$this->jenisTr]['receiptElements']) ? $configUi[$this->jenisTr]['receiptElements'] : array();
        $relElementConfigs = isset($configUi[$this->jenisTr]['relativeElements']) ? $configUi[$this->jenisTr]['relativeElements'] : array();
        $relOptionConfigs = isset($configUi[$this->jenisTr]['relativeOptions']) ? $configUi[$this->jenisTr]['relativeOptions'] : array();
        $noteEnabled = isset($configUi[$this->jenisTr]['shoppingCartNoteEnabled']) && $configUi[$this->jenisTr]['shoppingCartNoteEnabled'] == true ? true : false;
        $imageEnabled = isset($configUi[$this->jenisTr]['shoppingCartImageEnabled']) && $configUi[$this->jenisTr]['shoppingCartImageEnabled'] == true ? true : false;
        $addRowsConfigs = isset($configUi[$this->jenisTr]['additionalRows']) ? $configUi[$this->jenisTr]['additionalRows'] : array();
        $inputLabels = array();
        $rawPrevURL = isset($_GET['rawPrev']) ? $_GET['rawPrev'] : "";

        //
        //region lookup items from shopping cart sessions
        //        cekbiru($rawPrevURL);

        $main = array();
        $items = array();
        $items2 = array();
        $items2_sum = array();
        $items3_sum = array();
        $itemsSrc = array();
        //        arrPrint($_SESSION[$cCode]['itemSrc']);
        //        matiHEre();
        if (isset($_SESSION[$cCode])) {
            if (isset($_SESSION[$cCode]['items'])) {
                foreach ($_SESSION[$cCode]['items'] as $iSpec) {
                    $tmp = array(
                        "id" => $iSpec['id'],
                        "nama" => $iSpec['nama'],
                        "satuan" => isset($iSpec['satuan']) ? $iSpec['satuan'] : "n/a",
                        "jml" => $iSpec['jml'],
                        "produk_kode" => isset($iSpec['produk_kode']) ? $iSpec['produk_kode'] : "n/a",
                        "no_part" => isset($iSpec['no_part']) ? $iSpec['no_part'] : "n/a",

                        "stok" => isset($iSpec['stok']) ? $iSpec['stok'] : "",
                        "stok_center" => isset($iSpec['stok_center']) ? $iSpec['stok_center'] : "0",
                        "merk" => isset($iSpec['merk']) ? $iSpec['merk'] : "",
                        "serial_no" => isset($iSpec['serial_no']) ? $iSpec['serial_no'] : "",
                        "kode" => isset($iSpec['kode']) ? $iSpec['kode'] : "",
                        "extern_date2" => isset($iSpec['extern_date2']) ? $iSpec['extern_date2'] : "",
                        "extern_label2" => isset($iSpec['extern_label2']) ? $iSpec['extern_label2'] : "",
                    );
                    if (sizeof($itemNumLabels) > 0) {
                        foreach ($itemNumLabels as $key => $label) {
                            $tmp[$key] = isset($iSpec[$key]) ? $iSpec[$key] : 0;
                            if (!isset($main[$key])) {
                                $main[$key] = 0;
                            }
                            $main[$key] += isset($iSpec[$key]) ? ($iSpec['jml'] * $iSpec[$key]) : 0;

                        }
                    }
                    if ($noteEnabled) {
                        if (isset($iSpec['note'])) {
                            $tmp['note'] = $iSpec['note'];
                        }
                    }
                    if ($imageEnabled) {
                        if (isset($iSpec['images'])) {
                            $tmp['images'] = $iSpec['images'];
                        }
                    }
                    $tmp['subtotal'] = $iSpec['subtotal'];


                    $tmp["editTarget"] = base_url() . $iSpec['handler'] . "/select/" . $this->jenisTr . "?id=" . $iSpec['id'] . "&newQty=";
                    $tmp["removeTarget"] = base_url() . $iSpec['handler'] . "/remove/" . $this->jenisTr . "?id=" . $iSpec['id'];

                    $items[] = $tmp;
                }
            }

            if (isset($_SESSION[$cCode]['items2'])) {
                foreach ($_SESSION[$cCode]['items2'] as $aSpec) {
                    //                    arrPrint($iSpec);
                    foreach ($aSpec as $iSpec) {
                        if (isset($iSpec['id'])) {

                            $tmp = array(
                                "id" => $iSpec['id'],
                                "nama" => $iSpec['nama'],
                                "satuan" => isset($iSpec['satuan']) ? $iSpec['satuan'] : "n/a",
                                "jml" => $iSpec['jml'],
                                "produk_kode" => isset($iSpec['produk_kode']) ? $iSpec['produk_kode'] : "n/a",
                                "no_part" => isset($iSpec['no_part']) ? $iSpec['no_part'] : "n/a",

                                "kode" => isset($iSpec['kode']) ? $iSpec['kode'] : "n/a",
                                "disc_value" => isset($iSpec['disc_value']) ? $iSpec['disc_value'] : "0",
                                "jual" => isset($iSpec['jual']) ? $iSpec['jual'] : 0,
                                "stok" => isset($iSpec['stok']) ? $iSpec['stok'] : 0,
                                "stok_center" => isset($iSpec['stok_center']) ? $iSpec['stok_center'] : 0,
                                "harga_ori" => isset($iSpec['harga_ori']) ? $iSpec['harga_ori'] : "",
                                "harga" => isset($iSpec['harga']) ? $iSpec['harga'] : "",

                            );
                            if (sizeof($itemNumLabels) > 0) {
                                foreach ($itemNumLabels as $key => $label) {
                                    $tmp[$key] = isset($iSpec[$key]) ? $iSpec[$key] : 0;
                                    if (!isset($main[$key])) {
                                        $main[$key] = 0;
                                    }
                                    $main[$key] += isset($iSpec[$key]) ? ($iSpec['jml'] * $iSpec[$key]) : 0;

                                }
                            }
                            if ($noteEnabled) {
                                if (isset($iSpec['note'])) {
                                    $tmp['note'] = $iSpec['note'];
                                }
                            }
                            if ($imageEnabled) {
                                if (isset($iSpec['images'])) {
                                    $tmp['images'] = $iSpec['images'];
                                }
                            }
                            $tmp['subtotal'] = $iSpec['subtotal'];

                            if (isset($iSpec['handler'])) {
                                $tmp["editTarget"] = base_url() . $iSpec['handler'] . "/select/" . $this->jenisTr . "?id=" . $iSpec['id'] . "&newQty=";
                                $tmp["removeTarget"] = base_url() . $iSpec['handler'] . "/remove/" . $this->jenisTr . "?id=" . $iSpec['id'];
                            }
                            else {
                                $tmp["editTarget"] = "#";
                                $tmp["removeTarget"] = "#";
                            }

                            $items2[] = $tmp;
                        }
                    }


                }
            }

            if (isset($_SESSION[$cCode]['items2_sum'])) {
                foreach ($_SESSION[$cCode]['items2_sum'] as $iSpec) {
                    $tmp = array(
                        "id" => $iSpec['id'],
                        "nama" => $iSpec['nama'],
                        "satuan" => isset($iSpec['satuan']) ? $iSpec['satuan'] : "n/a",
                        "jml" => $iSpec['jml'],
                        "produk_kode" => isset($iSpec['produk_kode']) ? $iSpec['produk_kode'] : "n/a",
                        "no_part" => isset($iSpec['no_part']) ? $iSpec['no_part'] : "n/a",

                        "kode" => isset($iSpec['kode']) ? $iSpec['kode'] : "n/a",
                        "harga" => isset($iSpec['harga_ori']) ? $iSpec['harga_ori'] : isset($iSpec['harga']) ? $iSpec['harga'] : "0",
                        "harga_ori" => isset($iSpec['harga_ori']) ? $iSpec['harga_ori'] : "",
                        "referensi" => isset($iSpec['pihakName']) ? $iSpec['pihakName'] : "",
                        "disc_value" => isset($iSpec['disc_value']) ? $iSpec['disc_value'] : 0,
                        "jual" => isset($iSpec['jual']) ? $iSpec['jual'] : 0,

                        "stok" => isset($iSpec['stok']) ? $iSpec['stok'] : "",
                        "stok_center" => isset($iSpec['stok_center']) ? $iSpec['stok_center'] : "0",
                        "sisa" => isset($iSpec['stok']) ? $iSpec['stok'] - $iSpec['jml'] : "",
                    );
                    if (sizeof($itemNumLabels) > 0) {
                        foreach ($itemNumLabels as $key => $label) {
                            $tmp[$key] = isset($iSpec[$key]) ? $iSpec[$key] : 0;
                            if (!isset($main[$key])) {
                                $main[$key] = 0;
                            }
                            $main[$key] += isset($iSpec[$key]) ? ($iSpec['jml'] * $iSpec[$key]) : 0;

                        }
                    }
                    if ($noteEnabled) {
                        if (isset($iSpec['note'])) {
                            $tmp['note'] = $iSpec['note'];
                        }
                    }
                    if ($imageEnabled) {
                        if (isset($iSpec['images'])) {
                            $tmp['images'] = $iSpec['images'];
                        }
                    }
                    $tmp['subtotal'] = isset($iSpec['subtotal']) ? $iSpec['subtotal'] : 0;

                    if (isset($iSpec['handler'])) {

                        $tmp["editTarget"] = base_url() . $iSpec['handler'] . "/select/" . $this->jenisTr . "?id=" . $iSpec['id'] . "&newQty=";
                        $tmp["removeTarget"] = base_url() . $iSpec['handler'] . "/remove/" . $this->jenisTr . "?id=" . $iSpec['id'];
                    }
                    else {
                        $tmp["editTarget"] = "#";
                        $tmp["removeTarget"] = "#";
                    }

                    $items2_sum[] = $tmp;
                }
            }

            if (isset($_SESSION[$cCode]['items3_sum'])) {
                foreach ($_SESSION[$cCode]['items3_sum'] as $iSpec) {
                    $tmp = array(
                        "id" => $iSpec['id'],
                        "nama" => $iSpec['nama'],
                        "satuan" => isset($iSpec['satuan']) ? $iSpec['satuan'] : "n/a",
                        "jml" => $iSpec['jml'],
                        "produk_kode" => isset($iSpec['produk_kode']) ? $iSpec['produk_kode'] : "n/a",
                        "no_part" => isset($iSpec['no_part']) ? $iSpec['no_part'] : "n/a",

                        "harga" => isset($iSpec['harga']) ? $iSpec['harga'] : "",
                        "referensi" => isset($iSpec['pihakName']) ? $iSpec['pihakName'] : "",
                        "sub_nilai" => isset($iSpec['sub_nilai']) ? $iSpec['sub_nilai'] : "",

                        "stok" => isset($iSpec['stok']) ? $iSpec['stok'] : "",
                        "stok_center" => isset($iSpec['stok_center']) ? $iSpec['stok_center'] : "0",
                        "sisa" => isset($iSpec['stok']) ? $iSpec['stok'] - $iSpec['jml'] : "",
                    );
                    if (sizeof($itemNumLabels) > 0) {
                        foreach ($itemNumLabels as $key => $label) {
                            $tmp[$key] = isset($iSpec[$key]) ? $iSpec[$key] : 0;
                            if (!isset($main[$key])) {
                                $main[$key] = 0;
                            }
                            $main[$key] += isset($iSpec[$key]) ? ($iSpec['jml'] * $iSpec[$key]) : 0;

                        }
                    }
                    if ($noteEnabled) {
                        if (isset($iSpec['note'])) {
                            $tmp['note'] = $iSpec['note'];
                        }
                    }
                    if ($imageEnabled) {
                        if (isset($iSpec['images'])) {
                            $tmp['images'] = $iSpec['images'];
                        }
                    }
                    $tmp['subtotal'] = isset($iSpec['subtotal']) ? $iSpec['subtotal'] : 0;

                    if (isset($iSpec['handler'])) {

                        $tmp["editTarget"] = base_url() . $iSpec['handler'] . "/select/" . $this->jenisTr . "?id=" . $iSpec['id'] . "&newQty=";
                        $tmp["removeTarget"] = base_url() . $iSpec['handler'] . "/remove/" . $this->jenisTr . "?id=" . $iSpec['id'];
                    }
                    else {
                        $tmp["editTarget"] = "#";
                        $tmp["removeTarget"] = "#";
                    }

                    $items3_sum[] = $tmp;
                }
            }
            if (isset($_SESSION[$cCode]['itemSrc'])) {
                foreach ($_SESSION[$cCode]['itemSrc'] as $iSpec) {
                    $tmp = array(
                        "id" => $iSpec['id'],
                        "nama" => $iSpec['nama'],
                        "satuan" => isset($iSpec['satuan']) ? $iSpec['satuan'] : "n/a",
                        "jml" => $iSpec['jml'],
                        "produk_kode" => isset($iSpec['produk_kode']) ? $iSpec['produk_kode'] : "n/a",
                        "no_part" => isset($iSpec['no_part']) ? $iSpec['no_part'] : "n/a",

                        "stok" => isset($iSpec['stok']) ? $iSpec['stok'] : "",
                        "stok_center" => isset($iSpec['stok_center']) ? $iSpec['stok_center'] : "0",
                        "merk" => isset($iSpec['merk']) ? $iSpec['merk'] : "",
                        "serial_no" => isset($iSpec['serial_no']) ? $iSpec['serial_no'] : "",
                        "kode" => isset($iSpec['kode']) ? $iSpec['kode'] : "",
                        "extern_date2" => isset($iSpec['extern_date2']) ? $iSpec['extern_date2'] : "",
                        "extern_label2" => isset($iSpec['extern_label2']) ? $iSpec['extern_label2'] : "",
                        "extern_nama" => isset($iSpec['extern_nama']) ? $iSpec['extern_nama'] : "",
                    );
                    if (sizeof($itemSrcNumLabels) > 0) {
                        foreach ($itemSrcNumLabels as $key => $label) {
                            $tmp[$key] = isset($iSpec[$key]) ? $iSpec[$key] : 0;
                            if (!isset($main[$key])) {
                                $main[$key] = 0;
                            }
                            //                            $main[$key] += isset($iSpec[$key]) ? ($iSpec['jml'] * $iSpec[$key]) : 0;

                        }
                    }
                    if ($noteEnabled) {
                        if (isset($iSpec['note'])) {
                            $tmp['note'] = $iSpec['note'];
                        }
                    }
                    if ($imageEnabled) {
                        if (isset($iSpec['images'])) {
                            $tmp['images'] = $iSpec['images'];
                        }
                    }
                    $tmp['subtotal'] = $iSpec['subtotal'];


                    $tmp["editTarget"] = base_url() . $iSpec['handler'] . "/select/" . $this->jenisTr . "?id=" . $iSpec['id'] . "&newQty=";
                    $tmp["removeTarget"] = base_url() . $iSpec['handler'] . "/remove/" . $this->jenisTr . "?id=" . $iSpec['id'];

                    $itemsSrc[] = $tmp;
                }
            }
        }
        //endregion

        //
        //region labels for preview's bottom elements
        // cekBiru($jenisTr);
        // arrPrintBlue($configUi);
        $buttonLabel = $configUi[$jenisTr]["steps"][1]['actionLabel'];
        if (sizeof($configUi[$this->jenisTr]['steps']) > 1) {
            $saveWarning = "clicking <strong>$buttonLabel</strong> button will make transaction state to: <strong class='badge bg-grey text-white'>" . $configUi[$this->jenisTr]['steps'][1]['stateLabel'] . "</strong>";
            $saveWarning .= "<br>It would need to be authorized by <strong class='text-blue'>" . $configUi[$this->jenisTr]['steps'][2]['userGroup'] . "</strong>";
        }
        else {
            $saveWarning = "clicking <strong>$buttonLabel</strong> button will instantly make transaction state to <strong class='text-blue'>" . $configUi[$this->jenisTr]['steps'][1]['stateLabel'] . "</strong>";
        }
        //endregion


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

        //

        //region prepare params to viewer

        $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), array_filter($_SESSION[$cCode]['main']));
        $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']));
        }

        //        arrPrint($mainAddValues);

        //==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;
                    }
                    //                    cekmerah($currentValue);
                    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");
                    }
                }

                if (array_key_exists($eName, $relOptionConfigs)) {
                    //					cekhijau("$eName terdaftar pada relInputs");


                    if (isset($relOptionConfigs[$eName][$currentValue])) {
                        if (sizeof($relOptionConfigs[$eName][$currentValue]) > 0) {
                            foreach ($relOptionConfigs[$eName][$currentValue] as $oValueName => $oValSpec) {
                                $inputLabels[$oValueName] = $oValSpec['label'];
                            }
                        }
                    }
                    else {
                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
                    }

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

        $itemLabels = $itemLabels + $itemNumLabels + array("subtotal" => "sub-amount");
        $itemLabels2 = $itemLabels2 + $itemNumLabels2 + array("subtotal" => "sub-amount");
        $itemLabels3 = $itemLabels3 + $itemNumLabels3 + array("subtotal" => "sub-amount");
        $itemSrcLabels = $itemSrcLabels + $itemSrcNumLabels + array("subtotal" => "sub-amount");
        if (isset($configUi[$this->jenisTr]['shoppingCartHideSubamount']) && $configUi[$this->jenisTr]['shoppingCartHideSubamount'][$stepNumber] == true) {
            unset($itemLabels['subtotal']);
            unset($itemLabels2['subtotal']);
            unset($itemLabels3['subtotal']);
        }

        //region tambah additional rows tampil
        $addRowLabels = array();
        if (sizeof($elementConfigs) > 0) {
            foreach ($elementConfigs as $eName => $eSpec) {
                if (array_key_exists($eName, $addRowsConfigs)) {
                    switch ($elementConfigs[$eName]['elementType']) {
                        case "dataModel":
                            $currentValue = isset($_SESSION[$cCode]['main_elements'][$eName]['key']) ? $_SESSION[$cCode]['main_elements'][$eName]['key'] : "";
                            break;
                        case "dataField":
                            $currentValue = $_SESSION[$cCode]['main_elements'][$eName]['value'];
                            break;
                    }
                    if (isset($addRowsConfigs[$eName][$currentValue])) {
                        if (sizeof($addRowsConfigs[$eName][$currentValue]) > 0) {

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


                                }

                            }

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

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

            }
        }
        //endregion


        //endregion

        // arrPrint($itemLabels);
        //arrPrint($addRowLabels);

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

        // cekHitam($configUi[$jenisTr]["template"]);
        // cekOrange($this->uri->segment_array());
        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'] : "";
        }

        $data = array(
            "mode" => $this->uri->segment(3),
            "template" => $configUi[$jenisTr]["template"],
            "title" => $configUi[$jenisTr]["label"],
            "subTitle" => $configUi[$jenisTr]["steps"][1]['label'],
            "jenisTr" => $jenisTr,
            "configUi" => $this->configUi,
            "pihakLabel" => $configUi[$jenisTr]["pihakLabel"],
            "itemLabels" => $itemLabels,
            "itemLabels2" => $itemLabels2,
            "itemLabels3" => $itemLabels3,
            "itemSrcLabels" => $itemSrcLabels,
            "noteEnabled" => $noteEnabled,
            "imageEnabled" => $imageEnabled,
            "main" => $main,
            "items" => $items,
            //            "items2" => $items2,
            "items2" => $$pairedItemTarget,
            "items3" => $items3_sum,
            "itemsSrc" => $itemsSrc,
            "buttonLabel" => $buttonLabel,
            "saveWarning" => $saveWarning,
            //            "sumRows" => $this->configLayout[$this->jenisTr]['receiptSumFields'][$stepNumber],
            "sumRows" => isset($configUi[$this->jenisTr]['shoppingCartSumFields'][1]) ? $configUi[$this->jenisTr]['shoppingCartSumFields'][1] : $this->configLayout[$this->jenisTr]['receiptSumFields'][1],
            "sumAddRows" => $addRowLabels,
            "sumRows3" => isset($configUi[$this->jenisTr]['shoppingCartSumFields3'][1]) ? $configUi[$this->jenisTr]['shoppingCartSumFields3'][1] : isset($this->configLayout[$this->jenisTr]['receiptSumFields3'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields3'][1] : array(),
            "extValueLabels" => isset($this->configCore[$this->jenisTr]['externalValues']) ? $this->configCore[$this->jenisTr]['externalValues'] : array(),
            //            "mainAddValues" => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
            "mainAddValues" => $mainAddValues,
            "mainAddFields" => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
            //            "mainApplets"    => isset($_SESSION[$cCode]['main_applets']) ? $_SESSION[$cCode]['main_applets'] : array(),
            "mainElements" => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
            "actionTarget" => base_url() . $this->modul . "/Create/save/" . $this->jenisTr . "?rawPrev=$rawPrevURL",
            "appletConfig" => $appletConfigs,
            "elementConfig" => $elementConfigs,
            "mainInputs" => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
            "grandTotal" => isset($_SESSION[$cCode]['main']['grand_total']) ? $_SESSION[$cCode]['main']['grand_total'] : 0,
            "headerRows" => isset($this->configLayout[$this->jenisTr]['receiptMainFields'][$stepNumber]) ? $this->configLayout[$this->jenisTr]['receiptMainFields'][$stepNumber] : array(),
            "description" => isset($_SESSION[$cCode]['main']['description']) ? $_SESSION[$cCode]['main']['description'] : "",
            "stepLabels" => $stepLabels,
            "currentStep" => 1,
            "pairedValue" => isset($_SESSION[$cCode]['pairs']) ? $_SESSION[$cCode]['pairs'] : array(),
        );

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

    public function save__()
    {
        //        echo "<script>top.writeProgress('MEMULAI PROSES SAVING....');</script>";

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

        // $this->jenisTr = $this->uri->segment(3);
        $cCode = $this->cCode;
        $configUi = $this->configUi;

        $relOptionConfigs = isset($configUi[$this->jenisTr]['relativeOptions']) ? $configUi[$this->jenisTr]['relativeOptions'] : array();
        $validationTableInMaster = isset($configUi[$this->jenisTr]['validationTableInMaster']) ? $configUi[$this->jenisTr]['validationTableInMaster'] : false;
        $inputLabels = array();
        $inputAuthConfigs = array();

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

        $rawPrevURL = isset($_GET['rawPrev']) ? $_GET['rawPrev'] : "";
        $prevUrl = blobDecode($rawPrevURL);
        $mongoList = array();
        $mongRegID = array();

        /* ----------------------------------------------------------
         * SAVE:: kerjannya disini
         * ----------------------------------------------------------*/
        if (isset($_SESSION[$cCode])) {
            //            arrPRint($_SESSION[$cCode]['items']);
            if (!isset($_SESSION[$cCode]['items'])) {
                die("belum ada item yang dipilih");
            }
            else {
                if (sizeof($_SESSION[$cCode]['items']) < 1) {
                    die("belum ada item yang dipilih");
                }
            }
            echo("now processing your transaction..<br>");


            //region build table rekening
            //            $buildTablesMaster = isset($this->configCore[$this->jenisTr]['components'][1]['master']) ? $this->configCore[$this->jenisTr]['components'][1]['master'] : array();
            if (isset($_SESSION[$cCode]['componentsBuilder'][1]['master'])) {
                $buildTablesMaster = $_SESSION[$cCode]['componentsBuilder'][1]['master'];
            }
            elseif (isset($this->configCore[$this->jenisTr]['components'][1]['master'])) {
                $buildTablesMaster = $this->configCore[$this->jenisTr]['components'][1]['master'];
            }
            else {
                $buildTablesMaster = array();
            }
            //---------------------------------------
            //            $buildTablesDetail = isset($this->configCore[$this->jenisTr]['components'][1]['detail']) ? $this->configCore[$this->jenisTr]['components'][1]['detail'] : array();
            if (isset($_SESSION[$cCode]['componentsBuilder'][1]['detail'])) {
                $buildTablesDetail = $_SESSION[$cCode]['componentsBuilder'][1]['detail'];
            }
            elseif (isset($this->configCore[$this->jenisTr]['components'][1]['detail'])) {
                $buildTablesDetail = $this->configCore[$this->jenisTr]['components'][1]['detail'];
            }
            else {
                $buildTablesDetail = array();
            }


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

                    $bCtr++;
                    $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;

                    $this->load->model("Coms/" . $mdlName);
                    $m = new $mdlName();


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


                    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) {
                        //arrPrint($itemSpec);
                        $mdlName = $buildTablesDetail_specs['comName'];
                        cekLime($mdlName);
                        if (substr($mdlName, 0, 1) == "{") {
                            $mdlName = trim($mdlName, "{");
                            $mdlName = trim($mdlName, "}");
                            $mdlName = str_replace($mdlName, $itemSpec[$mdlName], $mdlName);
                            //                        $mdlName = str_replace($mdlName, $_SESSION[$cCode]['main'][$mdlName], $mdlName);
                        }
                        $mdlName = "Com" . $mdlName;
                        cekbiru("model: $mdlName");
                        $this->load->model("Coms/" . $mdlName);
                        $m = new $mdlName();

                        if (isset($buildTablesDetail_specs['loop']) && sizeof($buildTablesDetail_specs['loop']) > 0) {
                            foreach ($buildTablesDetail_specs['loop'] as $key => $val) {
                                if (substr($key, 0, 1) == "{") {
                                    $oldParam = $buildTablesDetail_specs['loop'][$key];
                                    unset($buildTablesDetail_specs['loop'][$key]);
                                    $key = trim($key, "{");
                                    $key = trim($key, "}");
                                    $key = str_replace($key, $itemSpec[$key], $key);
                                    //                                    $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
                                    $buildTablesDetail_specs['loop'][$key] = $oldParam;
                                }
                            }
                        }
                        if (method_exists($m, "getTableNameMaster")) {
                            if (sizeof($m->getTableNameMaster())) {
                                $m->buildTables($buildTablesDetail_specs);
                            }
                        }
                    }
                }
            }
            //endregion

            $this->db->trans_start();

            //region pre-processors (master)
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['preProc']['master']) ? $_SESSION[$cCode]['revert']['preProc']['master'] : array();
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][1]['master']) ? $this->configCore[$this->jenisTr]['preProcessor'][1]['master'] : array();
            }
            //            if (isset($this->configCore[$this->jenisTr]['preProcessor'][1]['master'])) {
            if (sizeof($iterator) > 0) {
                //                $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][1]['master']) ? $this->configCore[$this->jenisTr]['preProcessor'][1]['master'] : array();
                $itemNumLabels = isset($configUi[$this->jenisTr]['shoppingCartNumFields']) ? $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();
                        $subParams = array();

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

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

                            }

                            if (!isset($subParams['static']["transaksi_id"])) {
                                //									$subParams['static']["transaksi_id"] = $masterID;
                            }

                            $subParams['static']["fulldate"] = date("Y-m-d");
                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                            $subParams['static']["keterangan"] = $configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'];
                        }
                        $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(0, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $gotParams = $m->exec();

                            cekbiru("gotparams dari pre-proc $comName");
                            arrprint($gotParams);

                            if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                                foreach ($gotParams as $gateName => $gSpec) {
                                    //										$id=$gSpec['id'];
                                    if (isset($_SESSION[$cCode]['main'])) {
                                        if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                            foreach ($gSpec as $key => $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;
                                            }
                                        }
                                    }
                                    //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]['main'][$key])) {
                                                $_SESSION[$cCode]['main']['sub_' . $key] = ($_SESSION[$cCode]['main']['jml'] * $_SESSION[$cCode]['main'][$key]);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                        }
                    }
                }
                else {
                    //cekKuning("sub-preproc is not set");
                }
                $this->load->helper("he_value_builder");
                fillValues($this->jenisTr, 1, 1);
            }
            else {
                echo("no processor defined. skipping preprocessor..<br>");
            }
            //endregion

            //matiHere();
            //
            //region pre-processors (item)
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['preProc']['detail']) ? $_SESSION[$cCode]['revert']['preProc']['detail'] : array();
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][1]['detail']) ? $this->configCore[$this->jenisTr]['preProcessor'][1]['detail'] : array();
            }
            //            if (isset($this->configCore[$this->jenisTr]['preProcessor'][1]['detail'])) {
            if (sizeof($iterator) > 0) {
                //                $procList = $this->configCore[$this->jenisTr]['preProcessor'][1];

                //                $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][1]['detail']) ? $this->configCore[$this->jenisTr]['preProcessor'][1]['detail'] : array();
                $itemNumLabels = isset($configUi[$this->jenisTr]['shoppingCartNumFields']) ? $configUi[$this->jenisTr]['shoppingCartNumFields'] : array();
                echo "ITEM NUM LABELS";

                if (sizeof($iterator) > 0) {
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];

                        echo "sub-preproc: $comName, initializing values <br>";
                        //arrprint($_SESSION[$cCode][$srcGateName]);
                        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($subParams['static']["transaksi_id"])) {
                                    //									$subParams['static']["transaksi_id"] = $masterID;
                                }


                                $subParams['static']["fulldate"] = date("Y-m-d");
                                $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                $subParams['static']["keterangan"] = $configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'];
                            }
                            cekLime(":: cetak preprocc... $comName :: $srcGateName ::");
                            arrPrint($subParams);
                            //mati_disini();
                            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(0, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                    $gotParams = $m->exec();

                                    cekmerah("gotparams dari pre-proc $comName");
                                    arrprint($gotParams);


                                    if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor

                                        foreach ($gotParams as $gateName => $paramSpec) {
                                            cekBiru(":: getParams inject ke $gateName ::");
                                            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) {
                                                            cekHere(":: injecte ke $gateName, ::: $key diisi dengan $val");
                                                            $_SESSION[$cCode][$gateName][$id][$key] = $val;
                                                        }

                                                    }
                                                }
                                                //==inject gotParams to child gate
                                                cekHitam("srcGateName = $srcGateName :: " . __LINE__);
                                                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");
                                                        if (isset($_SESSION[$cCode][$gateName][$id][$key])) {
                                                            $_SESSION[$cCode][$gateName][$id]['sub_' . $key] = ($_SESSION[$cCode][$gateName][$id]['jml'] * $_SESSION[$cCode][$gateName][$id][$key]);
                                                        }
                                                        //                                        die();
                                                    }
                                                }
                                            }
                                            //                                    arrPrint($items);die();
                                        }


                                    }

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


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


                $this->load->helper("he_value_builder");
                fillValues($this->jenisTr, 1, 1);
                //region injector gerbang value untuk pembatalan ppv dan selisih
                if (isset($_SESSION[$cCode]["revert"]["preProc"]["replacer"])) {
                    $replace = $_SESSION[$cCode]["revert"]["preProc"]["replacer"];
                    //                    $mainVAl = $_SESSION[$cCode]["main"]["hpp"];
                    //                    $indexVal =$_SESSION[$cCode]["main"]["ppv_index__nilai"];
                    //                    $valRiil = $mainVAl/$indexVal;
                    //                    $ppv_nilai = $mainVAl-$valRiil;
                    $tempCalculate = array(
                        "selisih" => ($_SESSION[$cCode]["main"]["hpp"] + $_SESSION[$cCode]["main"]["ppn"]) - ($_SESSION[$cCode]["main"]["nett"] + $_SESSION[$cCode]["main"]["ppv"]),
                        "hpp_nppv" => $_SESSION[$cCode]["main"]["hpp"],
                        "hpp_nppn" => $_SESSION[$cCode]["main"]["hpp"] + $_SESSION[$cCode]["main"]["ppn"],
                    );

                    foreach ($replace['recalculate'] as $iKey => $gate) {
                        $_SESSION[$cCode]["main"][$gate] = $tempCalculate[$gate];
                    }

                    CekLime($_SESSION[$cCode]["main"]["hpp"] . "+" . $_SESSION[$cCode]["main"]["ppn"] . "-" . $_SESSION[$cCode]["main"]["nett"]);
                    //                    CekLime($mainVAl."-".$ppv_nilai."=".$ppv_nilai);

                }

                //endregion

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


            $this->load->library("Validator");
            $vd = new Validator();
            $vd->setCCode($this->cCode);
            $vd->setConfigUiJenis($this->configUiJenis);
            $step = $_SESSION[$cCode]['main']['step_number'];

            $vd->midValidate($step);
            // matiHere("under maintenance" . __LINE__);
            $vd->unionValidate();
            cekOrange("lolos validator @" . __LINE__ . " " . __METHOD__);

            // matiHere("under maintenance" . __LINE__);
            //===finalisasi sebelum masuk tabel beneran
            //===isinya ada pembentukan nomor nota dll
            cekHitam("cek line:: " . __LINE__);
            //
            //region penomoran receipt
            //<editor-fold desc="==========penomoran">
            $this->load->model("CustomCounter");
            $cn = new CustomCounter("transaksi");
            $cn->setType("transaksi");

            $counterForNumber = array($this->configCore[$this->jenisTr]['formatNota']);
            if (!in_array($counterForNumber[0], $this->configCore[$this->jenisTr]['counters'])) {
                die(__LINE__ . " Used number should be registered in 'counters' config as well");
            }
            echo "<div style='background:#ff7766;'>";
            foreach ($counterForNumber as $i => $cRawParams) {
                $cParams = explode("|", $cRawParams);
                $cValues = array();
                foreach ($cParams as $param) {
                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                }
                $cRawValues = implode("|", $cValues[$i]);
                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

            }
            echo "</div style='background:#ff7766;'>";

            $stepNumber = 1;

            $tmpNomorNota = $paramSpec['paramString'];


            if (isset($configUi[$this->jenisTr]['steps'][2])) {
                $nextProp = array(
                    "num" => 2,
                    "code" => $configUi[$this->jenisTr]['steps'][2]['target'],
                    "label" => $configUi[$this->jenisTr]['steps'][2]['label'],
                    "groupID" => $configUi[$this->jenisTr]['steps'][2]['userGroup'],
                );
            }
            else {
                $nextProp = array(
                    "num" => 0,
                    "code" => "",
                    "label" => "",
                    "groupID" => "",
                );
            }

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

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

            //
            //region addition on master


            $addValues = array(
                'counters' => $appliedCounters,
                'counters_intext' => $appliedCounters_inText,
                'nomer' => $tmpNomorNota,
                'dtime' => date("Y-m-d H:i:s"),
                'fulldate' => date("Y-m-d"),
                "step_avail" => sizeof($configUi[$this->jenisTr]['steps']),
                "step_number" => 1,
                "step_current" => 1,
                "next_step_num" => $nextProp['num'],
                "next_step_code" => $nextProp['code'],
                "next_step_label" => $nextProp['label'],
                "next_group_code" => $nextProp['groupID'],
                "tail_number" => 1,
                "tail_code" => $configUi[$this->jenisTr]['steps'][1]['target'],


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

            //
            //region addition on detail
            $addSubValues = array(
                "sub_step_number" => 1,
                "sub_step_current" => 1,
                "sub_step_avail" => sizeof($configUi[$this->jenisTr]['steps']),
                "next_substep_num" => $nextProp['num'],
                "next_substep_code" => $nextProp['code'],
                "next_substep_label" => $nextProp['label'],
                "next_subgroup_code" => $nextProp['groupID'],
                "sub_tail_number" => 1,
                "sub_tail_code" => $configUi[$this->jenisTr]['steps'][1]['target'],


            );
            foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                foreach ($addSubValues as $key => $val) {
                    $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                }
            }
            //endregion
            // </editor-fold>
            //endregion


            //
            //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
            if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {

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


                $this->load->model("MdlTransaksi");
                $tr = new MdlTransaksi();
                $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                showLast_query("lime");
                $epID = $tr->writeMainEntries_entryPoint($insertID, $insertID, $_SESSION[$cCode]['tableIn_master']);
                $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                if ($insertID < 1) {
                    die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                }
                $mongoList['main'] = array($insertID,
                    $epID
                );
                //==transaksi_id dan nomor nota diinject kan ke gate utama
                $injectors = array(
                    "transaksi_id" => $insertID,
                    "nomer" => $tmpNomorNota,
                );
                $arrInjectorsTarget = array(
                    "items",
                    "items2_sum",
                    "rsltItems",
                );
                foreach ($injectors as $key => $val) {
                    $_SESSION[$cCode]['main'][$key] = $val;
                    foreach ($arrInjectorsTarget as $target) {
                        if (isset($_SESSION[$cCode][$target])) {
                            foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                if (isset($_SESSION[$cCode][$target][$id])) {
                                    $_SESSION[$cCode][$target][$id][$key] = $val;
                                }
                            }
                        }
                    }
                }

                //===signature
                $dwsign = $tr->writeSignature($insertID, array(
                    "nomer" => $_SESSION[$cCode]['main']['nomer'],
                    "step_number" => 1,
                    "step_code" => $this->jenisTr,
                    "step_name" => $configUi[$this->jenisTr]['steps'][1]['label'],
                    "group_code" => $configUi[$this->jenisTr]['steps'][1]['userGroup'],
                    "oleh_id" => $this->session->login['id'],
                    "oleh_nama" => $this->session->login['nama'],
                    "keterangan" => $configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                    "transaksi_id" => $insertID,
                )) or die("Failed to write signature");
                $mongoList['sign'][] = $dwsign;
                $idHis = array(
                    $stepNumber => array(
                        "olehID" => $_SESSION[$cCode]['main']['olehID'],
                        "olehName" => $_SESSION[$cCode]['main']['olehName'],
                        "step" => $stepNumber,
                        "trID" => $insertID,
                        "nomer" => $tmpNomorNota,
                        "counters" => $appliedCounters,
                        "counters_intext" => $appliedCounters_inText,
                    ),
                );
                $idHis_blob = blobEncode($idHis);
                $idHis_intext = print_r($idHis, true);
                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array("id" => $insertID), array(
                    "next_step_num" => $nextProp['num'],
                    "next_step_code" => $nextProp['code'],
                    "next_step_label" => $nextProp['label'],
                    "next_group_code" => $nextProp['groupID'],

                    //===references
                    "id_master" => $insertID,
                    "id_top" => $insertID,
                    "ids_prev" => "",
                    "ids_prev_intext" => "",
                    "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                    "nomers_prev" => "",
                    "nomers_prev_intext" => "",
                    "jenises_prev" => "",
                    "jenises_prev_intext" => "",
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

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

                $addValues = array(
                    //===references
                    "id_master" => $insertID,
                    "id_top" => $insertID,
                    "ids_prev" => "",
                    "ids_prev_intext" => "",
                    "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                    "nomers_prev" => "",
                    "nomers_prev_intext" => "",
                    "jenises_prev" => "",
                    "jenises_prev_intext" => "",
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,
                );
                foreach ($addValues as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }

            }
            if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                $inserMainValues = array();
                if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                    //matiHEre("hooppp");
                    $inserMainValues = array();
                    foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                        if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                            $dd = $tr->writeMainValues($insertID, array(
                                "key" => $key,
                                "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                            ));

                            $inserMainValues[] = $dd;
                            $mongoList['mainValues'][] = $dd;
                        }
                    }
                }

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

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

                if (sizeof($inserMainValues) > 0) {
                    $arrBlob = blobEncode($inserMainValues);
                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                    $tr->writeMainValues($insertID, array("key" => $key,
                        "value" => $val
                    ));
                    //                    cekkuning("making a clone for input key $key / $val");
                    //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                    //                    $replacers=array(
                    //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                    //                    );
                    //                    foreach($replacers as $key=>$val){
                    //                        $tmpTableIn[$key]=$val;
                    //                    }
                    //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                }
            }
            if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                    $tr->writeMainFields($insertID, array("key" => $key,
                        "value" => $val
                    ));
                }
            }
            if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                    $tr->writeMainApplets($insertID, array(
                        "mdl_name" => $amdl,
                        "key" => $aSpec['key'],
                        "label" => $aSpec['labelValue'],
                        "description" => $aSpec['description'],
                    ));
                }
            }
            if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                    $tr->writeMainElements($insertID, array(
                        "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                        "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                        "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                        "name" => $aSpec['name'],
                        "label" => $aSpec['label'],
                        "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                        "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                    ));


                    //==nebeng bikin inputLabels
                    $currentValue = "";
                    switch ($aSpec['elementType']) {
                        case "dataModel":
                            $currentValue = $aSpec['key'];
                            break;
                        case "dataField":
                            $currentValue = $aSpec['value'];
                            break;
                    }
                    if (array_key_exists($elName, $relOptionConfigs)) {
                        //					cekhijau("$eName terdaftar pada relInputs");


                        if (isset($relOptionConfigs[$elName][$currentValue])) {
                            if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
                                foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
                                    $inputLabels[$oValueName] = $oValSpec['label'];
                                    if (isset($oValSpec['auth'])) {
                                        if (isset($oValSpec['auth']['groupID'])) {
                                            $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
                        }

                    }

                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

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


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

                    foreach ($indexing_details as $k => $arrID) {
                        $arrBlob = blobEncode($arrID);
                        $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                        cekOrange($this->db->last_query());
                    }
                }
            }
            else {
                die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
            }
            if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                    $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                    $mongoList['detail'] = $insertIDs;
                    if ($epID != 999) {
                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                        $mongoList['detail'] = $insertIDs;
                    }
                    cekUngu($this->db->last_query());
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $insertDetailID;
                    $mongoList['detail'][] = $insertDetailID;
                    if ($epID != 999) {
                        $dd = $tr->writeDetailEntries($epID, $dSpec);
                        $insertIDs[] = $dd;
                        $mongoList['detail'][] = $dd;
                    }
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                    $dd = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $dd;
                    $mongoList['detail'][] = $dd;
                    if ($epID != 999) {
                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                        $mongoList['detail'] = $insertIDs;
                    }
                    cekUngu($this->db->last_query());
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

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

                            }
                        }
                    }
                }

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

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

            cekHitam("cek line:: " . __LINE__);
            //===components akan langsung dieksekusi jika steps-nya tidak pakai approval
            $steps = $configUi[$this->jenisTr]['steps'];

            //region processing sub-components, if in single step geser ke CLI

            $componentGate['detail'] = array();
            $componentConfig['detail'] = array();
            //            //==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();
            $filterNeeded = false;
            $comsLocation = isset($this->configCore[$this->jenisTr]['componentsLocation']['detail']) ? $this->configCore[$this->jenisTr]['componentsLocation']['detail'] : "Coms";
            $comsPrefix = isset($this->configCore[$this->jenisTr]['componentsPrefix']['detail']) ? $this->configCore[$this->jenisTr]['componentsPrefix']['detail'] : "Com";
            $componentsDetailLoop = isset($this->configCore[$this->jenisTr]['componentsDetailLoop']) ? $this->configCore[$this->jenisTr]['componentsDetailLoop'] : true;


            //region processing sub-components
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['jurnal']['detail']) ? $_SESSION[$cCode]['revert']['jurnal']['detail'] : array();
                $revertedTarget = $_SESSION[$cCode]['main']['pihakExternID'];
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['components'][1]['detail']) ? $this->configCore[$this->jenisTr]['components'][1]['detail'] : array();
                $revertedTarget = "";
            }
            $componentConfig['detail'] = $iterator;
            //            //region processing sub-components
            //            if (sizeof($iterator) > 0) {
            //                foreach ($iterator as $cCtr => $tComSpec) {
            //                    $tmpOutParams[$cCtr] = array();
            //                    $gg = 0;
            //                    $srcGateName = $tComSpec['srcGateName'];
            //                    foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
            //                        $srcRawGateName = $tComSpec['srcRawGateName'];
            //                        $comName = $tComSpec['comName'];
            //                        if (substr($comName, 0, 1) == "{") {
            //                            $comName = trim($comName, "{");
            //                            $comName = trim($comName, "}");
            //                            //                            $comName = str_replace($comName, $_SESSION[$cCode]['main'][$comName], $comName);
            //                            cekLime($cCode . " || " . $srcGateName . " || " . $id . " || " . $comName);
            //                            $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
            //                        }
            //                        cekHitam(":: $comName ::");
            //                        $mdlName = "Com" . ucfirst($comName);
            //                        if (in_array($mdlName, $compValidators)) {//perlu validasi filter
            ////cekLime($mdlName. "line");
            //                            $filterNeeded = true;
            //                        }
            //                        else {
            //                            cekLime($mdlName . "like");
            //                            $filterNeeded = false;
            //                        }
            //                        echo "sub-component: $comName, initializing values <br>";
            //                        //                        cekHitam(__LINE__);
            //                        //                        $tmpOutParams[$cCtr] = array();
            //
            //                        //                        cekhitam("$comName filterneeded: $filterNeeded");
            //                        //                        cekhitam("mau mengiterasi $srcGateName");
            //                        //                        cekhitam("telah mengiterasi $srcGateName");
            //                        //
            //                        $subParams = array();
            ////arrPrint($tComSpec);
            //                        if (isset($tComSpec['loop'])) {
            //                            foreach ($tComSpec['loop'] as $key => $value) {
            //                                cekMerah(":: $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][$id][$key], $key);
            //                                }
            //
            //                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
            //                                $subParams['loop'][$key] = $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;
            //
            //                            }
            //                            if (!isset($subParams['static']["transaksi_id"])) {
            //                                $subParams['static']["transaksi_id"] = $insertID;
            //                            }
            //                            if (!isset($subParams['static']["transaksi_no"])) {
            //                                $subParams['static']["transaksi_no"] = $insertNum;
            //                            }
            //
            //                            $subParams['static']["fulldate"] = date("Y-m-d");
            //                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
            //                            $subParams['static']["keterangan"] = $configUi[$this->jenisTr]['steps'][1]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
            //                            if (strlen($revertedTarget) > 1) {
            //                                $subParams['static']['reverted_target'] = $revertedTarget;
            //                            }
            //                        }
            //                        //arrPrint($subParams);
            //                        if (sizeof($subParams) > 0) {
            ////                            arrprint($subParams);
            //                            cekhitam("subparam ada isinya");
            //                            if ($filterNeeded) {
            //                                if (isset($subParams['loop']) && sizeof($subParams['loop']) > 0) {
            //                                    $tmpOutParams[$cCtr][] = $subParams;
            //                                }
            //                            }
            //                            else {
            //                                $tmpOutParams[$cCtr][] = $subParams;
            ////                                CekHijiau("asem" .$gg++);
            //                            }
            //                        }
            //                        else {
            //                            cekhitam("subparam TIDAK ada isinya");
            //                        }
            //                    }
            //
            //                    $componentGate['detail'][$cCtr] = $subParams;
            //                }
            //                //cekHitam("cetak tmpOutParams");
            //
            //                foreach ($iterator as $cCtr => $tComSpec) {
            //                    $srcGateName = $tComSpec['srcGateName'];
            //                    foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
            //
            //                        $srcRawGateName = $tComSpec['srcRawGateName'];
            //                        $comName = $tComSpec['comName'];
            //                        if (substr($comName, 0, 1) == "{") {
            //                            $comName = trim($comName, "{");
            //                            $comName = trim($comName, "}");
            //                            $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
            //                            //                        $comName = str_replace($comName, $_SESSION[$cCode]['main'][$comName], $comName);
            //                        }
            //                    }
            //                    echo "sub component: $comName, sending values <br>";
            //
            //                    $mdlName = "Com" . ucfirst($comName);
            //                    $this->load->model("Coms/" . $mdlName);
            //                    $m = new $mdlName();
            //                    //===filter value nol, jika harus difilter
            ////                    arrPrint($tmpOutParams[$cCtr]);
            //                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
            //                        $tobeExecuted = true;
            //                    }
            //                    else {
            //                        $tobeExecuted = false;
            //                    }
            //
            //                    if ($tobeExecuted) {
            //                        cekMerah("$comName dieksekusiii");
            //                        arrPrint($tmpOutParams[$cCtr]);
            //                        $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__);
            //                        cekBiru($this->db->last_query());
            //                    }
            //                    else {
            //                        cekMerah("$comName tidak eksekusi");
            //                    }
            //
            //                }
            //            }
            //            else {
            //                //cekKuning("subcomponents is not set");
            //            }
            //            //endregion
            //endregion

            //region processing main components, if in single step

            $componentGate['master'] = array();
            $componentConfig['master'] = array();
            //==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();
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['jurnal']['master']) ? $_SESSION[$cCode]['revert']['jurnal']['master'] : array();
            }
            else {

                if (isset($_SESSION[$cCode]['componentsBuilder'][1]['master'])) {
                    $iterator = $_SESSION[$cCode]['componentsBuilder'][1]['master'];
                }
                elseif (isset($this->configCore[$this->jenisTr]['components'][1]['master'])) {
                    $iterator = $this->configCore[$this->jenisTr]['components'][1]['master'];
                }
                else {
                    $iterator = array();
                }
            }

            if (sizeof($iterator) > 0) {
                $componentConfig['master'] = $iterator;
                $cCtr = 0;
                foreach ($iterator as $cCtr => $tComSpec) {
                    $cCtr++;
                    $comName = $tComSpec['comName'];
                    if (substr($comName, 0, 1) == "{") {
                        $comName = trim($comName, "{");
                        $comName = trim($comName, "}");
                        $comName = str_replace($comName, $_SESSION[$cCode]['main'][$comName], $comName);
                    }
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo "component # $cCtr: $comName<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);
                            }

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                            $tmpOutParams['loop'][$key] = $realValue;
                            //                            cekKuning("LOOP $key diisi dengan $realValue");
                        }
                    }
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

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

                        }
                        if (!isset($tmpOutParams['static']["transaksi_id"])) {
                            $tmpOutParams['static']["transaksi_id"] = $insertID;
                        }
                        if (!isset($tmpOutParams['static']["transaksi_no"])) {
                            $tmpOutParams['static']["transaksi_no"] = $insertNum;
                        }
                        $tmpOutParams['static']["urut"] = $cCtr;
                        $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                        $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $tmpOutParams['static']["keterangan"] = $configUi[$this->jenisTr]['steps'][1]['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($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"] = $configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                    }


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

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


            //endregion

            //            mati_disini(":: AFTER MAIN COMPONENT ::");


            //region processing sub-post-processors, always
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['postProc']['detail']) ? $_SESSION[$cCode]['revert']['postProc']['detail'] : array();
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][1]['detail']) ? $this->configCore[$this->jenisTr]['postProcessor'][1]['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>";
                    $tmpOutParams[$cCtr] = array();
                    foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                        $id = $dSpec['id'];
                        $subParams = array();
                        if (isset($tComSpec['loop'])) {
                            foreach ($tComSpec['loop'] as $key => $value) {

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

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

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

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

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

                        $mdlName = "Com" . ucfirst($comName);

                        $perubahanComs[] = $comName;
                        cekBiru($mdlName);
                        // cekBiru($tComSpec);

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

                }
            }
            //endregion
            echo "-------------------------" . __LINE__ . "<hr>";

            //region relesaese connected payment source dan marking trash transaksi
            //            arrPrint($_SESSION[$cCode]["revert"]);
            if (isset($_SESSION[$cCode]["revert"]["connectedPaymentsource"]) && $_SESSION[$cCode]["revert"]["connectedPaymentsource"] == true) {
                $keyRel = $_SESSION[$cCode]["main"]["referenceID"];
                $keyRelRef = $_SESSION[$cCode]["main"]["pihakExternID"];
                $relPaymentSrc = isset($this->config->item("payment_source")[$keyRelRef]) ? $this->config->item("payment_source")[$keyRelRef] : array();
                if (sizeof($relPaymentSrc) > 0) {
                    $this->load->model("Mdls/MdlPaymentSource");
                    $m = new MdlPaymentSource();
                    $m->addFilter("transaksi_id='$keyRel'");
                    $tmpRelPay = $m->lookupAll()->result();
                    $paymentRelUsed = array(
                        "cabang_id" => "placeID",
                        "extern_id" => "id",
                        "extern_nama" => "name",
                        "label" => ".hutang biaya",
                        "target_jenis" => "jenisTr",
                        "transaksi_id" => "refID",
                        "terbayar" => "nilai_bayar",
                        "sisa" => "new_sisa",
                        "ppn" => "valid_ppn",
                        "extern_nilai2" => "valid_dpp",
                    );
                    if (sizeof($tmpRelPay) > 0) {
                        $tmpOutParams = array();
                        $iterator = array();
                        foreach ($tmpRelPay as $indexKey => $relData) {
                            $tmp = array();
                            foreach ($paymentRelUsed as $key => $keyGate) {
                                if ($key == "terbayar") {
                                    $val = $relData->sisa;
                                }
                                else {
                                    if ($key == "sisa") {
                                        $val = "-" . $relData->sisa;
                                    }
                                    else {
                                        $val = $relData->$key;
                                    }
                                }
                                $tmp["static"][$key] = $val;
                                $tmp["static"]["keterangan"] = $configUi[$this->jenisTr]['steps'][1]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];

                            }
                            $iterator[$indexKey]["loop"] = array();
                            $iterator[$indexKey]["comName"] = "PaymentSrcItem";
                            if (sizeof($tmp) > 0) {
                                $tmpOutParams[$indexKey][] = $tmp;
                            }
                        }
                        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__);
                            //                            cekHitam($this->db->last_query());
                        }
                    }
                    //                    foreach()
                    cekLime("yuk direset paymentsource**");
                }


            }
            //endregion

            //region processing main-post-processors, always
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['postProc']['detail']) ? $_SESSION[$cCode]['revert']['postProc']['master'] : array();
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][1]['master']) ? $this->configCore[$this->jenisTr]['postProcessor'][1]['master'] : array();
            }
            //            $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][1]['master']) ? $this->configCore[$this->jenisTr]['postProcessor'][1]['master'] : array();
            if (sizeof($iterator) > 0) {
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo "post-processor: $comName<br>LINE: " . __LINE__;

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

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

                        }
                    }
                    if (isset($tComSpec['static'])) {
                        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"] = $configUi[$this->jenisTr]['steps'][1]['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($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"] = $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__);


                }
            }
            else {

            }
            //endregion

            //region updater main transaksi rejection jurnal next step exist
            $mongUpdateList = array();
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {

                $tr->setFilters(array());
                $tr->addFilter("id='" . $_SESSION[$cCode]["main"]["referenceID"] . "'");
                $tempData = $tr->lookupAll()->result();
                $refMasterID = $tempData[0]->id_master;
                $refMasterJenis = $tempData[0]->jenis_master;
                $nextStepCode = $tempData[0]->next_step_code;
                $mainStepCode = $tempData[0]->jenis;
                $stepnum = $tempData[0]->step_number;
                $stepnumAvail = $tempData[0]->step_avail;
                if (($stepnumAvail - $stepnum) > 0) {
                    //                    matiHere("masukk".$nextStepCode);
                    $this->load->model("Coms/ComTransaksi_jurnal_revert");
                    $r = new ComTransaksi_jurnal_revert();
                    $outParams = array(
                        "refID" => $refMasterID,
                        "main_code" => $mainStepCode,
                        "next_code" => $nextStepCode,
                        "step_num" => $stepnum,
                    );
                    $r->pair($outParams) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $r->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);

                    //marking main transaksi trash4
                    $udpate = array(
                        "trash_4" => "1",
                    );
                    $tr->setFilters(array());
                    //                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array(
                        //                "id" => $no,
                        "id" => $_SESSION[$cCode]["main"]["referenceID"],
                    ), $udpate) or die("Failed to update tr next-state!");
                    $mongUpdateList['update']['main'][] = array(
                        "where" => array("id" => $_SESSION[$cCode]["main"]["referenceID"]),
                        "value" => array(
                            "trash_4" => "1",
                        ),
                    );
                    cekHijau("UPDATE transaksi step sebelumnya...");
                    cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    //update validqty 0 supaya gak bisa difollowup
                    //                    $arrData_detail["valid_qty"] = 0;
                    $td = new MdlTransaksi();
                    $td->setFilters(array());
                    $rslt = $td->lookupJoinedByID($_SESSION[$cCode]["main"]["referenceID"])->result();
                    if (sizeof($rslt) > 0) {
                        foreach ($rslt as $rsltSpec) {
                            if (array_key_exists($rsltSpec->produk_id, $_SESSION[$cCode]["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'];
                                //                                }
                                $arrData_detail["valid_qty"] = 0;
                                $tr = new MdlTransaksi();
                                $tr->setFilters(array());
                                $tr->setTableName($tr->getTableNames()['detail']);
                                $dupState = $tr->updateData(array(
                                    "transaksi_id" => $_SESSION[$cCode]["main"]["referenceID"],
                                    "produk_id" => $rsltSpec->produk_id,
                                ), $arrData_detail) or die("Failed to update tr next-state!");
                                $mongUpdateList['update']['detail'][] = array(
                                    "where" => array(
                                        "transaksi_id" => $_SESSION[$cCode]["main"]["referenceID"],
                                        "produk_id" => $rsltSpec->produk_id,
                                    ),
                                    "value" => $arrData_detail,
                                );
                                cekKuning("UPDATE transaksi data...");
                                cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                            }
                        }
                    }

                    $dwsign = $tr->writeSignature($refMasterID, array(
                        "prev_id" => "",
                        "nomer" => "pembatalan jurnal",
                        "step_number" => "-" . $stepnum,
                        // ini minus step number
                        "step_code" => $configUi[$refMasterJenis]['steps'][abs($stepnum)]['target'],
                        "step_name" => $configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'],
                        "group_code" => $configUi[$refMasterJenis]['steps'][abs($stepnum)]['userGroup'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "keterangan" => $configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'] . " oleh " . $this->session->login['nama'],
                        //            "transaksi_id" => $no,
                    )) or die("Failed to write signature");
                    $mongoList['sign'][] = $dwsign;
                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                    //                    matiHere();
                }
                else {

                    //marking main transaksi trash4
                    $udpate = array(
                        "trash_4" => "1",
                    );
                    $tr->setFilters(array());
                    //                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array(
                        //                "id" => $no,
                        "id" => $_SESSION[$cCode]["main"]["referenceID"],
                    ), $udpate) or die("Failed to update tr next-state!");
                    cekHijau("UPDATE transaksi step sebelumnya...");
                    cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                    $mongUpdateList['update']['main'][] = array(
                        "where" => array("id" => $_SESSION[$cCode]["main"]["referenceID"]),
                        "value" => array(
                            "trash_4" => "1",
                        ),
                    );

                    //update validqty 0 supaya gak bisa difollowup
                    $arrData_detail["valid_qty"] = $new_valid_qty;
                    $td = new MdlTransaksi();
                    $td->setFilters(array());
                    $rslt = $td->lookupJoinedByID($_SESSION[$cCode]["main"]["referenceID"])->result();
                    if (sizeof($rslt) > 0) {
                        foreach ($rslt as $rsltSpec) {
                            if (array_key_exists($rsltSpec->produk_id, $_SESSION[$cCode]["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'];
                                //                                }
                                $arrData_detail["valid_qty"] = 0;
                                $tr = new MdlTransaksi();
                                $tr->setFilters(array());
                                $tr->setTableName($tr->getTableNames()['detail']);
                                $dupState = $tr->updateData(array(
                                    "transaksi_id" => $_SESSION[$cCode]["main"]["referenceID"],
                                    "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() . "]");
                                $mongUpdateList['update']['detail'][] = array(
                                    "where" => array(
                                        "transaksi_id" => $_SESSION[$cCode]["main"]["referenceID"],
                                        "produk_id" => $rsltSpec->produk_id,
                                    ),
                                    "value" => $arrData_detail,
                                );
                            }
                        }
                    }

                    $dwsign = $tr->writeSignature($refMasterID, array(
                        "prev_id" => "",
                        "nomer" => "pembatalan jurnal",
                        "step_number" => "-" . $stepnum,
                        // ini minus step number
                        "step_code" => $configUi[$refMasterJenis]['steps'][abs($stepnum)]['target'],
                        "step_name" => $configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'],
                        "group_code" => $configUi[$refMasterJenis]['steps'][abs($stepnum)]['userGroup'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "keterangan" => $configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'] . " oleh " . $this->session->login['nama'],
                        //            "transaksi_id" => $no,
                    )) or die("Failed to write signature");
                    $mongoList['sign'][] = $dwsign;
                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    //                    matiHEre("uhuu");
                }
            }

            //endregion

            // region berlaku pembatalan transaksi bila ada config revertStep di model MdlRevertJurnal (true)
            if (isset($_SESSION[$cCode]['main']['pihakExternRevertStep']) && ($_SESSION[$cCode]['main']['pihakExternRevertStep'] == true)) {
                $referenceNextProp = (isset($_SESSION[$cCode]['main']['referenceNextProp']) && (sizeof($_SESSION[$cCode]['main']['referenceNextProp']) > 0)) ? $_SESSION[$cCode]['main']['referenceNextProp'] : array();
                if (sizeof($referenceNextProp) > 0) {
                    // update transaksi reference, step sebelumnya menjadi aktif lagi
                    $tr = new MdlTransaksi();
                    $tr->setFilters(array());
                    $dupState = $tr->updateData(array("id" => $referenceNextProp['trID']), array(
                        "next_step_code" => $referenceNextProp['code'],
                        "next_step_label" => $referenceNextProp['label'],
                        "next_group_code" => $referenceNextProp['groupID'],
                        "next_step_num" => $referenceNextProp['num'],
                        "step_current" => $referenceNextProp['step_num'],

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


                    // update transaksi data reference, step sebelumnya menjadi aktif lagi
                    $tr = new MdlTransaksi();
                    $tr->setFilters(array());
                    $tr->addFilter("trash='0'");
                    $tr->addFilter("transaksi_id='" . $referenceNextProp['trID'] . "'");
                    $tr->setTableName($tr->getTableNames()['detail']);
                    $detailTmp = $tr->lookupAll()->result();
                    $detailData = array();
                    foreach ($detailTmp as $dTmpSpec) {
                        $detailData[$dTmpSpec->produk_id] = array(
                            "valid_qty" => $dTmpSpec->valid_qty,
                        );
                    }
                    cekOrange($referenceNextProp['detailGate']);
                    if (isset($_SESSION[$cCode][$referenceNextProp['detailGate']]) && ($_SESSION[$cCode][$referenceNextProp['detailGate']] != NULL)) {

                        foreach ($_SESSION[$cCode][$referenceNextProp['detailGate']] as $itemsSpec) {
                            //                        arrPrint($itemsSpec);
                            $valid_qty = isset($detailData[$itemsSpec['id']]['valid_qty']) ? $detailData[$itemsSpec['id']]['valid_qty'] : 0;
                            $valid_qty_new = $valid_qty + $itemsSpec['qty'];

                            $tr = new MdlTransaksi();
                            $tr->setFilters(array());
                            $tr->setTableName($tr->getTableNames()['detail']);
                            $ddupState = $tr->updateData(
                                array(
                                    "transaksi_id" => $referenceNextProp['trID'],
                                    "trash" => 0,
                                    "produk_id" => $itemsSpec['id'],
                                ), array(
                                "next_substep_code" => $referenceNextProp['code'],
                                "next_substep_label" => $referenceNextProp['label'],
                                "next_subgroup_code" => $referenceNextProp['groupID'],
                                "next_substep_num" => $referenceNextProp['num'],
                                "sub_step_current" => $referenceNextProp['step_num'],
                                "valid_qty" => $valid_qty_new,

                            )) or die("Failed to update tr next-state!");
                            cekHijau("BATAL :: " . $this->db->last_query() . " -- " . $this->db->affected_rows());
                            $mongUpdateList['update']['detail'][] = array(
                                "where" => array(
                                    "transaksi_id" => $referenceNextProp['trID'],
                                    "trash" => 0,
                                    "produk_id" => $itemsSpec['id'],
                                ),
                                "value" => array(
                                    "next_substep_code" => $referenceNextProp['code'],
                                    "next_substep_label" => $referenceNextProp['label'],
                                    "next_subgroup_code" => $referenceNextProp['groupID'],
                                    "next_substep_num" => $referenceNextProp['num'],
                                    "sub_step_current" => $referenceNextProp['step_num'],
                                    "valid_qty" => $valid_qty_new,
                                ),
                            );

                        }
                    }
                }
            }
            // endregion

            //region nulis paymentSource
            $stepCode = $configUi[$this->jenisTr]['steps'][1]['target'];
            $paymentSources = $this->config->item("payment_source");
            if (array_key_exists($stepCode, $paymentSources)) {
                $payConfigs = $paymentSources[$stepCode];
                if (sizeof($payConfigs) > 0) {
                    foreach ($payConfigs[1] as $paymentSrcConfig) {
                        //					$paymentSrcConfig = $paymentSources[$stepCode];
                        $valueSrc = $paymentSrcConfig['valueSrc'];
                        $externSrc = $paymentSrcConfig['externSrc'];
                        $paymentMethod = isset($paymentSrcConfig['method']) ? $paymentSrcConfig['method'] : "insert";

                        if ($paymentMethod == "update") {
                            $filters = array(
                                "extern_id" => ""
                            );
                            arrPrint($externSrc);
                            $tr->setFilters(array());
                            $tmpData = $tr->lookupPaymentSrcByJenis($paymentSrcConfig['jenisTarget'])->result();
                            if (sizeof($tmpData) > 0) {
                                //sudah ada update aja gak perlu insert
                                $prevID = $tmpData[0]->id;
                                $preValue = $tmpData[0]->sisa;
                                $currValue = isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0;
                                $newValue = $preValue + $currValue;
                                $where = array(
                                    "id" => $prevID,
                                    //                                    "transaksi_id" => $pSpec->transaksi_id,
                                );
                                $data = array(
                                    "tagihan" => $newValue,
                                    "sisa" => $newValue,
                                );
                                $tr->updatePaymentSrc($where, $data);
                                //                                cekHitam($this->db->last_query());
                            }
                            else {
                                //di insert baru
                                $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" => $_SESSION[$cCode]['main']['nomer'],
                                    "label" => $paymentSrcConfig['label'],
                                    "tagihan" => isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0,
                                    "terbayar" => 0,
                                    "sisa" => isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0,
                                    "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']] : 0,
                                    "tagihan_valas" => (isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']])) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : 0,
                                    "terbayar_valas" => (isset($externSrc['valasTerbayar']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTerbayar']])) ? $_SESSION[$cCode]['main'][$externSrc['valasTerbayar']] : 0,
                                    "sisa_valas" => (isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']])) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : 0,
                                    "extern_label2" => (isset($externSrc['extern_label2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_label2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_label2']] : "",
                                    "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : 0,
                                ));
                            }


                        }
                        else {
                            $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" => $_SESSION[$cCode]['main']['nomer'],
                                "label" => $paymentSrcConfig['label'],
                                "tagihan" => isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0,
                                "terbayar" => 0,
                                "sisa" => isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0,
                                "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']] : 0,
                                "tagihan_valas" => (isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']])) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : 0,
                                "terbayar_valas" => (isset($externSrc['valasTerbayar']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTerbayar']])) ? $_SESSION[$cCode]['main'][$externSrc['valasTerbayar']] : 0,
                                "sisa_valas" => (isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']])) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : 0,
                                "extern_label2" => (isset($externSrc['extern_label2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_label2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_label2']] : "",
                                "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : 0,
                            ));
                        }

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


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

            // matiHere(__LINE__ . __METHOD__);

            //
            //region nulis paymentAntiSource
            $stepCode = $configUi[$this->jenisTr]['steps'][1]['target'];
            $paymentSources = $this->config->item("payment_antiSource") != null ? $this->config->item("payment_antiSource") : array();
            if (array_key_exists($stepCode, $paymentSources)) {
                cekHitam(":: 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" => $_SESSION[$cCode]['main']['nomer'],
                            "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" => isset($_SESSION[$cCode]['main'][$externSrc['valasTerbayar']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTerbayar']] : '',
                            "sisa_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',

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


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


            //====registri value-gate
            if (isset($this->configCore[$this->jenisTr]['components'][1]) && sizeof($this->configCore[$this->jenisTr]['components'][1])) {
                $jurnalIndex = $this->configCore[$this->jenisTr]['components'][1];
            }
            else {
                if (isset($_SESSION[$cCode]["revert"]["jurnal"]) && sizeof($_SESSION[$cCode]["revert"]["jurnal"]) > 0) {
                    $jurnalIndex = $_SESSION[$cCode]["revert"]["jurnal"];
                }
                else {
                    $jurnalIndex = array();
                }
            }

            if (isset($this->configCore[$this->jenisTr]['postProcessor'][1]) && sizeof($this->configCore[$this->jenisTr]['postProcessor'][1])) {
                $jurnalPostProc = $this->configCore[$this->jenisTr]['postProcessor'][1];
            }
            else {
                if (isset($_SESSION[$cCode]["revert"]["postProc"]) && sizeof($_SESSION[$cCode]["revert"]["postProc"]) > 0) {
                    $jurnalPostProc = $_SESSION[$cCode]["revert"]["postProc"];
                }
                else {
                    $jurnalPostProc = array();
                }
            }

            $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_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),

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

                'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                //                "jurnal_index" =>isset($this->configCore[$this->jenisTr]['components'][1]) ? $this->configCore[$this->jenisTr]['components'][1] : array(),
                "jurnal_index" => $jurnalIndex,
                //                "postProcessor" =>isset($this->configCore[$this->jenisTr]['postProcessor'][1]) ? $this->configCore[$this->jenisTr]['postProcessor'][1] : array(),
                "postProcessor" => $jurnalPostProc,
                "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(),
            );

            $doWriteReg = $tr->writeRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));

            //========extended steps (if any)
            //region extended steps
            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                foreach ($_SESSION[$cCode]['main_inputs'] as $iKey => $iVal) {
                    if ($iVal > 0) {

                        cekbiru("evaluating $iKey ($iVal) for paymentSrc..");
                        $stepCode = $this->jenisTr . "_";
                        $paymentSources = $this->config->item("payment_source");


                        if (array_key_exists($stepCode, $paymentSources)) {
                            $payConfigs = $paymentSources[$stepCode];
                            cekbiru("$stepCode registered");


                            //===kalau melibatkan payment-source
                            if (sizeof($payConfigs) > 0) {
                                foreach ($payConfigs as $paymentSrcConfig) {
                                    if ($paymentSrcConfig['valueSrc'] == $iKey) {
                                        cekhijau($paymentSrcConfig['valueSrc'] . "/$iKey akan dieksekusi");
                                        $valueSrc = $paymentSrcConfig['valueSrc'];
                                        $externSrc = $paymentSrcConfig['externSrc'];
                                        if ($tr->paymentSrcExistsInMaster($insertID, $stepCode, $paymentSrcConfig['label'])) {
                                            cekhijau($paymentSrcConfig['label'] . " pada $stepCode $insertID sudah ada, tidak perlu ditulis");
                                        }
                                        else {
                                            cekhijau($paymentSrcConfig['label'] . " pada $stepCode $insertID BELUM ada, ditulis sekarang");
                                            $tr->writePaymentSrc($insertID, array(
                                                "_key" => $iKey,
                                                "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" => $_SESSION[$cCode]['main']['nomer'],
                                                "label" => $paymentSrcConfig['label'],
                                                "tagihan" => $_SESSION[$cCode]['main_inputs'][$valueSrc],
                                                "terbayar" => 0,
                                                "sisa" => $_SESSION[$cCode]['main_inputs'][$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("paySrc: ".$this->db->last_query());

                                    }
                                    else {
                                        cekmerah($paymentSrcConfig['valueSrc'] . "/$iKey tidak untuk dieksekusi");
                                    }
                                }
                            }

                        }
                        else {
                            cekbiru("$stepCode NOT registered");
                        }


                        //==periksa apakah mainInput memerlukan auth
                        if (array_key_exists($iKey, $inputAuthConfigs)) {
                            $gID = $inputAuthConfigs[$iKey];
                            if (strlen($gID) > 0) {
                                cekhijau("input $iKey bernilai $iVal memerlukan auth dari $gID");
                                $trA = new MdlTransaksi();
                                if ($trA->extStepExistsInMaster($insertID, $iKey)) {
                                    cekhijau("extStep SUDAH terdaftar, sekarang nggak akan ditulis");
                                }
                                else {
                                    cekhijau("extStep belum terdaftar, sekarang hendak ditulis");
                                    $insertNew = $trA->writeExtStep($insertID, array(
                                        "master_id" => $insertID,
                                        "transaksi_id" => $insertID,
                                        "_key" => $iKey,
                                        "_label" => $inputLabels[$iKey],
                                        "_value" => $iVal,
                                        "group_id" => $gID,
                                        "state" => "0",
                                        "proposed_by" => $this->session->login['id'],
                                        "proposed_dtime" => date("Y-m-d H:i:s"),
                                        "done_by",
                                        "done_dtime",
                                    ));
                                    $mongoList['extras'][] = $insertNew;
                                    cekhijau($this->db->last_query());
                                }
                            }

                        }
                    }

                }
            }
            //endregion

            //==================================================================================================
            //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
            // bila step lebih dari 1
            if ($nextProp['num'] > 1) {
                $this->load->model("Mdls/MdlLockerTransaksi");
                $lt = New MdlLockerTransaksi();
                $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], NULL, $insertID);
            }

            //==========================================================================================================

            $masterID = $insertID;

            //region connecting antar cabang
            $mongoListConnect = array();
            $mongRegIDConnect = array();
            $connector = isset($configUi[$this->jenisTr]['connectTo']) ? $configUi[$this->jenisTr]['connectTo'] : "";
            $preReplacer = isset($configUi[$this->jenisTr]['replacerConnectTo']) ? $configUi[$this->jenisTr]['replacerConnectTo'] : array();
            if (strlen($connector) > 0) {
                cekMerah(":: CONNECTING BEGIN...");
                //cekMerah("to be connected to $connector");
                // matiHEre(sizeof($steps));
                if (sizeof($steps) == 1) {
                    cekMerah("now connecting to $connector");
                    if (!array_key_exists($connector, $configUi)) {
                        die("kode connector tidak dikenali!");
                    }
                    if (sizeof($configUi[$connector]['steps']) < 2) {
                        die("konfigurasi connector harus memiliki step lebih dari satu!");
                    }


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

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

                    //region detector cloner dalam satu cabang
                    $oldStep = $_SESSION[$oldCode]['main']["step_number"];
                    $clonerTransaction = isset($configUi[$this->jenisTr]['clonerTransaction'][$oldStep]) ? $configUi[$this->jenisTr]['clonerTransaction'][$oldStep] : array();


                    //endregion
                    if (sizeof($clonerTransaction) && isset($clonerTransaction['main']['cloner'])) {
                        cekHere("i am here");
                        $replacerTableinDetail = array(
                            "dtime" => "dtime",
                            "produk_id" => "id",
                            "produk_kode" => "kode",
                            "produk_label" => "label",
                            "produk_nama" => "nama",
                            "produk_ord_jml" => "produk_ord_jml",
                            "produk_ord_hrg" => "harga1",
                            "satuan" => "satuan",
                            "produk_jenis" => "produk_jenis",
                            "harga" => "harga1",
                            "valid_qty" => "produk_ord_jml",
                        );
                        $replacerStepItems2 = array(
                            "sub_tail_number" => "",
                            "sub_tail_code" => "",
                            "sub_step_avail" => "",
                            "sub_step_current" => "",
                            "sub_step_number" => "",
                            "next_substep_num" => "",
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                        );

                        $itesmNewTmp = array();
                        foreach ($_SESSION[$oldCode]['items2'] as $indexItems2) {
                            foreach ($indexItems2 as $itemsDetail) {

                                $itesmNewTmp[$itemsDetail['id']] = array_merge($itemsDetail, $replacerStepItems2);
                                foreach ($replacerTableinDetail as $selCol => $xAlias) {
                                    $_SESSION[$oldCode]['tableIn_detail2'][$itemsDetail['id']][$selCol] = $itemsDetail[$selCol];
                                }
                                foreach ($replacerStepItems2 as $stepItems2 => $tempItems2Val) {
                                    $_SESSION[$oldCode]['tableIn_detail2'][$itemsDetail['id']][$stepItems2] = $tempItems2Val;
                                }

                            }

                            //                            arrPrint($itesmNew);
                        }
                        $itesmNew = array();
                        foreach ($itesmNewTmp as $itemsID => $itemData) {
                            if (isset($itemData['harga'])) {
                                $itemData['harga'] = $itemData['produk_ord_hrg'];
                            }
                            if (!isset($itemData['pihakName'])) {
                                $itemData['pihakName'] = $_SESSION[$oldCode]['main']['pihakName'];
                            }

                            $itesmNew[$itemsID] = $itemData;
                        }

                        //region itemsToMaster
                        $itemTomasterStatic = isset($clonerTransaction['staticItemToMaster']) ? $clonerTransaction['staticItemToMaster'] : array();
                        $itemToMaster = isset($clonerTransaction['itemToMaster']) ? $clonerTransaction['itemToMaster'] : array();
                        //                        arrPrint($itemToMaster);
                        if (sizeof($itemToMaster) > 0) {
                            foreach ($_SESSION[$oldCode]['items'] as $itemsTemp) {
                                foreach ($itemToMaster as $colItems => $aliasMaster) {
                                    if (isset($itemsTemp[$colItems])) {
                                        $_SESSION[$oldCode]['main'][$aliasMaster] = $itemsTemp[$colItems];
                                        $_SESSION[$oldCode]['tableIn_master'][$aliasMaster] = $itemsTemp[$colItems];
                                    }
                                }
                            }
                            if (sizeof($itemTomasterStatic) > 0) {
                                foreach ($itemTomasterStatic as $kolStatic => $valStatic) {
                                    $_SESSION[$oldCode]['main'][$kolStatic] = $valStatic;
                                    $_SESSION[$oldCode]['tableIn_master'][$kolStatic] = $valStatic;
                                }
                            }

                        }


                        //endregion

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


                            "tableIn_master" => $_SESSION[$oldCode]['tableIn_master'],
                            "tableIn_detail" => $_SESSION[$oldCode]['tableIn_detail2'],
                            'tableIn_detail2_sum' => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                            "rsltItems" => $_SESSION[$oldCode]['rsltItems'],
                            'rsltItems2' => isset($_SESSION[$oldCode]['rsltItems2']) ? $_SESSION[$oldCode]['rsltItems2'] : array(),
                            "tableIn_detail_rsltItems" => $_SESSION[$oldCode]['tableIn_detail_rsltItems'],
                            'tableIn_detail_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems2'] : array(),
                            "main_add_values" => $_SESSION[$oldCode]['main_add_values'],
                            "main_add_fields" => $_SESSION[$oldCode]['main_add_fields'],
                            "main_elements" => $_SESSION[$oldCode]['main_elements'],
                            //
                            "tableIn_master_values" => $_SESSION[$oldCode]['tableIn_master_values'],
                            "tableIn_detail_values" => $_SESSION[$oldCode]['tableIn_detail_values2_sum'],
                            "tableIn_detail_values_rsltItems" => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                            'tableIn_detail_values_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems2'] : array(),
                            'tableIn_detail_values2_sum' => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                        );
                        //region unset sessio details2
                        //                        unset($_SESSION[$cCode]['tableIn_detail_values2_sum']);
                        if (isset($clonerTransaction['resetGate']) && (sizeof($clonerTransaction['resetGate']) > 0)) {
                            foreach ($clonerTransaction['resetGate'] as $gate) {
                                unset($_SESSION[$cCode][$gate]);
                            }
                        }
                        //endregion
                        $masterReplacers = array(
                            //                        "referensi_id" => $masterID, (dimatikan)
                            "inv" => $tmpNomorNota,
                            //                        "jenis_master"    => $connector,

                            "jenis_master" => $connector,
                            "jenis_top" => $configUi[$connector]['steps'][1]['target'],
                            //                        "jenis_top" => $configUi[$connector]['steps'][1]['target'],
                            "jenis" => $configUi[$connector]['steps'][1]['target'],
                            "jenis_label" => $configUi[$connector]['steps'][1]['label'],
                            "transaksi_jenis" => $configUi[$connector]['steps'][1]['target'],
                            "div_id" => "18",
                            "div_nama" => "default",
                            //                            "cabang_id"       => $_SESSION[$oldCode]['tableIn_master']['cabang2_id'],
                            //                            "cabang_nama"     => $_SESSION[$oldCode]['tableIn_master']['cabang2_nama'],
                            //                            "cabang2_id"      => $_SESSION[$oldCode]['tableIn_master']['cabang_id'],
                            //                            "cabang2_nama"    => $_SESSION[$oldCode]['tableIn_master']['cabang_nama'],
                            //                            "gudang_id"       => $_SESSION[$oldCode]['tableIn_master']['gudang2_id'],
                            //                            "gudang_nama"     => $_SESSION[$oldCode]['tableIn_master']['gudang2_nama'],
                            //                            "gudang2_id"      => $_SESSION[$oldCode]['tableIn_master']['gudang_id'],
                            //                            "gudang2_nama"    => $_SESSION[$oldCode]['tableIn_master']['gudang_nama'],

                            "step_avail" => sizeof($configUi[$connector]['steps']),
                            "step_current" => 1,
                            "step_number" => 1,
                            "next_step_code" => isset($configUi[$connector]['steps'][2]) ? $configUi[$connector]['steps'][2]['target'] : "",
                            "next_step_label" => isset($configUi[$connector]['steps'][2]) ? $configUi[$connector]['steps'][2]['label'] : "",
                            "next_group_code" => isset($configUi[$connector]['steps'][2]) ? $configUi[$connector]['steps'][2]['userGroup'] : "",
                            "next_step_num" => isset($configUi[$connector]['steps'][2]) ? 2 : "0",


                        );

                        //                        arrPrint( $_SESSION[$cCode]);
                        $masterReplacersO = array(
                            "jenisTr" => $connector,
                            "div_id" => "18",
                            "jenisTrMaster" => $connector,
                            "jenisTrTop" => $configUi[$connector]['steps'][1]['target'],
                            "jenis" => $configUi[$connector]['steps'][1]['target'],
                            "jenis_label" => $configUi[$connector]['steps'][1]['label'],
                            "transaksi_jenis" => $configUi[$connector]['steps'][1]['target'],
                            "stepCode" => $configUi[$connector]['steps'][1]['target'],
                            //                            "placeID"         => $_SESSION[$oldCode]['main']['place2ID'],


                            //                            "placeName"       => $_SESSION[$oldCode]['main']['place2Name'],
                            //                            "place2ID"        => $_SESSION[$oldCode]['main']['placeID'],
                            //                            "place2Name"      => $_SESSION[$oldCode]['main']['placeName'],
                            //                            "cabangID"        => $_SESSION[$oldCode]['main']['place2ID'],
                            //                            "cabangName"      => $_SESSION[$oldCode]['main']['place2Name'],
                            //                            "cabang2ID"       => $_SESSION[$oldCode]['main']['placeID'],
                            //                            "cabang2Name"     => $_SESSION[$oldCode]['main']['placeName'],
                            //                            //
                            //                            "gudang2ID"       => $_SESSION[$cCode]['main']['gudangID'],
                            //                            "gudang2Name"     => $_SESSION[$cCode]['main']['gudangName'],
                            //                            "gudangID"        => $_SESSION[$cCode]['main']['gudang2ID'],
                            //                            "gudangName"      => $_SESSION[$cCode]['main']['gudang2Name'],
                        );
                    }
                    else {
                        $_SESSION[$cCode] = array(
                            "main" => $_SESSION[$oldCode]['main'],
                            "items" => $_SESSION[$oldCode]['items'],
                            'items2' => isset($_SESSION[$oldCode]['items2']) ? $_SESSION[$oldCode]['items2'] : array(),
                            'items2_sum' => isset($_SESSION[$oldCode]['items2_sum']) ? $_SESSION[$oldCode]['items2_sum'] : array(),
                            'items3' => isset($_SESSION[$oldCode]['items3']) ? $_SESSION[$oldCode]['items3'] : array(),
                            'items3_sum' => isset($_SESSION[$oldCode]['items3_sum']) ? $_SESSION[$oldCode]['items3_sum'] : array(),
                            // -------------
                            "tableIn_master" => isset($_SESSION[$oldCode]['tableIn_master']) ? $_SESSION[$oldCode]['tableIn_master'] : array(),
                            "tableIn_detail" => isset($_SESSION[$oldCode]['tableIn_detail']) ? $_SESSION[$oldCode]['tableIn_detail'] : array(),
                            'tableIn_detail2_sum' => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                            "rsltItems" => isset($_SESSION[$oldCode]['rsltItems']) ? $_SESSION[$oldCode]['rsltItems'] : array(),
                            'rsltItems2' => isset($_SESSION[$oldCode]['rsltItems2']) ? $_SESSION[$oldCode]['rsltItems2'] : array(),
                            //----------------
                            "tableIn_detail_rsltItems" => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems'] : array(),
                            'tableIn_detail_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems2'] : array(),
                            "tableIn_master_values" => isset($_SESSION[$oldCode]['tableIn_master_values']) ? $_SESSION[$oldCode]['tableIn_master_values'] : array(),
                            "tableIn_detail_values" => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                            "tableIn_detail_values_rsltItems" => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                            'tableIn_detail_values_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems2'] : array(),
                            'tableIn_detail_values2_sum' => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                        );
                        $masterReplacers = array(
                            "inv" => $tmpNomorNota,
                            "jenis_master" => $connector,
                            "jenis_top" => $configUi[$connector]['steps'][1]['target'],
                            // "jenis_top" => $configUi[$connector]['steps'][1]['target'],
                            "jenis" => $configUi[$connector]['steps'][1]['target'],
                            "jenis_label" => $configUi[$connector]['steps'][1]['label'],
                            "transaksi_jenis" => $configUi[$connector]['steps'][1]['target'],
                            "cabang_id" => isset($preReplacer['cabang2ID']) ? $preReplacer['cabang2ID'] : $_SESSION[$oldCode]['tableIn_master']['cabang2_id'],
                            "cabang_nama" => isset($preReplacer['cabang2Name']) ? $preReplacer['cabang2Name'] : $_SESSION[$oldCode]['tableIn_master']['cabang2_nama'],
                            "cabang2_id" => $_SESSION[$oldCode]['tableIn_master']['cabang_id'],
                            "cabang2_nama" => $_SESSION[$oldCode]['tableIn_master']['cabang_nama'],
                            // -----------------
                            "gudang_id" => isset($preReplacer['gudang2ID']) ? $preReplacer['gudang2ID'] : $_SESSION[$oldCode]['tableIn_master']['gudang2_id'],
                            "gudang_nama" => isset($preReplacer['gudang2Name']) ? $preReplacer['gudang2Name'] : $_SESSION[$oldCode]['tableIn_master']['gudang2_nama'],
                            "gudang2_id" => isset($_SESSION[$oldCode]['tableIn_master']['gudang_id']) ? $_SESSION[$oldCode]['tableIn_master']['gudang_id'] : "",
                            "gudang2_nama" => isset($_SESSION[$oldCode]['tableIn_master']['gudang_nama']) ? $_SESSION[$oldCode]['tableIn_master']['gudang_nama'] : "",
                            // -------------------
                            "step_avail" => sizeof($configUi[$connector]['steps']),
                            "step_current" => 1,
                            "step_number" => 1,
                            "next_step_code" => isset($configUi[$connector]['steps'][2]) ? $configUi[$connector]['steps'][2]['target'] : "",
                            "next_step_label" => isset($configUi[$connector]['steps'][2]) ? $configUi[$connector]['steps'][2]['label'] : "",
                            "next_group_code" => isset($configUi[$connector]['steps'][2]) ? $configUi[$connector]['steps'][2]['userGroup'] : "",
                            "next_step_num" => isset($configUi[$connector]['steps'][2]) ? 2 : "0",
                        );
                        $masterReplacersO = array(
                            "jenisTr" => $connector,
                            "jenisTrMaster" => $connector,
                            "jenisTrTop" => $configUi[$connector]['steps'][1]['target'],
                            "jenis" => $configUi[$connector]['steps'][1]['target'],
                            "jenis_label" => $configUi[$connector]['steps'][1]['label'],
                            "transaksi_jenis" => $configUi[$connector]['steps'][1]['target'],
                            "stepCode" => $configUi[$connector]['steps'][1]['target'],
                            "placeID" => isset($preReplacer['place2ID']) ? $preReplacer['place2ID'] : $_SESSION[$oldCode]['main']['place2ID'],
                            "placeName" => isset($preReplacer['place2Name']) ? $preReplacer['place2Name'] : $_SESSION[$oldCode]['main']['place2Name'],
                            "place2ID" => $_SESSION[$oldCode]['main']['placeID'],
                            "place2Name" => $_SESSION[$oldCode]['main']['placeName'],
                            // -----------------
                            "cabangID" => isset($preReplacer['cabang2ID']) ? $preReplacer['cabang2ID'] : $_SESSION[$oldCode]['main']['place2ID'],
                            "cabangName" => isset($preReplacer['gudang2Name']) ? $preReplacer['gudang2Name'] : $_SESSION[$oldCode]['main']['place2Name'],
                            "cabang2ID" => $_SESSION[$oldCode]['main']['placeID'],
                            "cabang2Name" => $_SESSION[$oldCode]['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'],
                            "efaktur_source" => isset($preReplacer['efaktur_source']) ? $_SESSION[$cCode]['main']['nomer'] : "",
                        );
                    }

                    //==replace pertama

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


                    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($this->configCore[$connector]['formatNota']);
                    if (!in_array($counterForNumber[0], $this->configCore[$connector]['counters'])) {
                        die(__LINE__ . " Used number should be registered in 'counters' config as well");
                    }

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

                    }

                    $tmpNomorNota2 = $paramSpec['paramString'];


                    //</editor-fold>
                    //endregion

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

                            $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                            switch ($paramSpec['id']) {
                                case 0: //===counter type is new
                                    $addData = array(
                                        "toko_id" => $tokoID,
                                        "toko_nama" => $tokoNama,
                                    );
                                    $paramKeyRaw = print_r($cParams, true);
                                    $paramValuesRaw = print_r($cValues[$i], true);
                                    $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                    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' => $appliedCounters,
                        'counters_intext' => $appliedCounters_inText,
                        'nomer' => $tmpNomorNota,
                        'dtime' => date("Y-m-d H:i:s"),
                        'fulldate' => date("Y-m-d"),
                    );
                    foreach ($addValues as $key => $val) {
                        $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                    }

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


                    //==replace kedua

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

                    if ($validationTableInMaster != false) {
                        arrPrint($validationTableInMaster);
                        foreach ($validationTableInMaster as $itemKolom => $kolomNilaiValidasi) {
                            if (!isset($_SESSION[$cCode]['tableIn_master'][$itemKolom])) {
                                lgShowWarning("transaksi gagal", "$itemKolom tidak terdeteksi");
                                matiDisini("$itemKolom belum dikirim");
                            }

                            $nilai_kolom_ygdicek = $_SESSION[$cCode]['tableIn_master'][$itemKolom];
                            $validator = "$nilai_kolom_ygdicek $kolomNilaiValidasi";

                            if ($nilai_kolom_ygdicek == 0) {
                                // if ($validator) {
                                //     matiDisini(__LINE__ . " kena validasi $nilai_kolom_ygdicek . $kolomNilaiValidasi ** $validator");
                                lgShowWarning("transaksi gagal", "$itemKolom tidak terdeteksi");
                                matiDisini("$itemKolom terdeteksi 0");
                            }
                        }

                    }
                    //===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($configUi[$connector]['steps']),
                        "sub_step_current" => 1,
                        "sub_step_number" => 1,
                        "next_substep_num" => $_SESSION[$cCode]['tableIn_master']['next_step_num'],
                        "next_substep_code" => $_SESSION[$cCode]['tableIn_master']['next_step_code'],
                        "next_substep_label" => $_SESSION[$cCode]['tableIn_master']['next_step_label'],
                        "next_subgroup_code" => $_SESSION[$cCode]['tableIn_master']['next_group_code'],
                        //                    "next_substep_code" => isset($configUi[$connector]['steps'][2]) ? $configUi[$connector]['steps'][2]['target'] : "",
                        //                    "next_substep_label" => isset($configUi[$connector]['steps'][2]) ? $configUi[$connector]['steps'][2]['label'] : "",
                        //                    "next_subgroup_code" => isset($configUi[$connector]['steps'][2]) ? $configUi[$connector]['steps'][2]['userGroup'] : "",
                    );
                    if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                        foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                            foreach ($dSpec as $key => $val) {
                                $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                            }
                        }
                    }

                    //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']);
                        cekBiru($this->db->last_query());
                        $epID = $tr->writeMainEntries_entryPoint($insertID, $insertID, $_SESSION[$cCode]['tableIn_master']);
                        $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                        $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                        if ($insertID < 1) {
                            die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                        }
                        $mongoListConnect['main'] = array($insertID,
                            $epID
                        );
                    }
                    $inserMainValues = array();
                    if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                        foreach ($_SESSION[$cCode]['tableIn_master_values'] as $key => $val) {
                            $dd = $tr->writeMainValues($insertID, array("key" => $key,
                                "value" => $val
                            ));
                            $inserMainValues[] = $dd;
                            $mongoListConnect['mainValues'][] = $dd;
                        }
                    }

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

                    if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                        cekkuning("main_inputs detected");
                        $inserMainValues = array();
                        foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                            $dd = $tr->writeMainValues($insertID, array("key" => $key,
                                "value" => $val
                            ));
                            $inserMainValues[] = $dd;
                            $mongoListConnect['mainValues'][] = $dd;
                            //                            cekkuning("making a clone for input key $key / $val");
                            //                            $subInputInsertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                        }
                    }

                    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) {
                        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) : "",

                            ));
                        }
                    }

                    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) {
                            $insertIDDetail = $tr->writeDetailEntries($insertID, $dSpec);
                            $insertIDs[] = $insertIDDetail;
                            $mongoListConnect['detail'][] = $insertIDDetail;
                            if ($epID != 999) {
                                $insertIDDetail = $tr->writeDetailEntries($epID, $dSpec);
                                $insertIDs[] = $insertIDDetail;
                                $mongoListConnect['detail'][] = $insertIDDetail;
                            }
                        }
                    }

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

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


                        }
                    }


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

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

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

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

                    $baseRegistries = array(
                        'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                        'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                        'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                        'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                        'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                        'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                        'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                        'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                        'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                        'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                        'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                        'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                        'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                        'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                        'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                        // --
                        'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                        'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                        // --
                        '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(),
                        "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                    );
                    //                    arrPrint($baseRegistries);

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

                    //
                    //region nulis paymentSource
                    //                    $stepCode = $connector;
                    $stepCode = $configUi[$connector]['steps'][1]['target'];
                    $paymentSources = $this->config->item("payment_source");
                    cekHitam(":: $stepCode ::");
                    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" => $connector,
                                    "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                    "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                    "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                                    "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                                    "nomer" => $_SESSION[$cCode]['main']['nomer'],
                                    "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 = $connector;
                    $stepCode = $configUi[$connector]['steps'][1]['target'];
                    $paymentSources = $this->config->item("payment_antiSource");
                    if (array_key_exists($stepCode, $paymentSources)) {

                        $payConfigs = $paymentSources[$stepCode];
                        if (sizeof($payConfigs) > 0) {
                            foreach ($payConfigs as $paymentSrcConfig) {
                                //					$paymentSrcConfig = $paymentSources[$stepCode];
                                $valueSrc = $paymentSrcConfig['valueSrc'];
                                $externSrc = $paymentSrcConfig['externSrc'];
                                $tr->writePaymentAntiSrc($insertID, array(
                                    "jenis" => $connector,
                                    "target_jenis" => $paymentSrcConfig['jenisTarget'],
                                    "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                                    "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                                    "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                                    "nomer" => $_SESSION[$cCode]['main']['nomer'],
                                    "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


                    //==================================================================================================
                    //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
                    // bila step lebih dari 1
                    $nextStepConnector = sizeof($configUi[$connector]['steps']);
                    if ($nextStepConnector > 1) {
                        $this->load->model("Mdls/MdlLockerTransaksi");
                        $lt = New MdlLockerTransaksi();
                        $lt->execLocker($_SESSION[$cCode]['main'], $nextStepConnector, NULL, $insertID);
                    }


                }
                else {
                    //cekMerah("to be delayed to connect to $connector");
                }
            }
            else {
                //cekKuning("not connecting to any tCode");
            }

            //endregion


            cekMerah("TRANSAKSI DONE");

            //region writelog
            $this->load->model("Mdls/" . "MdlActivityLog");
            $hTmp = new MdlActivityLog();
            $tmpHData = array(
                "title" => $_SESSION[$cCode]['main']['jenisTrName'],
                "sub_title" => "Saving new transaction",
                "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

            cekKuning(":: mulai cek rek besar dan rek pembantu");
            $cabangID_validate = $this->session->login['cabang_id'];
            validateBalancesComparison($cabangID_validate, $componentGate, $componentConfig, "master", $insertID, $tmpNomorNota);
            validateAllBalances();

            //==========================================================================================================
            if (isset($this->configCore[$this->jenisTr]['cloningTransaction'][1])) {
                $cloningTransaction = $this->configCore[$this->jenisTr]['cloningTransaction'][1];
                if (isset($cloningTransaction['enabled']) && ($cloningTransaction['enabled'] == true)) {
                    $jenisTargetClone = $cloningTransaction['targetJenis'];
                    //--clone transaksi dan transaks_data
                    if (isset($cloningTransaction['tabel']['transaksi']) && sizeof($cloningTransaction['tabel']['transaksi']) > 0) {
                        $registryReplacer = isset($cloningTransaction['registry']) ? $cloningTransaction['registry'] : array();
                        $kolomMain = isset($cloningTransaction['tabel']['transaksi']['kolom']) ? $cloningTransaction['tabel']['transaksi']['kolom'] : array();
                        $sessionGateMain = isset($cloningTransaction['tabel']['transaksi']['session']) ? $cloningTransaction['tabel']['transaksi']['session'] : mati_disini("session sumber cloning transaksi belum didefine.");

                        $kolomDetail = isset($cloningTransaction['tabel']['transaksi_data']['kolom']) ? $cloningTransaction['tabel']['transaksi_data']['kolom'] : array();
                        $sessionGateDetail = isset($cloningTransaction['tabel']['transaksi_data']['session']) ? $cloningTransaction['tabel']['transaksi_data']['session'] : mati_disini("session sumber cloning transaksi belum didefine.");

                        if (sizeof($kolomMain) > 0) {
                            $transMainData = array();
                            $transMainDataValues = array();
                            $registriesClone = array();
                            foreach ($_SESSION[$cCode][$sessionGateMain] as $trNomer => $spec) {
                                // mereplace reg MAIN, ITEMS, ITEMS2_SUM
                                if (isset($registryReplacer['main']) && sizeof($registryReplacer['main']) > 0) {
                                    foreach ($registryReplacer['main'] as $r_key => $r_val) {
                                        $spec[$r_key] = $r_val;
                                    }
                                }
                                if (isset($registryReplacer['items']) && sizeof($registryReplacer['items']) > 0) {
                                    foreach ($registryReplacer['items'] as $r_key => $r_val) {
                                        foreach ($_SESSION[$cCode][$sessionGateDetail][$trNomer] as $ii => $iSpec) {
                                            $_SESSION[$cCode][$sessionGateDetail][$trNomer][$ii][$r_key] = $r_val;
                                        }
                                    }
                                }
                                if (isset($registryReplacer['items2_sum']) && sizeof($registryReplacer['items2_sum']) > 0) {
                                    foreach ($registryReplacer['items2_sum'] as $r_key => $r_val) {
                                        foreach ($_SESSION[$cCode]['items4_sum'][$trNomer] as $ii => $iSpec) {
                                            $_SESSION[$cCode]['items4_sum'][$trNomer][$ii][$r_key] = $r_val;
                                        }
                                    }
                                }
                                //------------------

                                foreach ($kolomMain as $keyTbl => $keyGate) {
                                    $transMainData[$keyTbl] = isset($spec[$keyGate]) ? $spec[$keyGate] : $keyGate;
                                    if (isset($spec[$keyGate]) && is_numeric($spec[$keyGate])) {
                                        $transMainDataValues[$keyTbl] = isset($spec[$keyGate]) ? $spec[$keyGate] : 0;
                                    }
                                }
                                $transMainData['step_number'] = 1;
                                $transMainData['dtime'] = date("Y-m-d H:i:s");
                                //--------------------------------------
                                $transDetailData = array();
                                $transDetailDataValues = array();
                                if (isset($_SESSION[$cCode][$sessionGateDetail][$trNomer]) && sizeof($_SESSION[$cCode][$sessionGateDetail][$trNomer]) > 0) {
                                    foreach ($_SESSION[$cCode][$sessionGateDetail][$trNomer] as $ii => $dSpec) {
                                        foreach ($kolomDetail as $keyTbl => $keyGate) {
                                            $transDetailData[$ii][$keyTbl] = isset($dSpec[$keyGate]) ? $dSpec[$keyGate] : "";
                                            if (isset($dSpec[$keyGate]) && is_numeric($dSpec[$keyGate])) {
                                                $transDetailDataValues[$ii][$keyTbl] = isset($dSpec[$keyGate]) ? $dSpec[$keyGate] : "";
                                            }
                                        }
                                    }
                                }
                                //--------------------------------------
                                $tr = new MdlTransaksi();
                                $insertCloneID = $tr->writeMainEntries($transMainData);

                                $epCloneID = $tr->writeMainEntries_entryPoint($insertCloneID, $insertID, $transMainData);

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

                                if (sizeof($transDetailData) > 0) {
                                    foreach ($transDetailData as $dSpec) {
                                        $insertDetailID = $tr->writeDetailEntries($insertCloneID, $dSpec);
                                        showLast_query("hijau");
                                        $insertDetailEpID = $tr->writeDetailEntries($epCloneID, $dSpec);
                                        //                                        showLast_query("kuning");
                                        if ($insertDetailID < 1) {
                                            die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                                        }
                                    }
                                }
                                //--------------------------------------

                                //arrPrint($spec);
                                //arrPrintWebs($_SESSION[$cCode][$sessionGateDetail][$trNomer]);
                                //arrPrintPink($_SESSION[$cCode]['items4_sum'][$trNomer]);
                                //

                                // build registry per-transaksi cloningan
                                $registriesClone['main'] = $spec;                                                                                                            // main per-transaksi
                                $registriesClone['items'] = $_SESSION[$cCode][$sessionGateDetail][$trNomer];                                                                 // detail per-transaksi
                                $registriesClone['items2_sum'] = isset($_SESSION[$cCode]['items4_sum'][$trNomer]) ? $_SESSION[$cCode]['items4_sum'][$trNomer] : array();     // akumulasi bahan per-transaksi
                                $registriesClone['items_komposisi'] = isset($_SESSION[$cCode]['items8_sum'][$trNomer]) ? $_SESSION[$cCode]['items8_sum'][$trNomer] : array();// komposisi per-transaksi

                                $registriesClone['tableIn_master'] = $transMainData;               // tableIN master per-transaksi
                                $registriesClone['tableIn_detail'] = $transDetailData;             // tableIN detail per-transaksi
                                $registriesClone['tableIn_master_values'] = $transMainDataValues;  // tableIN master values per-transaksi
                                $registriesClone['tableIn_detail_values'] = $transDetailDataValues;// tableIN detail values per-transaksi

                                $doWriteCloneRegistries = $tr->writeRegistries($insertCloneID, $registriesClone) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                                showLast_query("hitam");

                                $tr = new MdlTransaksi();
                                $cloneUpdate = $tr->updateData(array("id" => $insertCloneID), array(
                                    //===references
                                    "id_master" => $insertCloneID,
                                    "id_top" => $insertCloneID,
                                )) or die("Failed to update tr clone transaction!");
                                cekHijau($this->db->last_query());

                            }
                        }

                    }
                }
            }
            //==========================================================================================================
            // if($debu)
            // mati_disini("LINE: " . __LINE__ . " under debuging, tunggu beberapa saat lagi yaa..");

            $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");

            if (isset($_SESSION[$cCode])) {
                unset($_SESSION[$cCode]);
            }
            if (isset($oldCode)) {
                if (isset($_SESSION[$oldCode])) {
                    unset($_SESSION[$oldCode]);
                }
            }
            //region cloning update mongo
            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 cloning ke 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);
                            //                            arrPrint($transksi_main);
                            $mong->addData($transksi_main);
                        }
                    }
                    //                    cekHitam($listedTable[$gateList]);
                    //                    cekLime($gateList);

                }
            }
            // if (sizeof($mongRegID) > 0) {
            //     //                $arrMainID = $mongoList['main'];
            //     $tr->setTableName("transaksi_registry");
            //     $tr->setFilters(array());
            //     $tr->setSortBy(array());
            //     $tr->addFilter("id in (" . implode(",", $mongRegID) . ")");
            //     $tmpTrm = $tr->lookUpAll()->result();
            //
            //     $mong->setTableName("transaksi_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 cloning conecto mongo
            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) {
            //     //                $arrMainID = $mongRegIDConnect['main'];
            //     $tr->setTableName("transaksi_registry");
            //     $tr->setFilters(array());
            //     $tr->setSortBy(array());
            //     $tr->addFilter("id in (" . implode(",", $mongRegIDConnect) . ")");
            //     $tmpTrm = $tr->lookUpAll()->result();
            //     //                    cekbiru($this->db->last_query());
            //     $mong->setTableName("transaksi_registry");
            //     if (sizeof($tmpTrm) > 0) {
            //         foreach ($tmpTrm as $tmpMain) {
            //             $transksi_main = json_decode(json_encode($tmpMain), true);
            //             $mong->addData($transksi_main);
            //         }
            //     }
            //
            // }
            //            $mongRegIDConnect //punya registry 2
            //endregion
            //region feedback msg
            $this->session->errMsg = "transaction entry has been saved<br>";
            $nextNum = $nextProp["num"];
            if (isset($configUi[$this->jenisTr]['steps'][$nextNum])) {
                $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white'>" . $configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . "</strong><br>";
                $this->session->errMsg .= "This entry needs to be authorized by <strong class='text-blue'>" . $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'>" . $configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . "</strong><br>";
                $trBackLink = base_url() . get_class($this) . "/viewHistory/" . $this->jenisTr;

            }
            $trBackClick = "location.href='$trBackLink'";
            //            $this->session->errMsg .= "<a href='javascript:void(0)' onclick=\"$trBackClick\">view entry</a><br>";
            //endregion

            /* --------------------------------------------------------------------------------------------------------
             * update ke file untuk sync ke APK
             * -------------------------------------------------------------------------------------------------------*/
            if (sizeof($perubahanComs) > 0) {
                foreach ($perubahanComs as $namaCom) {
                    $namaMdl = "Mdl" . ucfirst($namaCom);
                    // cekMerah($namaMdl);
                    $file = fopen(__DIR__ . '/eusvc/sync/' . $namaMdl . "_" . my_toko_id() . ".txt", "w");
                    echo fwrite($file, json_encode(array("datetime" => date("Y-m-d H:i:s"))));
                    fclose($file);
                }
            }

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

            if (strlen($rawPrevURL) > 3) {
                $actionTarget = "top.BootstrapDialog.closeAll();top.BootstrapDialog.show(
                                   {
                                       title:'Followup preview',
                                       message: " . 'top.$' . "('<div><img class=\"text-center text-bold\" width=\"35%\" src=\"//cdn.mayagrahakencana.com/assets/images/d60eb1v-79212624-e842-4e55-8d58-4ac7514ca8e4.gif\"><br/><h2>MOHON TUNGGU, SYSTEM SEDANG MEMUAT DATA...</h2></div>').load('$prevUrl'),
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        draggable:false,
                                        closable:true,
                                        }
                                        );";


                //                echo "<html>";
                //                echo "<head>";
                //                echo "<script src=\"" . cdn_suport() . "AdminLTE-2.3.11/plugins/jQuery/jquery-2.2.3.min.js\"></script>";
                //                echo "</head>";
                echo "<script>top.open_holdon();$actionTarget</script>";

                //                echo "</body>";
                //                echo "</html>";
            }
            else {
                if (isset($this->configLayout[$this->jenisTr]['allowPrint']['1'])) {
                    $printSettings = isset($this->configLayout[$this->jenisTr]['allowPrint']['1']) ? $this->configLayout[$this->jenisTr]['allowPrint']['1'] : array();
                    $printLocation = $this->configLayout[$this->jenisTr]['printLocation'];
                    if (isset($printSettings['size'])) {
                        cekkuning("detecting printing size");

                        switch ($printSettings['size']) {
                            case "normal":

                                //                                cekkuning("size: NORMAL");
                                echo "<script>";
                                echo "top.popBig('" . base_url() . $this->modul . "/" . $printLocation . $this->jenisTr . "/$tmpNomorNota/$masterID');";
                                echo "top.location.reload();";
                                echo "</script>";
                                break;
                            case "small":
                                //                                cekkuning("size: SMALL");
                                echo "<script>";
                                echo "top.popSmall('" . base_url() . $this->modul . "/" . $printLocation . $this->jenisTr . "/$tmpNomorNota/$masterID');";
                                echo "top.location.reload();";
                                echo "</script>";
                                break;
                            default:
                                //                                cekkuning("size: UNKNOWN");
                                break;
                        }


                    }
                    else {
                        cekkuning("not printing");
                        $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" => $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);
                    //                    mati_disini("TEST...");
                }

            }

        }
        else {
            die("the gate index you want to debug has not been formed yet! @" . __LINE__ . " " . __METHOD__);
        }
    }

    /*followUp I vlidasi*/
    public function followupPrePreview_modul()
    {
        // cekMerah(url_segment());
        $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()));

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

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

                // insert ke tabel locker transaksi
                $lt->addData($ltActive);
                $lt->addData($ltHold);
            }
            else {
                //            cekPink("sudah ada lockernya");

                $byUpdateHold = array();
                $totalUpdateHold = 0;
                $insertHold = true;
                foreach ($ltTmp as $ltSpec) {
                    if (($ltSpec->state == "hold") && ($ltSpec->jumlah == "1")) {
                        $insertHold = false;
                        break;
                    }
                    elseif (($ltSpec->state == "hold")) {
                        $totalUpdateHold += isset($ltSpec->jumlah) ? $ltSpec->jumlah : 0;
                        $byUpdateHold[] = $ltSpec->oleh_id;
                    }
                }
                if ($insertHold == true) {
                    //                cekPink("saya HOLD dan active di-nol-kan");
                    //                cekPink("total HOLDnya 0 dan saya pernah HOLD transaksi ini");
                    if (($totalUpdateHold == 0) && (in_array($this->session->login['id'], $byUpdateHold))) {
                        $ltHold = array(
                            "jumlah" => "1",
                        );
                        $ltWhere = array(
                            "state" => "hold",
                            "produk_id" => "$no",
                            "transaksi_id" => "$no",
                            "jenis" => "transaksi",
                            "jenis_locker" => "transaksi",
                            "oleh_id" => $this->session->login['id'],
                        );
                        $lt->updateData($ltWhere, $ltHold);
                    }
                    else {
                        //                    cekPink("total HOLDnya 0 dan saya BELUM pernah HOLD transaksi ini");
                        $ltHold = array(
                            "state" => "hold",
                            "produk_id" => "$no",
                            "transaksi_id" => "$no",
                            "cabang_id" => $this->session->login['cabang_id'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "jenis" => "transaksi",
                            "jenis_locker" => "transaksi",
                            "jumlah" => "1",
                        );
                        $lt->addData($ltHold);
                    }

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


        //        mati_disini();

        //
        //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();
        $registryFields = $trs->getRegistryFields();
        $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) {
            $this->jenisTr = $tmpTr[0]->jenis_master;
            $cCode = "_TR_" . $this->jenisTr;
            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($configUiJenis['shoppingCartNumFields'][$stepNumber]) ? $configUiJenis['shoppingCartNumFields'][$stepNumber] : array();
            $subAmountConfig = isset($configUiJenis['shoppingCartAmountValue'][$stepNumber]) ? $configUiJenis['shoppingCartAmountValue'][$stepNumber] : null;
            //            $masterID = isset($tmpTr[0]->referensi_id) && $tmpTr[0]->referensi_id > 0 ? $tmpTr[0]->referensi_id : $tmpTr[0]->transaksi_id;
            $measurementDetails = isset($configUiJenis["receiptMesurementRows"]) ? $configUiJenis["receiptMesurementRows"] : array();
            $validatePaymentLocker = isset($configUiJenis["validatePaymentSource"][$stepNumber]) ? $configUiJenis["validatePaymentSource"][$stepNumber] : array();
            $itemsChild = isset($configUiJenis["shopingCartDetailFields"][$stepNumber]['fields']) ? $configUiJenis["shopingCartDetailFields"][$stepNumber]['fields'] : array();//dipake detil pembelian aset
            $itemsChildGate = isset($configUiJenis["shopingCartDetailFields"][$stepNumber]['gate']) ? $configUiJenis["shopingCartDetailFields"][$stepNumber]['gate'] : array();//dipake detil pembelian aset/penambahan aset dari supplies sebagai switcer baca item atau main
            $connectedOptionFields = isset($configUiJenis["shopingCartOptionFields"][$stepNumber]) ? $configUiJenis["shopingCartOptionFields"][$stepNumber] : array();         //dipake detil pembelian aset
            $refecthAssamble = isset($configUiJenis["componentAssRefecth"]) ? $configUiJenis["componentAssRefecth"] : false;
            $masterID = $tmpTr[0]->id_master;
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $currentStepNum = $tmpTr[0]->step_number;
            $afterTargetStepNum = ($currentStepNum + 1);


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


            //            arrPrint($tempLocker);
            //endregion

            cekOrange($itemsChildGate);
            //==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($configUiJenis['steps'][$stepNumber]['allowEdit']) ? $configUiJenis['steps'][$stepNumber]['allowEdit'] : false;
            $allowCancel = isset($configUiJenis['steps'][$stepNumber]['allowCancel']) ? $configUiJenis['steps'][$stepNumber]['allowCancel'] : false;
            $editableFields = isset($configUiJenis['shoppingCartEditableFields'][$stepNumber]) ? $configUiJenis['shoppingCartEditableFields'][$stepNumber] : array();


            //region valid items
            $this->load->model("MdlTransaksi");
            $tr = new MdlTransaksi();

            $tr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");


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

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


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


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


            $tmpTrPrePacked = array();
            if (sizeof($id_top_source_cancel_packing) > 0) {
                $trPrePack = new MdlTransaksi();
                $trPrePack->setFilters(array());
                $trPrePack->addFilter("id_top in (" . implode(",", explode("-", $id_top_source_cancel_packing)) . ")");
                $trPrePack->addFilter("valid_qty>0");
                $trPrePack->addFilter("trash_4<1");
                $tmpTrPrePacked = $trPrePack->lookupJoined()->result();
            }
            else {
                $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");
                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


            //region take from registries
            //==ambil value-gate
            //            $trr = new MdlTransaksi();
            //            $trr->setFilters(array());
            //            $trr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
            //            $tmpReg = $trr->lookupRegistries()->result();

            $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();
            $mainElements = array();
            $mainInputs = array();
            $itemsKomposisi = array();
            if (sizeof($registryFields) > 0) {
                foreach ($registryFields as $param) {
                    //                    if(in_array($param, $filterField)){
                    //                        $tmpReg_result[$row->transaksi_id][$param] = blobDecode($row->$param);
                    //                    }
                    //
                    switch ($param) {
                        case "main"://
                            $main = $main + blobDecode($tmpTr[0]->$param);
                            break;
                        case "items"://
                            $items = $items + blobDecode($tmpTr[0]->$param);
                            break;
                        case "items2"://
                            $items2 = $items2 + blobDecode($tmpTr[0]->$param);
                            break;
                        case "rsltItems"://
                            $rsltItems = $rsltItems + blobDecode($tmpTr[0]->$param);
                            break;
                        case "rsltItems2"://
                            $rsltItems2 = $rsltItems2 + blobDecode($tmpTr[0]->$param);
                            break;
                        case "items2_sum"://
                            $items2_sum = $items2_sum + blobDecode($tmpTr[0]->$param);
                            break;
                        case "items3"://
                            $items3 = $items3 + blobDecode($tmpTr[0]->$param);
                            break;
                        case "items3_sum"://
                            $items3_sum = $items3_sum + blobDecode($tmpTr[0]->$param);
                            break;

                        case "tableIn_master"://
                            $masterTableInParams = $masterTableInParams + blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_detail"://
                            $childTableInParams = $childTableInParams + blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_detail_rsltItems"://
                            $childTableInParamsRsltItems = $childTableInParamsRsltItems + blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_detail_rsltItems2"://
                            $childTableInParamsRsltItems2 = $childTableInParamsRsltItems2 + blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_master_values"://
                            $masterTableInValueParams = $masterTableInValueParams + blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_detail_values"://
                            $childTableInValueParams = $childTableInValueParams + blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_detail_values_rsltItems"://
                            $childTableInValueParamsRsltItems = $childTableInValueParamsRsltItems + blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_detail_values_rsltItems2"://
                            $childTableInValueParamsRsltItems2 = $childTableInValueParamsRsltItems2 + blobDecode($tmpTr[0]->$param);
                            break;
                        case "main_add_values"://
                            $masterAddValues = $masterAddValues + blobDecode($tmpTr[0]->$param);
                            break;
                        case "main_add_fields"://
                            $masterAddFields = $masterAddFields + blobDecode($tmpTr[0]->$param);
                            break;

                        case "main_elements"://
                            $mainElements = blobDecode($tmpTr[0]->$param);
                            break;
                        case "main_inputs"://
                            $mainInputs = blobDecode($tmpTr[0]->$param);
                            break;
                        case "items_komposisi"://
                            $itemsKomposisi = blobDecode($tmpTr[0]->$param);
                            break;
                    }
                }
            }

            //            if (sizeof($tmpReg) > 0) {
            //                foreach ($tmpReg as $row) {
            //                    switch ($row->param) {
            //                        case "main"://
            //                            $main = $main + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "items"://
            //                            $items = $items + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "items2"://
            //                            $items2 = $items2 + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "rsltItems"://
            //                            $rsltItems = $rsltItems + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "rsltItems2"://
            //                            $rsltItems2 = $rsltItems2 + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "items2_sum"://
            //                            $items2_sum = $items2_sum + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "items3"://
            //                            $items3 = $items3 + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "items3_sum"://
            //                            $items3_sum = $items3_sum + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "tableIn_master"://
            //                            $masterTableInParams = $masterTableInParams + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "tableIn_detail"://
            //                            $childTableInParams = $childTableInParams + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "tableIn_detail_rsltItems"://
            //                            $childTableInParamsRsltItems = $childTableInParamsRsltItems + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "tableIn_detail_rsltItems2"://
            //                            $childTableInParamsRsltItems2 = $childTableInParamsRsltItems2 + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "tableIn_master_values"://
            //                            $masterTableInValueParams = $masterTableInValueParams + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "tableIn_detail_values"://
            //                            $childTableInValueParams = $childTableInValueParams + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "tableIn_detail_values_rsltItems"://
            //                            $childTableInValueParamsRsltItems = $childTableInValueParamsRsltItems + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "tableIn_detail_values_rsltItems2"://
            //                            $childTableInValueParamsRsltItems2 = $childTableInValueParamsRsltItems2 + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "main_add_values"://
            //                            $masterAddValues = $masterAddValues + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "main_add_fields"://
            //                            $masterAddFields = $masterAddFields + unserialize(base64_decode($row->values));
            //                            break;
            //                        case "main_elements"://
            //                            $mainElements = unserialize(base64_decode($row->values));
            //                            break;
            //                        case "main_inputs"://
            //                            $mainInputs = unserialize(base64_decode($row->values));
            //                            break;
            //                        case "items_komposisi"://
            //                            $itemsKomposisi = unserialize(base64_decode($row->values));
            //                            break;
            //                    }
            //                }
            //            }
            //            else {
            //                die("Cannot read the registry entries from $masterID!");
            //            }

            //endregion


            //region replacer Downpayment avail
            if (isset($mainInputs['dp'])) {
                if (isset($configUiJenis["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();

            //arrPrint($items);
            $itemChildData = array();
            if (sizeof($items) > 0) {
                if ($refecthAssamble) {
                    // matiHere("9999");
                    $this->load->model("Mdls/MdlProdukKomposisi");
                    $rf = new MdlProdukKomposisi();
                    $fields = $rf->getFields();
                    // arrPrint($fields);
                    $komposisiErr = array();
                    $komposisiData = array();
                    $kID = array();
                    $jmlProd = array();
                    // $jmlItems = 0;
                    foreach ($items as $xid => $iSpec) {
                        $kID[] = $iSpec['id'];
                        $tmpKom = $rf->lookupByPID($iSpec['id'])->result();
                        if (sizeof($tmpKom) == 0) {
                            $komposisiErr[] = $iSpec['nama'];
                            // matiHEre("komposisi produk " .$iSpec['nama']." belum ditentukan!");
                        }
                        $jmlProd[$iSpec['id']] = $iSpec['jml'];

                        // arrPrint($komposisiData);

                    }
                    // arrPrint($jmlProd);
                    // matiHEre();
                    if (sizeof($komposisiErr) > 0) {
                        $hasil = "";
                        $no = 0;

                        foreach ($komposisiErr as $pId => $item) {
                            // matiHEre($item);
                            $no++;
                            $nama_f = htmlspecialchars($item);
                            $var = "<span class='font-size-0-7'>$no. <span style='font-weight:bold;'>$nama_f</span>";
                            if ($hasil == "") {
                                $hasil = "$var";
                            }
                            else {
                                $hasil = "$hasil<br>$var";
                            }
                            $hasil .= "<br><br><span style='font-wight:bold;' class='text-danger'>Silahkan lengkapi data produk pada bagian komposisi produk.<br> Transaksi tidak dapat dilanjutkan sampai komposisi produk lengkap.</span>";


                        }
                        // if (sizeof($kurangStoks) > 0) {

                        $alerts = array(
                            "type" => "warning",
                            "title" => "komposisi produk belum ditentukan",
                            "html" => $hasil,
                        );
                        echo swalAlert($alerts);
                        die();
                        // }
                        // matiHere($komposisiErr . " belum ditentukan, silahkan periksa komposisi produk");
                    }
                    else {
                        cekLime("here u are");
                        $rf->setfilters(array());
                        $rf->addFilter("produk_id in ('" . implode("','", $kID) . "')");
                        $dataKomposisi = $rf->lookUpAll()->result();
                        $ix = 0;
                        if (sizeof($tmpKom) > 0) {
                            $items2Sum = array();
                            $listedBahan = array();
                            $jmlItem = 0;
                            foreach ($dataKomposisi as $komTmp) {

                                $ix++;
                                $reqValue = $jmlProd[$komTmp->produk_id];
                                $itemsKomposisi[$komTmp->produk_id][$komTmp->jenis][$ix] = $komTmp;
                                $items2[$komTmp->produk_id][$komTmp->jenis][$ix] = array(
                                    "handler" => "",
                                    "id" => $komTmp->produk_dasar_id,
                                    "nama" => $komTmp->produk_dasar_nama,
                                    "jml" => $komTmp->jml,
                                    "satuan" => $komTmp->satuan_nama,
                                    "nilai" => $komTmp->nilai,
                                    "sub_nilai" => $komTmp->jml * $komTmp->nilai,
                                );

                                $listedBahan[$komTmp->produk_id][$komTmp->produk_dasar_id] = array(
                                    "id" => $komTmp->produk_dasar_id,
                                    "nama" => $komTmp->produk_dasar_nama,
                                    "jml" => $komTmp->jml * $jmlProd[$komTmp->produk_id],
                                    "satuan" => $komTmp->satuan_nama,
                                    "placeID" => $main['placeID'],
                                    "placeName" => $main['placeName'],
                                    "toko_id" => $this->session->login['toko_id'],
                                    "olehID" => $main['olehID'],
                                    "olehName" => $main['olehName'],
                                );
                            }

                            if (sizeof($listedBahan) > 0) {

                                $sumData = array();
                                $valjml = array();
                                foreach ($listedBahan as $pID => $bahanData) {
                                    // arrPrint($bahanData);

                                    foreach ($bahanData as $bID => $bData) {
                                        // arrPrint($bData);
                                        if (!isset($valjml[$bID])) {
                                            $valjml[$bID] = 0;
                                        }
                                        $valjml[$bID] += $bData['jml'];
                                        $sumData[$bID] = array(
                                            "id" => $komTmp->id,
                                            "nama" => $bData['nama'],
                                            "jml" => 0,
                                            "satuan" => $bData['satuan'],
                                            "placeID" => $bData['placeID'],
                                            "placeName" => $bData['placeName'],
                                            "toko_id" => $bData['toko_id'],
                                            "olehID" => $bData['olehID'],
                                            "olehName" => $bData['olehName'],
                                        );
                                    }
                                }
                                // arrPrint($listedBahan);
                                $items2_sum = array();
                                foreach ($sumData as $bahanID => $bahanData) {
                                    if (isset($valjml[$bahanID])) {
                                        $bahanData['jml'] = $valjml[$bahanID];
                                    }
                                    $items2_sum[$bahanID] = $bahanData;
                                    // $bahanData['jml'] = isset($valjml[$bahanID]) ? ($valjml[$bahanID] :$bahanData
                                }

                                // arrPrint($item2_sum);
                                // arrPrint($listedBahan);
                            }
                        }
                        // arrPrint($);
                    }
                    // arrPrint($listedBahan);
                    // matiHEre("inject items2");
                }
                foreach ($items as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $tipeSize = isset($iSpec['detilSize']) && sizeof($iSpec['detilSize']) > 0 ? $iSpec['detilSize'] : "";

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

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


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

                                    }
                                    else {
                                        if (isset($tmp[$val2])) {
                                            $newSrc = str_replace($val2, $items[$val2], $newSrc);

                                        }
                                        else {
                                            $newSrc = str_replace($val2, "0", $newSrc);

                                        }
                                    }


                                }
                                $subtotal = $cal->calculate($newSrc);


                            }
                            else {
                                //                            echo lgShowAlert("memasang subtotal dari $subAmountConfig");
                                $subtotal = $items[$id][$subAmountConfig];

                            }
                        }
                        else {
                            //                        echo lgShowAlert("tidak mengapa-apakan subtotal");
                            $subtotal = 0;

                        }

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

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

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

                        //endregion

                        if (sizeof($connectedOptionFields) > 0) {
                            if ($connectedOptionFields['followup'] == false) {

                                $mdlPair = $connectedOptionFields['mdlName'];
                                $modelFilter = $connectedOptionFields['mdlFilter'];
                                $selectedFields = $connectedOptionFields['selectedFields'];
                                $indexFields = $connectedOptionFields['fields'];
                                $this->load->model("Mdls/" . $mdlPair);
                                $mp = new $mdlPair();
                                if (sizeof($modelFilter) > 0) {
                                    foreach ($modelFilter as $f) {
                                        $f_ex = explode("=", $f);
                                        if (!isset($f_ex[1])) {
                                            $f_ey = explode(">", $f_ex[0]);
                                            if (substr($f_ey[1], 0, 1) == ".") {
                                                $mp->addFilter($f_ey[0] . ">'" . ltrim($f_ey[1], ".") . "'");
                                            }
                                            else {
                                                if (isset($iSpec[$f_ey[1]])) {
                                                    $mp->addFilter($f_ey[0] . ">'" . $iSpec[$f_ey[1]] . "'");
                                                }
                                                else {
                                                    $mp->addFilter($f_ey[0] . ">0");
                                                }
                                            }
                                        }
                                        else {
                                            if (substr($f_ex[1], 0, 1) == ".") {
                                                $mp->addFilter($f_ex[0] . "='" . ltrim($f_ex[1], ".") . "'");
                                            }
                                            else {
                                                if (isset($iSpec[$f_ex[1]])) {
                                                    $mp->addFilter($f_ex[0] . "='" . $iSpec[$f_ex[1]] . "'");
                                                }
                                                else {
                                                    $mp->addFilter($f_ex[0] . "=''");
                                                }

                                            }
                                        }
                                    }
                                }
                                $tmpPair = $mp->lookUpAll()->result();
                                //                                cekLime("LINE: " . __LINE__);
                                //                                arrPrint($tmpPair);
                                $pairResultTmp = array();
                                if (sizeof($tmpPair) > 0) {
                                    foreach ($tmpPair as $tmpPair0) {
                                        $tmpPairData = array();
                                        foreach ($selectedFields as $col) {
                                            $tmpPairData[$col] = $tmpPair0->$col;
                                        }
                                        $pairResultTmp[$tmpPair0->id] = $tmpPairData;
                                    }

                                }
                                $resultPairserial[$id][$indexFields] = $pairResultTmp;
                            }
                        }

                        if ((isset($resultPairserial)) && sizeof($resultPairserial) > 0) {

                            $_SESSION[$cCode]["pair_ext"] = $resultPairserial;
                        }

                        if (sizeof($itemsKomposisi) > 0) {
                            if (array_key_exists($id, $itemsKomposisi)) {
                                //                                cekBiru(":: ADA komposisinya yaitu $id ::");
                                foreach ($items2[$id] as $jenis_komposisi => $iiSpec) {

                                    foreach ($iiSpec as $ee => $eeSpec) {
                                        $komposisi = $itemsKomposisi[$id][$jenis_komposisi][$ee];
                                        // re-kalkulasi gerbang items2
                                        $items2[$id][$jenis_komposisi][$ee]['jml'] = $komposisi->jml * $validItems[$id];
                                        $items2[$id][$jenis_komposisi][$ee]['sub_nilai'] = $komposisi->nilai * $validItems[$id];

                                    }
                                }
                            }
                        }


                    }
                    else {
                        unset($items[$id]);
                        unset($items2[$id]);
                        unset($childGates[$id]);
                        unset($childTableInParams[$id]);
                        unset($childTableInValueParams[$id]);

                    }
                }


                if (sizeof($itemsKomposisi) > 0) {
                    $items2_sum = array();// supplies-nya...
                    $items3_sum = array();// biaya-nya...
                    foreach ($items2 as $pID => $pSpec) {
                        foreach ($pSpec as $jenis => $jSpec) {
                            foreach ($jSpec as $eSpec) {
                                if ($jenis == "produk") {
                                    if (!isset($items2_sum[$eSpec['id']])) {
                                        $items2_sum[$eSpec['id']] = $eSpec;
                                        $items2_sum[$eSpec['id']]['jml'] = 0;
                                        $items2_sum[$eSpec['id']]['produk_ids'] = array();
                                    }
                                    $items2_sum[$eSpec['id']]['jml'] += $eSpec['jml'];
                                    $items2_sum[$eSpec['id']]['produk_ids'][$pID] = $pID;
                                }
                                if ($jenis == "biaya") {
                                    if (!isset($items3_sum[$eSpec['id']])) {
                                        $items3_sum[$eSpec['id']] = $eSpec;
                                        $items3_sum[$eSpec['id']]['jml'] = 0;
                                        $items3_sum[$eSpec['id']]['sub_nilai'] = 0;
                                        $items3_sum[$eSpec['id']]['produk_ids'] = array();
                                    }
                                    $items3_sum[$eSpec['id']]['jml'] += $eSpec['jml'];
                                    $items3_sum[$eSpec['id']]['sub_nilai'] += $eSpec['sub_nilai'];
                                    $items3_sum[$eSpec['id']]['produk_ids'][$pID] = $pID;
                                }
                            }
                        }
                    }
                }

            }

            if (sizeof($itemsChild) > 0 && ($itemsChildGate == 'main')) {
                //                arrPrint($main);
                $fieldAlias = isset($configUiJenis["shopingCartDetailFields"][$stepNumber]['fieldAlias']) ? $configUiJenis["shopingCartDetailFields"][$stepNumber]['fieldAlias'] : $itemsChild;//dipake detil pembelian aset
                foreach ($fieldAlias as $col => $col_label) {
                    $itemChildData[$main['pihakMainRulesID']][1][$col] = isset($main[$col_label]) ? $main[$col_label] : "";
                }
                $itemChildData[$main['pihakMainRulesID']][1]["jml"] = 1;
                $itemChildData[$main['pihakMainRulesID']][1]["qty"] = 1;
                $itemChildData[$main['pihakMainRulesID']][1]["folders"] = $main['pihakID'];
                cekBiru("main");
            }

            //            arrPrint($itemChildData);
            //            matiHEre();
            ////            cekHere("cetaik items");
            ////            arrPrint($items);
            //            cekHere("cetaik items2");
            //            arrprint($items2);
            //            cekHere("cetaik items3_sum");
            //            arrprint($items3_sum);
            //            cekHere("cetaik item komposisi");
            //            arrprint($itemsKomposisi);
            //            mati_disini();

            //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,
                "items_komposisi" => $itemsKomposisi,
            );
            foreach ($swappers as $targetVar => $src) {
                $_SESSION[$cCode][$targetVar] = $src;

            }
            //endregion

            //region sub itemtarget
            $pairedSubItemTarget = isset($configUiJenis['shoppingCartPairedSubItem'][$afterTargetStepNum]['targetGateName']) ? $configUiJenis['shoppingCartPairedSubItem'][$afterTargetStepNum]['targetGateName'] : NULL;
            //            cekHere("$this->jenisTr :: $afterTargetStepNum " . $pairedSubItemTarget);
            //            matiHEre($pairedSubItemTarget);
            if ($pairedSubItemTarget != NULL) {

                foreach ($_SESSION[$cCode]['items'] as $pID => $spec) {
                    if (!isset($_SESSION[$cCode]['items2'][$pID])) {
                        $spec['qty'] = 0;
                        $spec['jml'] = 0;
                        $_SESSION[$cCode]['items2'][$pID][0] = $spec;
                    }
                }
                //                cekHere("cetak items2");
                //                arrPrint($_SESSION[$cCode]['items2']);
            }
            //endregion

            //==init replacer


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

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

                }
            }

            $this->load->helper("he_value_builder");
            resetValues($this->jenisTr);
            // function fillValues($jenisTr, $fromStep = 0, $intoStep = 0, $configCoreJenis, $configUiJenis)
            fillValues($this->jenisTr, $idTr, $stepNumber, $this->configCoreJenis, $this->configUiJenis);

            // cekBiru($rawBuilderURL);
            // matiHere();
            $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("Transaksi sudah tidak ditemukan, Silahkan merefresh browser, untuk memperbarui data"));
        }


    }

    /*followUp II previewe*/
    public function followupPreview_modul()
    {
        // cekHijau(url_segment(), "@" . __LINE__ ." ". __METHOD__ . __CLASS__ );
        // cekOrange(my_memberships(), "@" . __LINE__ ." ". __METHOD__ . __CLASS__ );
        // cekKuning($_SERVER['PHP_SELF']);
        // cekBiru(blobEncode(current_url()));

        $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'] : "";
        // matiHere(__METHOD__);
        $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();
        $registryFields = $tr->getRegistryFields();
        $tr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
        $tr->addFilter("sub_step_number='" . $currentStepNum . "'");
        $tmpTr = $tr->lookupJoined()->result();
        // showLast_query("merah");

        //endregion

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

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

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

            $cCode = "_TR_" . $this->jenisTr;

            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "items2" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            if (!isset($_SESSION[$cCode]['items2'])) {
                $_SESSION[$cCode]['items2'] = array();
            }
            //endregion
            $detailSizeKey = isset($_SESSION[$cCode]['main_elements']['detilSize']['key']) ? $_SESSION[$cCode]['main_elements']['detilSize']['key'] : array();
            $trID = $tmpTr[0]->transaksi_id;
            /* ----------------------------------------------
             * digeser ngambil dr ui biar satu titik
             * teryata harus dr layout karenan menyesuaikan kiriman item2 8/2 dikembalikan
             * ----------------------------------*/
            $itemLabels = isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][$targetStepNum]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][$targetStepNum] : array();
            // $itemLabels = isset($configUiJenis['shoppingCartFields'][$targetStepNum]) ? $configUiJenis['shoppingCartFields'][$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();
            $itemSubLabels = isset($this->configLayout[$this->jenisTr]['receiptSubDetailFields'][$targetStepNum]) ? $this->configLayout[$this->jenisTr]['receiptSubDetailFields'][$targetStepNum] : array();
            // -------
            $itemNumLabels = isset($configUiJenis['shoppingCartNumFields'][$targetStepNum]) ? $configUiJenis['shoppingCartNumFields'][$targetStepNum] : array();
            $itemNumLabels2 = isset($configUiJenis['shoppingCartNumFields2'][$targetStepNum]) ? $configUiJenis['shoppingCartNumFields2'][$targetStepNum] : array();
            $itemNumLabels3 = isset($configUiJenis['shoppingCartNumFields3'][$targetStepNum]) ? $configUiJenis['shoppingCartNumFields3'][$targetStepNum] : array();
            $subAmountConfig = isset($configUiJenis['shoppingCartAmountValue'][$targetStepNum]) ? $configUiJenis['shoppingCartAmountValue'][$targetStepNum] : null;
            $noteEnabled = isset($configUiJenis['shoppingCartNoteEnabled']) && $configUiJenis['shoppingCartNoteEnabled'] == true ? true : false;
            $noteEditabled = isset($configUiJenis['shoppingCartNoteEditabled'][$targetStepNum]) ? $configUiJenis['shoppingCartNoteEditabled'][$targetStepNum] : false;
            $noteAdditionalEditabled = isset($configUiJenis['shoppingCartNoteAdditionalEditabled'][$targetStepNum]) ? $configUiJenis['shoppingCartNoteAdditionalEditabled'][$targetStepNum] : false;
            $noteFollowupEditabled = isset($configUiJenis['followupMainNote'][$targetStepNum]) ? $configUiJenis['followupMainNote'][$targetStepNum] : array();
            $noteType = isset($configUiJenis['shoppingCartNoteType']) ? $configUiJenis['shoppingCartNoteType'] : "text";
            $addRowsConfigs = isset($configUiJenis['additionalRows']) ? $configUiJenis['additionalRows'] : array();
            $imageEnabled = isset($configUiJenis['shoppingCartImageEnabled']) && $configUiJenis['shoppingCartImageEnabled'] == true ? true : false;
            $imageType = isset($configUiJenis['shoppingCartImageType']) ? $configUiJenis['shoppingCartImageType'] : "text";
            $showPoStatus = isset($configUiJenis['showPoStatus']) ? $configUiJenis['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);


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


            //region take from registries

            //==ambil value-gate
            //            $tr->setFilters(array());
            //            $tr->addFilter("trash='0'");
            //            $tmpReg = $tr->lookupRegistriesByMasterID($masterID)->result();

            $main = array();
            $items = array();
            $masterGates = array();
            $childGates = array();
            $masterTableInParams = array();
            $childTableInParams = array();
            $masterTableInValueParams = array();
            $childTableInValueParams = array();
            $masterAddValues = array();
            $masterAddFields = array();
            $mainElements = array();
            $itemsKomposisi = array();
            if (sizeof($registryFields) > 0) {
                foreach ($registryFields as $param) {
                    //                    if(in_array($param, $filterField)){
                    //                        $tmpReg_result[$row->transaksi_id][$param] = blobDecode($row->$param);
                    //                    }
                    //
                    switch ($param) {
                        case "main"://
                            $main = blobDecode($tmpTr[0]->$param);
                            break;
                        case "items"://
                            $items = blobDecode($tmpTr[0]->$param);
                            break;
                        case "items2"://
                            $items2 = blobDecode($tmpTr[0]->$param);
                            break;
                        case "items2_sum"://
                            $items2_sum = blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_master"://
                            $masterTableInParams = blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_detail"://
                            $childTableInParams = blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_master_values"://
                            $masterTableInValueParams = blobDecode($tmpTr[0]->$param);
                            break;
                        case "tableIn_detail_values"://
                            $childTableInValueParams = blobDecode($tmpTr[0]->$param);
                            break;
                        case "main_add_values"://
                            $masterAddValues = blobDecode($tmpTr[0]->$param);
                            break;
                        case "main_add_fields"://
                            $masterAddFields = blobDecode($tmpTr[0]->$param);
                            break;
                        case "main_elements"://
                            $mainElements = blobDecode($tmpTr[0]->$param);
                            break;
                        case "items_komposisi"://
                            $itemsKomposisi = blobDecode($tmpTr[0]->$param);
                            break;
                    }
                }
            }

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

            //endregion


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


            $arrTest = array();
            $totalValidQty = 0;
            $totalOrdJml = 0;
            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;


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

            }

            if ($totalValidQty == $totalOrdJml) {
                $partialCanceled = true;
            }
            if ($totalOrdJmlMaster != $totalOrdJml) {
                $rejectAllAllowed = false;
            }
        }
        else {

            $errMsg = "Transaksi yg anda cari sudah tidak ada<br>";
            $errMsg .= "cobalah untuk me-refresh browser dengan F5 pada keyboard.<br>";
            // $errMsg .= "if this error re-occurs, please contact system developer.<br>";


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

        // matiHere(__METHOD__);
        $items = array();
        $items2 = array();

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


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

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

        // cekBiru($allowedAction);
        //endregion

        //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();
        $userGroup_editElementAllowed = $this->config->item("userGroup_editElementAllowed") != NULL ? $this->config->item("userGroup_editElementAllowed") : array();
        $thisStepGID = isset($configUiJenis['steps'][$currentStepNum]['userGroup']) ? $configUiJenis['steps'][$currentStepNum]['userGroup'] : "";
        $nextStepGID = isset($configUiJenis['steps'][$targetStepNum]['userGroup']) ? $configUiJenis['steps'][$targetStepNum]['userGroup'] : "";
        $hideFollowUp = isset($configUiJenis['steps'][$targetStepNum]['hideFollowUp']) ? $configUiJenis['steps'][$targetStepNum]['hideFollowUp'] : false;
        $editElementAllowed = array_intersect($userGroup_editElementAllowed, $mems);
        $allowFollowup = isset($configUiJenis['steps'][$targetStepNum]['allowFollowup']) ? $configUiJenis['steps'][$targetStepNum]['allowFollowup'] : true;

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

        $deleteSpec = array(
            "label" => "cannot delete",
            "targetUrl" => "",
            "warning" => "",
        );

        $undoSpec = array(
            "label" => "cannot undo",
            "targetUrl" => "",
            "warning" => "",
        );

        $rejectionSpec = array(
            "label" => "cannot reject 1 step",
            "targetUrl" => "",
            "warning" => "",
        );

        $rejectionSpecAll = array(
            "label" => "cannot reject all steps",
            "targetUrl" => "",
            "warning" => "",
        );

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

        $editSpec = array(
            "label" => "cannot edit",
            "targetUrl" => "",
            "warning" => "",
        );

        $evPre = evaluatePreProcessors($this->jenisTr, $currentStepNum);
        $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
        $evCom = evaluateComponents($this->jenisTr, $currentStepNum);

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

        //==delete, hanya pelaku yang membuat transaksi dan step 1
        if (($origTCode == null) && ($currentStepNum == 1) && ($pelaku == $this->session->login['id']) &&
            placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum, "delete", $this->configUiJenis)) {//$targetStepNum
            if (isset($_SESSION[$cCode]['lockerPayment']['allowedUndone']) && $_SESSION[$cCode]['lockerPayment']['allowedUndone'] == true) {
                if ($_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                    $evPre = evaluatePreProcessors($this->jenisTr, $currentStepNum);
                    $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
                    $evCom = evaluateComponents($this->jenisTr, $currentStepNum);
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $deleteSpec = array(
                            "label" => "delete",
                            // "targetUrl" => base_url() . $this->uri->segment(1) . "/doRevert/$no/$jenisTr/$masterRevertStep/$childRevertStep/$currentStepNum",
                            "targetUrl" => $doRevertLink,
                            "warning" => "pressing REJECT will set this entry one step behind. continue?",
                        );
                    }
                    else {
                    }
                }
                else {
                    //                    cekungu("bukan credit");
                    $evPre = evaluatePreProcessors($this->jenisTr, $currentStepNum);
                    $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
                    $evCom = evaluateComponents($this->jenisTr, $currentStepNum);
                    //                    cekUngu("delete pre:$evPre, post:$evPost, com:$evCom");
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT || LINE: " . __LINE__);
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);
                        $deleteSpec = array(
                            "label" => "delete",
                            "targetUrl" => $doRevertLink,
                            "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'])) {
                $evPre = evaluatePreProcessors($this->jenisTr, $currentStepNum);
                $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
                $evCom = evaluateComponents($this->jenisTr, $currentStepNum);
                if ($evPre == null && $evPost == null && $evCom == null) {
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $deleteSpec = array(
                        "label" => "safely delete",
                        "targetUrl" => $doRevertLink,
                        "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($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $currentStepNum, "undo", $this->configUiJenis)) {

            if (isset($_SESSION[$cCode]['lockerPayment']['allowedUndone']) && $_SESSION[$cCode]['lockerPayment']['allowedUndone'] == true) {
                if (isset($_SESSION[$cCode]['main']['paymentMethod']) && $_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                    $evPre = evaluatePreProcessors($this->jenisTr, $currentStepNum);
                    $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
                    $evCom = evaluateComponents($this->jenisTr, $currentStepNum);
                    //                    cekHere("$evPre :: $evPost :: $evCom");
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT");
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);

                        $rejectionSpec = array(
                            "label" => "reject",
                            "targetUrl" => $doRevertLink,
                            "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" => $doRevertLink,
                            "warning" => "pressing UNDO will set this entry one step behind. continue?",
                        );
                    }
                }
            }
            else {
                //                if (!isset($_SESSION[$cCode]['main']['paymentMethod'])) {

                //                cekLime("allowed to undo");
                $evPre = evaluatePreProcessors($this->jenisTr, $currentStepNum);
                $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
                $evCom = evaluateComponents($this->jenisTr, $currentStepNum);
                //                cekmerah("evPre: $evPre, evPos: $evPost, evCom: $evCom");
                if ($evPre == null && $evPost == null && $evCom == null) {
                    //                cekhijau("allowed to undo");
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $undoSpec = array(
                        "label" => "undo last step",
                        "targetUrl" => $doRevertLink,
                        "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($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "reject", $this->configUiJenis)) {//$targetStepNum
            //            cekHijau("ready to reject");
            if (isset($_SESSION[$cCode]['lockerPayment']['allowedUndone']) && $_SESSION[$cCode]['lockerPayment']['allowedUndone'] == true) {
                //                cekKuning("kena if locker payment");
                if (isset($_SESSION[$cCode]['main']['paymentMethod']) && $_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                    $evPre = evaluatePreProcessors($this->jenisTr, $currentStepNum);
                    $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
                    $evCom = evaluateComponents($this->jenisTr, $currentStepNum);
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT || LINE: " . __LINE__);
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);

                        $rejectionSpec = array(
                            "label" => "reject 1 step",
                            "targetUrl" => $doRevertLink,
                            "warning" => "pressing REJECT will set this entry one step behind. continue?",
                        );

                        if ($rejectAllAllowed == true) {

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

                }
                else {
                    $evPre = evaluatePreProcessors($this->jenisTr, $currentStepNum);
                    $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
                    $evCom = evaluateComponents($this->jenisTr, $currentStepNum);
                    //                    cekUngu("pre:$evPre, post:$evPost, com:$evCom");
                    if ($evPre == null && $evPost == null && $evCom == null) {
                        //                        cekhijau("allowed to REJECT || LINE: " . __LINE__);
                        $masterRevertStep = ($currentStepNum - 1);
                        $childRevertStep = -($currentStepNum);

                        $rejectionSpec = array(
                            "label" => "reject 1 step",
                            "targetUrl" => $doRevertLink,
                            "warning" => "pressing REJECT will set this entry one step behind. continue?",
                        );

                        if ($rejectAllAllowed == true) {

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

                }
            }
            else {

                $evPre = evaluatePreProcessors($this->jenisTr, $currentStepNum);
                $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
                $evCom = evaluateComponents($this->jenisTr, $currentStepNum);
                //                cekHitam("evPreProcc: $evPre, evPostProcc: $evPost, evCom: $evCom");
                if ($evPre == null && $evPost == null && $evCom == null) {
                    //                    cekhijau("allowed to REJECT || LINE: " . __LINE__);
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $rejectionSpec = array(
                        "label" => "reject 1 step",
                        "targetUrl" => $doRevertLink,
                        "warning" => "pressing REJECT will set this entry one step behind. continue?",
                    );
                    if ($rejectAllAllowed == true) {

                        $rejectionSpecAll = array(
                            "label" => "reject all steps",
                            "targetUrl" => $doRevertAllLink,
                            "warning" => "Dengan klik REJECT ALL transaksi ini akan dimatikan dan tidak bisa digunakan lagi. Apakah akan melanjutkan?",
                        );
                    }
                }
                else {
                    cekmerah("NOT allowed to REJECT || LINE: " . __LINE__);
                }

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


        //edit, hanya pelaku yang membuat transaksi dan step 1
        if (($origTCode == null) && ($currentStepNum > 0) && ($pelaku == $this->session->login['id']) &&
            placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "edit", $this->configUiJenis)) {
            $evPre = evaluatePreProcessors($this->jenisTr, $currentStepNum);
            $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
            $evCom = evaluateComponents($this->jenisTr, $currentStepNum);
            $evMaster = evaluateMain($this->jenisTr, $currentStepNum);
            //            cekHere("$evPre :: $evPost :: $evCom :: -- $evMaster");
            if ($evPre == null && $evPost == null && $evCom == null && $evMaster == null) {
                //                cekhijau("allowed to EDIT");
                $editSpec = array(
                    "label" => "edit",
                    "targetUrl" => base_url() . $this->uri->segment(1) . "/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($this->jenisTr, $currentStepNum);
                $evPost = evaluatePostProcessors($this->jenisTr, $currentStepNum);
                $evCom = evaluateComponents($this->jenisTr, $currentStepNum);
                $evMaster = evaluateMain($this->jenisTr, $currentStepNum);
                //            arrPrint("$evPre :: $evPost :: $evCom");
                if ($evPre == null && $evPost == null && $evCom == null && $evMaster == null) {
                    //                    cekhijau("allowed to EDIT");
                    $editSpec = array(
                        "label" => "edit",
                        "targetUrl" => base_url() . $this->uri->segment(1) . "/doPreEdit/$no/$jenisTr/$currentStepNum",
                        "warning" => "pressing EDIT will modify entire transaction data. continue?",
                    );
                }
                else {
                    //                    cekmerah("NOT allowed to EDIT");
                }
            }
        }


        //==approve
        // $allowFollowup = true;
        // cekMerah($allowFollowup);
        // cekBiru($targetStepNum);
        // cekKuning($currentStepNum);
        // arrPrint($approvalSpec);

        if ($targetStepNum > $currentStepNum) {
            // cekOrange($approvalSpec,"sebelum " . __LINE__);
            if ($allowFollowup == true) {
                if (isset($_SESSION[$cCode]['lockerPayment']['allowedFollow']) && $_SESSION[$cCode]['lockerPayment']['allowedFollow'] == true) {
                    if (isset($_SESSION[$cCode]['main']['paymentMethod']) && $_SESSION[$cCode]['main']['paymentMethod'] == "credit") {
                        if (isset($this->accessList[$this->jenisTr])) {
                            if (isset($this->accessList[$this->jenisTr][$targetStepNum])) {

                                $paymentSrcCek = isset($configUiJenis['steps'][$targetStepNum]['paymentSrc']) ? $configUiJenis['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" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                                "label" => $paymentSrcCek['label'],
                                            );
                                        }
                                        else {
                                            $approvalSpec = array(
                                                //                                            "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                                "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                                "targetUrl" => $doFollowupLink,
                                                "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            //                                        "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                            "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => $doFollowupLink,
                                            "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                    "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => $doFollowupLink,
                                        "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                        }
                        else {
                            if (placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum)) {
                                //                cekBiru(":: $currentStepNum :: $targetStepNum ::");
                                $paymentSrcCek = isset($configUiJenis['steps'][$targetStepNum]['paymentSrc']) ? $configUiJenis['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" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                                "label" => $paymentSrcCek['label'],
                                            );
                                        }
                                        else {
                                            $approvalSpec = array(
                                                //                                            "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                                "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                                "targetUrl" => $doFollowupLink,
                                                "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                            );
                                            if ($hideFollowUp) {
                                                $approvalSpec = array();
                                            }
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            //                                        "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                            "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => $doFollowupLink,
                                            "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "targetUrl" => $doFollowupLink,
                                        "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                            }
                        }
                    }
                    else {
                        //                    $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                        //                        "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                        //                        "label" => isset($_SESSION[$cCode]['lockerPayment']['label']) ? $_SESSION[$cCode]['lockerPayment']['label'] . " belum dilakukan. Segera hubungi pihak Finance." : "Segera hubungi pihak Finance untuk follow up",
                        //                    );
                        //                    cekUngu("approve : " . placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum));
                        if (placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum)) {
                            $approvalSpec = array(
                                "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                "targetUrl" => $doFollowupLink,
                                "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                            );
                        }
                        else {
                            cekUngu("tidak ada approve");
                        }
                    }
                }
                else {
                    // cekBiru("@" . __LINE__ . " " . __METHOD__);
                    // arrPrintPink($this->accessList);
                    if (isset($this->accessList[$this->jenisTr])) {

                        if (isset($this->accessList[$this->jenisTr][$targetStepNum])) {

                            //                    $approvalSpec = array(
                            //                        "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                            //                        "targetUrl" => $doFollowupLink,
                            //                        "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                            //                    );
                            $paymentSrcCek = isset($configUiJenis['steps'][$targetStepNum]['paymentSrc']) ? $configUiJenis['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" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                        );
                                        $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                            "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                            "label" => $paymentSrcCek['label'],
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => $doFollowupLink,
                                            "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                    "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => $doFollowupLink,
                                        "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {

                                $approvalSpec = array(
                                    //                                "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                    "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                    "targetUrl" => $doFollowupLink,
                                    "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                );

                                if (isset($hideFollowUp)) {
                                    // $approvalSpec = array();
                                }
                            }
                        }
                    }
                    else {

                        if (placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->configUiJenis)) {
                            //                cekBiru(":: $currentStepNum :: $targetStepNum ::");
                            $paymentSrcCek = isset($configUiJenis['steps'][$targetStepNum]['paymentSrc']) ? $configUiJenis['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" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                        );
                                        $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                                            "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                                            "label" => $paymentSrcCek['label'],
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                    else {
                                        $approvalSpec = array(
                                            "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => $doFollowupLink,
                                            "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                    "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => $doFollowupLink,
                                        "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                                // cekLime(__LINE__)
                                /* ------------------------------------------------------------------
                                 * approval button
                                 * ------------------------------------------------------------------*/
                                $approvalSpec = array(
                                    //                                "label" => isset($configUiJenis['steps'][$targetStepNum]['actionLabel']) ? $configUiJenis['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                    "label" => isset($configUiJenis['steps'][$targetStepNum]['buttonLabel']) ? $configUiJenis['steps'][$targetStepNum]['buttonLabel'] : $configUiJenis['steps'][$targetStepNum]['actionLabel'],
                                    "targetUrl" => $doFollowupLink,
                                    "warning" => "Dengan menekan OK berarti transaksi akan disimpan ke step berikutnya. Lanjutkan?",
                                );
                                // cekBiru($hideFollowUp);
                                if ($hideFollowUp) {
                                    $approvalSpec = array();
                                }
                            }
                        }
                        else {

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

        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, "", $configUiJenis)) {
                //                if (in_array($configUiJenis['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 " . $configUiJenis['steps'][$currentStepNum]['label'];
                        $revertLabel = "undo";
                        $childRevertStep = -($currentStepNum);
                        $revertTarget = $doRevertLink;

                    }
                }
                else {
                    $allowRevert = true;
                    //                    $revertLabel = $masterRevertStep . "undo " . $configUiJenis['steps'][$currentStepNum]['label'];
                    $revertLabel = "undo";
                    $childRevertStep = -($currentStepNum);
                    $revertTarget = $doRevertLink;
                }

            }
            //            }
        }
        //endregion


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

        if (isset($configUiJenis['steps'][$targetStepNum])) {
            if (placeCanFollowupTrans($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $configUiJenis)) {
                //            if (in_array($configUiJenis['steps'][$targetStepNum]['userGroup'], $this->session->login['membership'])) {
                $allowFollowup = true;
                $buttonLabel = $configUiJenis['steps'][$targetStepNum]['actionLabel'];
                $acceptTarget = base_url() . $this->modul . "/FollowUp/doFollowup/$jenisTr/$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 = base_url() . $this->modul . "/FollowUp/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

        //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");
                    }
                }
            }
        }
        else {
            //                echo("no preval defined. skipping preval..<br>");
        }

        //endregion


        //
        //region preview bottom elements

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

        //endregion

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

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

        $msgWarning = $va->validate2();

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

        //
        //region prepare params for viewer

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

        }


        $editableElements = array();
        $elementConfigs = isset($configUiJenis['receiptElements']) ? $configUiJenis['receiptElements'] : array();
        $relElementConfigs = isset($configUiJenis['relativeElements']) ? $configUiJenis['relativeElements'] : array();
        $relOptionConfigs = isset($configUiJenis['relativeOptions']) ? $configUiJenis['relativeOptions'] : array();
        $xShipmentConfig = isset($configUiJenis['xShipmentConfig']) ? $configUiJenis['xShipmentConfig'] : array();
        $itemsChildLabel = isset($configUiJenis['shopingCartDetailFields'][$targetStepNum]['fields']) ? $configUiJenis['shopingCartDetailFields'][$targetStepNum]['fields'] : array();
        $itemsChildEditable = isset($configUiJenis['shopingCartDetailFields'][$targetStepNum]['editable']) ? $configUiJenis['shopingCartDetailFields'][$targetStepNum]['editable'] : array();
        $itemsChildGate = isset($configUiJenis['shopingCartDetailFields'][$targetStepNum]['gate']) ? $configUiJenis['shopingCartDetailFields'][$targetStepNum]['gate'] : "none";
        $addRowsConfigs = isset($configUiJenis['additionalRows']) ? $configUiJenis['additionalRows'] : array();
        $shoppingCartInputType = isset($configUiJenis['shoppingCartInputType'][$targetStepNum]) ? $configUiJenis['shoppingCartInputType'][$targetStepNum] : array();
        if (sizeof($_SESSION[$cCode]['main_elements']) > 0) {

            if (sizeof($elementConfigs) > 0) {
                foreach ($elementConfigs as $aKey => $aSpec) {
                    //                    cekHijau("receipt element $aKey");
                    if (array_key_exists($aKey, $mainElements) && in_array($targetStepNum, $aSpec['editPoints'])) {
                        $editableElements[] = $aKey;
                    }
                    if (isset($relElementConfigs[$aKey])) {

                        foreach ($relElementConfigs[$aKey] as $mainRel => $relData) {
                            //                            cekUngu("relative element $mainRel ---- $aKey");
                            foreach ($relData as $relKey => $relDetails) {
                                //                                if (in_array("o_seller_spv", $mems)) {
                                if (sizeof($editElementAllowed) > 0) {
                                    if (array_key_exists($relKey, $mainElements) && in_array($targetStepNum, $relDetails['editPoints'])) {
                                        $editableElements[] = $relKey;

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

                                    }
                                }
                                //                                }
                            }
                        }
                    }
                }
            }

        }


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

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


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


        //endregion


        //region elements editor

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

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

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

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

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

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

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


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

                                    $editStr = "<a href='JavaScript:void(0)' class='btn btn-default' onclick=\"$editClick\"><span class='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) {
            $mems = isset($this->session->login['membership']) ? $this->session->login['membership'] : array();
            //            arrPrint($mems);
            foreach ($xShipmentConfig as $num => $val) {
                if ($num == $currentStepNum) {

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

                        $labelx = $val['label'];
                        $targetJenisMaster = $val['targetJenisMaster'];
                        $warningx = $val['warning'];
                        $xShipmentBtn_str = array(
                            "label" => $labelx,
                            "targetUrl" => base_url() . $this->uri->segment(1) . "/preCancelPacking/$no/$jenisTr/$targetJenisMaster/$currentStepNum",
                            "warning" => $warningx,
                        );
                        $xShipmentBtn = $xShipmentBtn_str;
                    }
                }
            }
        }

        $stepLabels = array();
        foreach ($configUiJenis['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($configUiJenis["additionalRows"]["shippingService"][$selectedService]["shipping_service"]['editPoints']) ? $configUiJenis["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='+this.value";

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

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

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

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

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

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


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

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

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

                                        }
                                    }
                                    break;
                            }


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

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

                            }

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

                                        $editStr = "<a href='JavaScript:void(0)' class='btn btn-tool' onclick=\"$editClick\"><span class='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='+this.value";
                            //                        $elStr[$eName] .="<div class='box'>";

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

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

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


        //endregion.

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

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

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

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

                                }

                            }

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

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

            }
        }
        //endregion

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

        //        arrPrint($configUiJenis["addMainSource"]);


        //endregion

        // cekOrange($approvalSpec, __LINE__);
        $detilSizeBar = array();
        $measureConf = isset($configUiJenis['shoppingCartMeasurement'][$targetStepNum]) ? $configUiJenis['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,
                );
            }
        }


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

        if (isset($configUiJenis['shoppingCartHideSubamount']) && $configUiJenis['shoppingCartHideSubamount'][$targetStepNum] == true) {
            unset($itemLabels['subtotal']);
            unset($itemLabels2['subtotal']);
            unset($itemLabels3['subtotal']);
        }

        $pairedItemTarget = isset($configUiJenis['shoppingCartPairedItem']['targetGateName']) ? $configUiJenis['shoppingCartPairedItem']['targetGateName'] : "items2_sum";
        $pairedSubItemTarget = isset($configUiJenis['shoppingCartPairedSubItem'][$targetStepNum]['targetGateName']) ? $configUiJenis['shoppingCartPairedSubItem'][$targetStepNum]['targetGateName'] : NULL;
        $pairedSelectedSubItem = isset($configUiJenis['shoppingCartSelectedSubItem']) ? $configUiJenis['shoppingCartSelectedSubItem'] : false;


        $itemsEditableConfig = isset($configUiJenis['followupItemEditable']) ? $configUiJenis['followupItemEditable'] : "_followupLiveEdit/updateItemField/";
        $itemsRemoveConfig = isset($configUiJenis['followupItemRemove']) ? $configUiJenis['followupItemRemove'] : "_followupLiveEdit/removeItem/";
        $mainEditableConfig = isset($configUiJenis['followupMainEditable']) ? $configUiJenis['followupMainEditable'] : "_followupLiveEdit/updateMainField/";
        $itemsEditableLockerDateConfig = isset($configUiJenis['followupSubItemEditable']) ? $configUiJenis['followupSubItemEditable'] : "";
        $definitionButton = definitionButton();
        // cekOrange($approvalSpec, __LINE__);
        if ($partialCanceled == false) {
            $deleteSpec = array(
                "label" => "cannot delete",
                "targetUrl" => "",
                "warning" => "",
            );
            $undoSpec = array(
                "label" => "cannot undo",
                "targetUrl" => "",
                "warning" => "",
            );
            $rejectionSpec = array(
                "label" => "cannot reject 1 step",
                "targetUrl" => "",
                "warning" => "",
            );
            $rejectionSpecAll = array(
                "label" => "cannot reject all steps",
                "targetUrl" => "",
                "warning" => "",
            );
            $editSpec = array(
                "label" => "cannot edit",
                "targetUrl" => "",
                "warning" => "",
            );

            $lastWarningLabel = isset($msgWarning2[$_SESSION[$cCode]['main']['masterID']]['label']) ? $msgWarning2[$_SESSION[$cCode]['main']['masterID']]['label'] . "<br>" : "";
            $newWarningLabel = "Transaksi ini telah diproses sebagian, UNDO/REJECT/DELETE/EDIT tidak bisa digunakan.";
            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                "label" => $lastWarningLabel . $newWarningLabel,
            );
        }
        if ($allowedAction == false) {
            $deleteSpec = array(
                "label" => "cannot delete",
                "targetUrl" => "",
                "warning" => "",
            );
            $undoSpec = array(
                "label" => "cannot undo",
                "targetUrl" => "",
                "warning" => "",
            );
            $rejectionSpec = array(
                "label" => "cannot reject 1 step",
                "targetUrl" => "",
                "warning" => "",
            );
            $rejectionSpecAll = array(
                "label" => "cannot reject all steps",
                "targetUrl" => "",
                "warning" => "",
            );
            $editSpec = array(
                "label" => "cannot edit",
                "targetUrl" => "",
                "warning" => "",
            );
            $approvalSpec = array(
                "label" => "cannot approve",
                "targetUrl" => "",
                "warning" => "",
            );
            cekOrange($approvalSpec, __LINE__);
            $xShipmentBtn = array();
            $extBtns = array();
            $extNewBtns = array();
            $payBtns = array();

            $lastWarningLabel = isset($msgWarning2[$_SESSION[$cCode]['main']['masterID']]['label']) ? $msgWarning2[$_SESSION[$cCode]['main']['masterID']]['label'] . "<br>" : "";
            $newWarningLabel = "Transaksi ini dikunci karena sedang ditindaklanjuti oleh <span class='text-uppercase text-bold'>$allowedActionByHold</span>.";
            $msgWarning2[$_SESSION[$cCode]['main']['masterID']] = array(
                "id" => "trItems_" . $_SESSION[$cCode]['main']['masterID'],
                "label" => $lastWarningLabel . $newWarningLabel,
            );
        }
        //arrPrint($pairedSubItemTarget);
        // cekOrange($approvalSpec, __LINE__);
        //matihere();
        // menonaktifkan tombol approve di followupPreview
        $pakai_ini = 0;
        if ($pakai_ini == 1) {
            if (($this->jenisTr == "967") && ($targetStepNum == 2)) {
                $approvalSpec = array(
                    "label" => "cannot approve",
                    "targetUrl" => "",
                    "warning" => "",
                );
            }
            //            if (($this->jenisTr == "582") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "582") && ($targetStepNum == 4)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "382") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "382") && ($targetStepNum == 4)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "466") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "461") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "585") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "985") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "982") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1585") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1985") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "2985") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "3585") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "967") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "961") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "587") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "587") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "687") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "687") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1587") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1587") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1687") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1687") && ($targetStepNum == 3)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "334") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1334") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
            //            elseif (($this->jenisTr == "1337") && ($targetStepNum == 2)) {
            //                $approvalSpec = array(
            //                    "label" => "cannot approve",
            //                    "targetUrl" => "",
            //                    "warning" => "",
            //                );
            //            }
        }

        if ($pairedSelectedSubItem == true) {
            $selectedSubItems = array();
            $notSelectedSubItems = array();
            if (isset($_SESSION[$cCode]['items2'])) {
                foreach ($_SESSION[$cCode]['items2'] as $pID => $iSpec) {
                    foreach ($iSpec as $iid => $iiSpec) {
                        $selectedSubItems[$pID][$iid] = isset($iiSpec['id_locker']) ? $iiSpec['id_locker'] : NULL;
                        //                        $notSelectedSubItems[$pID][] = isset($iiSpec['id_locker']) ? $iiSpec['id_locker'] : NULL;
                    }
                }
            }
        }

        //        arrPrintWebs($_SESSION[$cCode]["pair_ext"]);
        //endregion
        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'] : "";
        }
        // cekOrange($approvalSpec);
        $data = array(
            // "mode"                          => $this->uri->segment(2),
            "mode" => "followupPreview",
            "template" => $configUiJenis["template"],
            "title" => $configUiJenis["label"],
            "subTitle" => $configUiJenis["steps"][1]['label'],
            "configUi" => $this->configUi,
            "jenisTr" => $jenisTr,
            "pihakLabel" => $configUiJenis["pihakLabel"],
            "mainLabels" => $this->configLayout[$jenisTr]["receiptMainFields"],
            "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,
            "itemsChildGate" => $itemsChildGate,
            "buttonLabel" => $buttonLabel,
            "saveWarning" => $saveWarning,
            "sumRows" => isset($configUiJenis['shoppingCartSumFields'][$targetStepNum]) ? $configUiJenis['shoppingCartSumFields'][$targetStepNum] : $this->configLayout[$this->jenisTr]['receiptSumFields'][$targetStepNum],
            "sumAddRows" => $addRowLabels,
            "sumRows3" => isset($configUiJenis['shoppingCartSumFields3'][$targetStepNum]) ? $configUiJenis['shoppingCartSumFields3'][$targetStepNum] : isset($this->configLayout[$this->jenisTr]['receiptSumFields3'][$targetStepNum]) ? $this->configLayout[$this->jenisTr]['receiptSumFields3'][$targetStepNum] : array(),
            "extValueLabels" => isset($this->configCore[$this->jenisTr]['externalValues']) ? $this->configCore[$this->jenisTr]['externalValues'] : array(),
            "extEditableFields" => $editableAddVals,
            // ------
            "mainAddValues" => $mainAddValues,
            "mainAddFields" => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
            "mainElements" => $_SESSION[$cCode]['main_elements'],
            "elements" => $elements,
            "editableElements" => $editableElements,
            "elementConfig" => $elementConfigs,
            "mainInputs" => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
            "elementEditTarget" => base_url() . "_followupLiveEdit/selectElement/" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            //            "actionTarget" => base_url() . $this->uri->segment(1) . "/doFollowup/$jenisTr/$no/$targetStepNum",
            "actionTarget" => $doFollowupLink,
            "paymentMethod" => isset($tmpTr[0]->pembayaran) ? $tmpTr[0]->pembayaran : "",
            "grandTotal" => isset($_SESSION[$cCode]['main']['grand_total']) ? $_SESSION[$cCode]['main']['grand_total'] : 0,
            //-----------------------------------
            "description" => isset($_SESSION[$cCode]['main']['description']) ? $_SESSION[$cCode]['main']['description'] : "",
            "descriptionAdditional" => isset($_SESSION[$cCode]['main']['description_additional'][$targetStepNum]) ? $_SESSION[$cCode]['main']['description_additional'][$targetStepNum] : "",
            "descriptionAdditionalPreviews" => isset($_SESSION[$cCode]['main']['description_additional']) ? $_SESSION[$cCode]['main']['description_additional'] : array(),
            "descriptionAdditionalRule" => $noteAdditionalEditabled,
            "descriptionMainFollowup" => isset($_SESSION[$cCode]['main']['description_main_followup']) ? $_SESSION[$cCode]['main']['description_main_followup'] : "",
            "descriptionMainFollowupRule" => $noteFollowupEditabled,
            // --------------
            "allowEdit" => isset($configUiJenis['steps'][$targetStepNum]['allowEdit']) ? $configUiJenis['steps'][$targetStepNum]['allowEdit'] : false,
            "allowRemove" => isset($configUiJenis['steps'][$targetStepNum]['allowRemove']) ? $configUiJenis['steps'][$targetStepNum]['allowRemove'] : true,
            "allowCancel" => isset($configUiJenis['steps'][$targetStepNum]['allowCancel']) ? $configUiJenis['steps'][$targetStepNum]['allowCancel'] : false,
            "allowIncrement" => isset($configUiJenis['steps'][$targetStepNum]['allowIncrement']) ? $configUiJenis['steps'][$targetStepNum]['allowIncrement'] : false,
            "allowSubIncrement" => isset($configUiJenis['steps'][$targetStepNum]['allowSubIncrement']) ? $configUiJenis['steps'][$targetStepNum]['allowSubIncrement'] : false,
            "editableFields" => isset($configUiJenis['shoppingCartEditableFields'][$targetStepNum]) ? $configUiJenis['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" => base_url() . "$itemsRemoveConfig" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "updateItemFieldTarget" => base_url() . "$itemsEditableConfig" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "updateItemChildTarget" => base_url() . "_followupLiveEdit/updateChildField/" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "updateMainFieldTarget" => base_url() . "$mainEditableConfig" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "updateMainSourceTarget" => base_url() . "_followupLiveEdit/updateSourceField/" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "clearContentTarget" => base_url() . get_class($this) . "/clearContent/" . $this->jenisTr . "/" . $this->uri->segment(3),
            "followupPreviewTarget" => base_url() . "Transaksi/followupPreview/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5),
            "msgWarning" => isset($msgWarning) ? $msgWarning : array(),
            "msgWarning2" => isset($msgWarning2) ? $msgWarning2 : array(),
            // ----
            "addRows" => $addRows,
            "addRowLabels" => $addRowLabels,
            "deleteSpec" => $deleteSpec,
            "undoSpec" => $undoSpec,
            "rejectionSpec" => $rejectionSpec,
            "rejectionSpecAll" => $rejectionSpecAll,
            "approvalSpec" => $approvalSpec,
            "editSpec" => $editSpec,
            "detailSizeKey" => $detailSizeKey,
            "detilSizeBar" => $detilSizeBar,
            "addMainSourceField" => $addMainSourceField,
            "addMainSourceEdit" => $addMainSourceEdit,
            "definitionButton" => $definitionButton,
            "dpData" => $dpData,
            "pair_ext" => isset($_SESSION[$cCode]['pair_ext']) ? $_SESSION[$cCode]['pair_ext'] : array(),
            //==========
            "shoppingCartInputType" => $shoppingCartInputType,
            "editableSubFields" => isset($configUiJenis['shoppingCartEditableSubFields'][$targetStepNum]) ? $configUiJenis['shoppingCartEditableSubFields'][$targetStepNum] : array(),
            "itemsEditableLockerDateConfig" => base_url() . $itemsEditableLockerDateConfig . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "pairedSubItemTarget" => $pairedSubItemTarget,
            "items2_detail" => isset($_SESSION[$cCode][$pairedSubItemTarget]) ? $_SESSION[$cCode][$pairedSubItemTarget] : array(),
            "itemsSubLabels" => $itemSubLabels,
            "allowSubTambah" => isset($configUiJenis['steps'][$targetStepNum]['allowSubTambah']) ? $configUiJenis['steps'][$targetStepNum]['allowSubTambah'] : true,
            "allowSubRemove" => isset($configUiJenis['steps'][$targetStepNum]['allowSubRemove']) ? $configUiJenis['steps'][$targetStepNum]['allowSubRemove'] : true,
            "removeSubItemTarget" => base_url() . "_followupLiveEdit/removeSubItem/" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "tambahSubItemTarget" => base_url() . "_followupLiveEdit/tambahSubItem/" . $this->jenisTr . "/" . $this->uri->segment(3) . "/" . $this->uri->segment(4) . "/" . $this->uri->segment(5) . "/",
            "selectedSubItems" => isset($selectedSubItems) ? $selectedSubItems : array(),
        );

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

    }

    // -------------------------------SAN
    /*followUp I vlidasi*/
    public function followupPrePreview_old()
    {
        $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;
            $tokoID = $tmpTr[0]->toko_id;
            $cCode = $this->cCode;

            $configUi = $this->configUi;
            $configCore = $this->configCore;
            $configLayout = $this->configLayout;

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

            //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
            $priceInjectorItems = isset($this->configUi[$this->jenisTr]["priceInjectorItems"][$stepNumber]) ? $this->configUi[$this->jenisTr]["priceInjectorItems"][$stepNumber] : array();
            $masterID = $tmpTr[0]->id_master;
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $currentStepNum = $tmpTr[0]->step_number;
            $afterTargetStepNum = ($currentStepNum + 1);


            //region periksa locker value;
            $tempLocker = array();
            $tempBtnUndo = array();
            if (sizeof($validatePaymentLocker) > 0) {
                $mdlName = "Mdls/" . $validatePaymentLocker;
                $this->load->model($mdlName);
                $l = new $validatePaymentLocker();
                $l->addFilter("transaksi_id='$no'");
                $l->addFilter("state='active'");
                $l->addFilter("nilai > 0");
                $tempLocker = $l->lookupAll()->result();
                //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();
            $mainElements = array();
            $mainInputs = array();
            $diskon_event = array();
            $cashback_event = 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_elements"://
                            $mainElements = unserialize(base64_decode($row));
                            break;
                        case "main_inputs"://
                            $mainInputs = unserialize(base64_decode($row));
                            break;
                        case "diskon_event"://
                            $diskon_event = unserialize(base64_decode($row));
                            break;
                        case "cashback_event"://
                            $cashback_event = 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();


            $itemChildData = array();
            $arrHpp = array();
            if (sizeof($items) > 0) {

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


                        }

                        //-----------------
                        if (sizeof($finalItemPrice) > 0) {

                            $nom = 0;
                            foreach ($finalItemPrice as $cID => $cSpec) {
                                foreach ($cSpec as $pID => $pSpec) {

                                    $items[$pID]['price_setting'][$cID] = $pSpec;


                                    $nom++;
                                    foreach ($pSpec as $key => $val) {
                                        $finalItemPriceSum[$nom][$key] = $val;
                                        $finalItemPriceSum[$nom]['id'] = $pID;
                                    }
                                }
                            }
                        }
                        //-----------------

                    }
                    $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,
                "main_add_fields" => $masterAddFields,
                "main_elements" => $mainElements,
                "main_inputs" => $mainInputs,
                "extSteps" => $extSteps,
                "paySrcs" => $paySrcs,
                "lockerPayment" => $tempBtnUndo,
                "itemPrice" => $finalItemPrice,
                "itemPrice_sum" => $finalItemPriceSum,
                "itemHargaJual" => $finalHargaJual,
                "diskon_event" => $diskon_event,
                "cashback_event" => $cashback_event,
            );
            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_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;


            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_id in (" . implode(",", explode("-", $no)) . ")");
        $tr->addFilter("sub_step_number='" . $currentStepNum . "'");
        $tmpTr = $tr->lookupJoined()->result();
        //endregion

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

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

        $rejectAllAllowed = true;
        $partialCanceled = false;
        $rawItems = array();

        //region detail elements of preview
        if (sizeof($tmpTr) > 0) {
            $jenisTr = $this->jenisTr = $tmpTr[0]->jenis_master;
            $pelaku = $tmpTr[0]->oleh_id;
//cekHitam($this->jenisTr);
//            $cCode = "_TR_" . $this->jenisTr;
            $cCode = $this->cCode;
            $configUi = $this->configUi;
            $configCore = $this->configCore;
            $configLayout = $this->configLayout;

            //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();
            //------
            $qtyItemValidate = isset($this->configUi[$this->jenisTr]['qtyItemValidate'][$targetStepNum]['enabled']) ? $this->configUi[$this->jenisTr]['qtyItemValidate'][$targetStepNum]['enabled'] : 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

            //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 {
                $errMsg = "Cannot read the registry entries from $masterID!";
                $alerts = array(
                    "type"  => "warning",
                    "title" => strtoupper("PERHATIAN"),
                    "html"  => $errMsg,
                );
                echo swalAlert($alerts);
                die();
                // die("Cannot read the registry entries from $masterID!");
            }
            //endregion
            // matiHEre();

            $arrTest = array();
            $totalValidQty = 0;
            $totalOrdJml = 0;
            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;

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

            }
//
//
//            cekHere("$totalOrdJmlMaster != $totalOrdJml");
//            cekHere("$totalValidQty == $totalOrdJml");
//
            if ($totalValidQty == $totalOrdJml) {
                $partialCanceled = true;
            }
//            if ($totalOrdJmlMaster != $totalOrdJml) {
//                $rejectAllAllowed = false;
//            }
//

            if ($qtyItemValidate == true) {
                $arrItemKekurangan = array();
                foreach ($_SESSION[$cCode]['items'] as $pid => $spec) {
                    $stok = $spec['stok'];
                    $qty = $spec['qty'];
                    if ($qty > $stok) {
                        $arrItemKekurangan[$pid] = $pid;
                    }
                }
            }
        }
        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();
        $userGroup_editElementAllowed = $this->config->item("userGroup_editElementAllowed") != NULL ? $this->config->item("userGroup_editElementAllowed") : array();
        $thisStepGID = isset($this->configUi[$this->jenisTr]['steps'][$currentStepNum]['userGroup']) ? $this->configUi[$this->jenisTr]['steps'][$currentStepNum]['userGroup'] : "";
        $nextStepGID = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['userGroup']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['userGroup'] : "";
        $hideFollowUp = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['hideFollowUp']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['hideFollowUp'] : false;

        $editElementAllowed = array_intersect($userGroup_editElementAllowed, $mems);

        $allowFollowup = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowFollowup']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['allowFollowup'] : true;

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

        $deleteSpec = array(
            "label" => "cannot delete",
            "targetUrl" => "",
            "warning" => "",
        );

        $undoSpec = array(
            "label" => "cannot undo",
            "targetUrl" => "",
            "warning" => "",
        );

        $rejectionSpec = array(
            "label" => "cannot reject",
            "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/$jenisTr/$no/$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/$jenisTr/$no/$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/$jenisTr/$no/$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/$jenisTr/$no/$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/$jenisTr/$no/$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/$jenisTr/$no/$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/$jenisTr/$no/$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/$jenisTr/$no/$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) {
                    // cekhijau("allowed to REJECT || LINE: " . __LINE__);
                    $masterRevertStep = ($currentStepNum - 1);
                    $childRevertStep = -($currentStepNum);
                    $rejectionSpec = array(
                        "label" => "reject",
                        "targetUrl" => MODUL_PATH . get_class($this) . "/doRevert/$jenisTr/$no/$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/$jenisTr/$no/$currentStepNum",
                    "warning" => "pressing EDIT will modify entire transaction data. continue?",
                );
            }
            else {
                //                cekmerah("NOT allowed to EDIT");
            }
        }
        else {
            if ($pelaku == $this->session->login['id']) {
                $evPre = evaluatePreProcessors_he_menu($this->jenisTr, $currentStepNum, $this->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]);
//                cekHitam($evMaster);
                if ($evPre == null && $evPost == null && $evCom == null && $evMaster == null) {
//                    cekhijau("allowed to EDIT");
                    $editSpec = array(
                        "label" => "edit",
                        "targetUrl" => MODUL_PATH . get_class($this) . "/doPreEdit/$jenisTr/$no/$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]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                            "targetUrl" => MODUL_PATH . get_class($this) . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . get_class($this) . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                                $approvalSpec = array(
                                    //                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                    "targetUrl" => MODUL_PATH . get_class($this) . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                    "warning" => "pressing green button will set this entry one step ahead. continue?",
                                );
                                if ($hideFollowUp) {
                                    $approvalSpec = array();
                                }
                            }
                        }
                    }
                    else {
                        if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->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/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                                        );
                                        if ($hideFollowUp) {
                                            $approvalSpec = array();
                                        }
                                    }
                                }
                                else {
                                    $approvalSpec = array(
                                        //                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                        "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                        "targetUrl" => MODUL_PATH . get_class($this) . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                                $approvalSpec = array(
                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                    "targetUrl" => MODUL_PATH . get_class($this) . "/doFollowup/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                    "warning" => "pressing green button will set this entry one step ahead. continue?",
                                );
                                if ($hideFollowUp) {
                                    $approvalSpec = array();
                                }
                            }
                        }
                        else {
                        }
                    }
                }
                else {
                    if (placeCanFollowupTrans_he_menu($this->session->login['membership'], $this->session->login['cabang_id'], $this->session->login['gudang_id'], $this->jenisTr, $targetStepNum, "", $this->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/$jenisTr/$no/$targetStepNum/$currentStepNum",
                            "warning" => "pressing green button will set this entry one step ahead. continue?",
                        );
                    }
                    else {
                        cekUngu("tidak ada approve");
                    }
                }

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

                            $approvalSpec = array(
                                //                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                "targetUrl" => $doFollowupLink,
                                "warning" => "pressing green button will set this entry one step ahead. continue?",
                            );

                            if ($hideFollowUp) {
                                $approvalSpec = array();
                            }
                        }
                    }
                }
                else {
                    // matiHEre(__LINE__);
                    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/$jenisTr/$no/$targetStepNum/$currentStepNum",
                                        "warning" => "pressing green button will set this entry one step ahead. continue?",
                                    );
                                    if ($hideFollowUp) {
                                        $approvalSpec = array();
                                    }
                                }
                            }
                            else {
                                $approvalSpec = array(
                                    //                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'] : "continue to next step",
                                    "label" => isset($this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel']) ? $this->configUi[$jenisTr]['steps'][$targetStepNum]['buttonLabel'] : $this->configUi[$jenisTr]['steps'][$targetStepNum]['actionLabel'],
                                    "targetUrl" => $doFollowupLink,
                                    "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(in_array($this->configUi[$jenisTr]['steps'][$targetStepNum]['userGroup'], $this->session->login['membership'])){
                            $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{
//                            cekHitam($this->configUi[$jenisTr]['steps'][$targetStepNum]['userGroup']);

                        }
//                        arrPrint($this->session->login['membership']);
//                        cekHitam($this->jenisTr);
//                        cekHitam("gak punya akses");
                    }
                }
            }
        }
        else {
            // cekmerah("NOT possible to approve");
        }
        //endregion

        // arrPrint($approvalSpec);
        // matiHEre(__LINE__);

        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();
        $accountAlias = fetchAccountStructureAlias();
        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] = isset($accountAlias[$rek]) ? $accountAlias[$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();

        //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();
        $extRowsPpnConfigs = isset($this->configUi[$this->jenisTr]['additionalShopingcartHeaderElement'][$targetStepNum]) ? $this->configUi[$this->jenisTr]['additionalShopingcartHeaderElement'][$targetStepNum] : array();
        if (sizeof($_SESSION[$cCode]['main_elements']) > 0) {

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

        }

        //region elements editor

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

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

                        $elStr[$eName] = "";
                        $this->load->model("Mdls/" . $amdlName);
                        $labelSrc = $eSpec['labelSrc'];
                        $keySrc = $eSpec['key'];
                        $oo = new $amdlName();
                        $addLink = base_url() . "Data/add/" . str_replace("Mdl", "", $amdlName);
                        if (sizeof($aFilter) > 0) {
                            foreach ($aFilter as $filter) {
                                $exFilter = explode("=", $filter);
                                if (sizeof($exFilter) > 1) {
                                    if (isset($_SESSION[$cCode]['main'][$exFilter[1]])) {
                                        $oo->addFilter($exFilter[0] . "='" . $_SESSION[$cCode]['main'][$exFilter[1]] . "'");
                                        $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>";
                            }
                        }

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

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

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

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


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

                                    $editStr = "<a href='JavaScript:void(0)' class='btn btn-default' onclick=\"$editClick\"><span class='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() . $this->modul . "/" . "FollowUp/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() . $this->modul . "/" . "FollowUp/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'] = $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() . $this->modul . "/" . "FollowUp/selectPaymentSrc/" . $xSpec['targetJenis'] . "/" . $xSpec['extID'] . "/$masterID?rawPrev=$rawPrevURL'),
                                        size:top.BootstrapDialog.SIZE_WIDE,
                                        draggable:false,
                                        closable:true,
                                        }
                                        );";
                        //                        $payBtns[$xSpec['targetJenis']] = "<a class='btn btn-warning' href='JavaScript:void(0)' onclick=\"$actionTarget\"><span class='glyphicon glyphicon-triangle-right'></span> do " . $xSpec['label'] . "</a>";
                    }
                    else {
                        //                        $payBtns[$xSpec['targetJenis']] = "<a class='btn btn-default text-muted'><i>" . $xSpec['label'] . "</i></a>";
                    }
                }
            }
        }
        //endregion

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

        //        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() . $this->modul . "/" . "_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() . $this->modul . "/" . 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() . $this->modul . "/" . 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($configUi[$this->jenisTr]["addMainSource"][$targetStepNum]) ? $configUi[$this->jenisTr]["addMainSource"][$targetStepNum] : array();

        //region detector non pkp gak perlu tampil diUI
        $validateJenisUsaha = isset($_SESSION[$cCode]['main']['jenis_usaha']) ? $_SESSION[$cCode]['main']['jenis_usaha'] : $this->session->login['jenis_usaha'];

        if (sizeof($addMainSource) > 0) {
            if ($validateJenisUsaha == "pkp") {
                $addMainSourceValidateGate = isset($configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["validateFields"]) ? $configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["validateFields"] : "ppn";
                if (isset($_SESSION[$cCode]['main'][$addMainSourceValidateGate]) && $_SESSION[$cCode]['main'][$addMainSourceValidateGate] > 0) {
                    $addMainSourceField = isset($configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["fields"]) ? $configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["fields"] : array();
                    $addMainSourceEdit = isset($configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["editableFields"]) ? $configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["editableFields"] : array();
                    $addMainSourceLabel = isset($configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["label"]) ? $configUi[$this->jenisTr]["addMainSource"][$targetStepNum]["label"] : "";
                }
                else {
                    $addMainSourceField = array();
                    $addMainSourceEdit = array();
                    $srcMainAdd = array();
                    $addMainSourceLabel = "";

                }
            }
            else {
                $addMainSourceField = array();
                $addMainSourceEdit = array();
                $srcMainAdd = array();
                $addMainSourceLabel = "";
            }
        }
        else {
            $addMainSourceField = array();
            $addMainSourceEdit = array();
            $addMainSourceLabel = "";
        }
        //endregion

        $updatePriceLabel = isset($configUi[$this->jenisTr]["itemPrice"][$targetStepNum]["fieldsLabel"]) ? $configUi[$this->jenisTr]["itemPrice"][$targetStepNum]["fieldsLabel"] : array();
        $updatePriceEditable = isset($configUi[$this->jenisTr]["itemPrice"][$targetStepNum]["editableFields"]) ? $configUi[$this->jenisTr]["itemPrice"][$targetStepNum]["editableFields"] : array();

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

        }
        //        arrPrint($configUi[$this->jenisTr]["addMainSource"]);
// arrPrint($branchData);
// matiHEre();
        //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

        $status_pengiriman = isset($this->configUi[$this->jenisTr]['steps'][$targetStepNum]['status_pengiriman']) ? $this->configUi[$this->jenisTr]['steps'][$targetStepNum]['status_pengiriman'] : array();
        $arrStatusPengiriman=array();

        if(!empty($status_pengiriman)){
//            $this->load->library("Curl");
//            $curl = New Curl();
            $response = array(
                "nomor_referensi" => $_SESSION[$cCode]['tableIn_master']['inv'],
            );
//            $callBackFromApk = $curl->_simple_call("post", ADM_DOMAIN . "run_sakura_apk/eusvc/Entries/getStatusLogistik", $response);
//            $arrStatusPengiriman = json_decode($callBackFromApk, true);
            $arrStatusPengiriman = $response;
        }

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

        $data = array(
            "mode" => "followupPreview",
            "arrStatusPengiriman" => $arrStatusPengiriman,
            "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,
            "addMainSourceLabel" => $addMainSourceLabel,
            "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(),

            "addRowsPpnConfigs" => isset($addRowsPpnConfigs) ? $addRowsPpnConfigs : array(),
            "extFollowupPPn" => isset($extRowsPpnConfigs) ? $extRowsPpnConfigs : array(),
            "jenis_usaha" => $this->session->login['jenis_usaha'],
            "itemKekurangan" => isset($arrItemKekurangan) ? $arrItemKekurangan : array(),
        );
        if (isset($_SESSION[$cCode]['main'])) {
            $data['pihakID'] = isset($_SESSION[$cCode]['main']['pihakID']) ? $_SESSION[$cCode]['main']['pihakID'] : 0;
            $data['pihakName'] = isset($_SESSION[$cCode]['main']['pihakName']) ? $_SESSION[$cCode]['main']['pihakName'] : "";
        }
        //endregion

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

    }

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


        $no = $this->uri->segment(3);
        $jenisTr = $this->uri->segment(4);
        $masterTargetStepNum = $this->uri->segment(5);
        $childTargetStepNum = $this->uri->segment(6);
        $stepNumCurrent = $this->uri->segment(7);
        $cCode = "_TR_" . $this->jenisTr;

        echo "no: $no<br>";
        echo "masterTargetStepNum: $masterTargetStepNum<br>";
        echo "childTargetStepNum: $childTargetStepNum<br>";
        echo "stepNumCurrent: $stepNumCurrent<br>";


        $this->db->trans_start();

        cekMerah(url_segment());
        matiHere(__METHOD__ . __LINE__);
        //
        //region update step2an di masternya

        $nextMasterStep = $stepNumCurrent;
        echo "nextMasterStep: $nextMasterStep<br>";
        $nextProp = array(
            "num" => $nextMasterStep,
            "code" => $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'],
            "label" => $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'],
            "groupID" => $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'],
        );
        $tr = new MdlTransaksi();
        $dupState = $tr->updateData(array("id" => $no), array(
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            "next_step_num" => $nextProp['num'],
            "step_current" => $masterTargetStepNum,

        )) or die("Failed to update tr next-state!");
        cekHijau($this->db->last_query());
        //endregion


        //region update step2an di childnya
        $tru = new MdlTransaksi();
        $tru->setFilters(array());
        $tru->setTableName($tru->getTableNames()['detail']);


        $dupState = $tru->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" => $masterTargetStepNum,
        )) or die("Failed to update previous detail entries!");
        cekHijau($this->db->last_query());
        unset($tru);
        //endregion


        //region update step yang sebelumnya aktif
        $tr = new MdlTransaksi();
        $dupState = $tr->updateData(array("id_master" => $no,
            "step_number" => $stepNumCurrent
        ), array(
            "step_number" => $childTargetStepNum,

        )) or die("Failed to update tr next-state!");
        cekHijau($this->db->last_query());
        //endregion

        //
        //region update nomor step di cloningan jadi minus current
        //endregion
        //
        //region sesuaikan signature untuk cloningan, ikut minus
        $dwsign = $tr->writeSignature($no, array(
            "nomer" => "rejection",
            "step_number" => $childTargetStepNum,
            "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" => $masterID,
        )) or die("Failed to write signature");
        cekKuning($this->db->last_query());
        //endregion

        //==tampilkan receipt
        cekOrange("-- DONE --");
        //        die();
        // matiHere(__LINE__." COMPLITTT");
        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");
        $_SESSION[$cCode] = null;
        unset($_SESSION[$cCode]);
        if (isset($oldCode)) {
            $_SESSION[$oldCode] = null;
            unset($_SESSION[$oldCode]);
        }
        //region feedback msg
        $this->session->errMsg = "transaction entry has been rejected<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 followed-up 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 .= "cannot detect transaction state<br>";
            $trBackLink = base_url() . get_class($this) . "/viewHistory/" . $this->jenisTr;

        }
        $trBackClick = "location.href='$trBackLink'";
        $this->session->errMsg .= "<a href='JavaScript:void(0)' onclick=\"$trBackClick\">view entry</a><br>";
        //endregion
        echo "<script>";
        //        echo "top.window.open('" . base_url() . "Transaksi/viewReceipt/$tmpNomorNota');";
        echo "top.location.reload();";
        echo "</script>";

    }
    public function doFollowup_OLD_unused()
    {
        // $debug_cek = true;

        echo "<script>top.writeProgress('MEMULAI PROSES FOLLOWUP....');</script>";

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

        //        $no = $this->uri->segment(3);
        $transaksiID_reference = $no = rtrim($this->uri->segment(5), "-");
        $stepNum = $this->uri->segment(6);
        $stepNumCurrent = $this->uri->segment(7);
        //         cekOrange(url_segment());
        // matiHere(__METHOD__);
        echo "<script>top.writeProgress('MEMUAT CONFIG', 'HEAD');</script>";

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

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

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

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

        //==ambil datanya
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("transaksi_id in (" . implode(",", explode("-", $no)) . ")");
        $tr->addFilter("step_number='" . $stepNumCurrent . "'");
        $tr->addFilter("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

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

            $masterID = isset($_SESSION[$cCode]['main']['masterID']) ? $_SESSION[$cCode]['main']['masterID'] : cekKuning("masterID tidak ada dalam session @" . __LINE__ . " " . __METHOD__);
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;

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


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


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


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

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

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

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


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

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


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


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

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

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


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

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

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

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

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

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

                        }
                    }


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


        $this->db->trans_start();

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

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

            echo "ITEM NUM LABELS @" . __LINE__;
            arrPrint($iterator);
            if (sizeof($iterator) > 0) {
                echo "<script>top.writeProgress('PERSIAPAN PRE-PROCESSOR...', 'HEAD');</script>";
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                    echo "master-preproc: $comName, initializing values <br>";
                    $tmpOutParams[$cCtr] = array();


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

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

                        }

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

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


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


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

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

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

                        if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                            cekhijau("ada gotparam, sekarang mau replace");
                            foreach ($gotParams as $gateName => $gSpec) {
                                if (isset($_SESSION[$cCode]['main'])) {
                                    if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                        foreach ($gSpec as $key => $val) {
                                            cekbiru("injecting param $key with $val");
                                            $_SESSION[$cCode]['main'][$key] = $val;
                                        }
                                    }
                                }
                                //==inject gotParams to child gate
                                if (isset($_SESSION[$cCode]['main'])) {
                                    if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                        foreach ($gSpec as $key => $val) {
                                            $_SESSION[$cCode]['main'][$key] = $val;
                                        }
                                    }
                                }

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

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

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


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

        //endregion


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

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

            if (sizeof($iterator) > 0) {
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo __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 " . __LINE__ . ": $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");
                        }
                    }
                }
            }
            else {
                //cekKuning("sub-preproc is not set");
            }

            //cekHere("cetak rsltItems");
            //arrPrintWebs($_SESSION[$cCode]['rsltItems']);
            //mati_disini();

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


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

        //endregion
        //        matihere("consolisadi fifo non aktif dulu broo ".__LINE__);

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


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

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

                        }

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

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


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


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

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

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

                                }

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

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

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

            $this->load->helper("he_value_builder");
            fillValues($this->jenisTr, $stepNumCurrent, $stepNum);

        }
        //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
        cekBiru("validator done @:" . __LINE__);

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

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


        echo "checking components..<br>";
        echo "<script>top.writeProgress('CHECKING KOMPONEN');</script>";
        //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,

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


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


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

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

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


        $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->configCore[$origJenis]['formatNota']);
        if (!in_array($counterForNumber[0], $this->configCore[$origJenis]['counters'])) {
            die(__LINE__ . " Used number should be registered in 'counters' config as well");
        }

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

        //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->configCore[$origJenis]['counters'];
        $configCustomParams[] = "stepCode";
        if (sizeof($configCustomParams) > 0) {
            $cContent = array();
            foreach ($configCustomParams as $i => $cRawParams) {
                $cParams = explode("|", $cRawParams);
                $cValues = array();
                foreach ($cParams as $param) {
                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                }
                $cRawValues = implode("|", $cValues[$i]);
                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

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


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

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

        // </editor-fold>
        //endregion


        //==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,
                );
                $idHis_blob = blobEncode($idHis_decode);
                $idHis_intext = print_r($idHis_decode, true);

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


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

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


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


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

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

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

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


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


                }
            }


            //region update validQty pada step sebelumnya yang di-refer
            echo "<script>top.writeProgress('EXTRACT ITEMS...','head');</script>";
            $seluruhnya = true;
            $prevTrID = 0;
            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                $insertIDs = array();
                $insertDeIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail'] as $iID => $dSpec) {
                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                    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']);
                                }
                                $itemFulfilledJml += $newValidQty;
                                //                                $newValidQty = ($triSpec['valid_qty'] - $dSpec['produk_ord_jml']);
                                $updateContents = array(
                                    "valid_qty" => $newValidQty,
                                );
                                if ($newValidQty < 1) {
                                    $childPrevRepaclers = array(
                                        "next_substep_code" => "",
                                        "next_substep_label" => "",
                                        "next_subgroup_code" => "",
                                        "sub_tail_number" => $stepNum,
                                        "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                    );
                                    foreach ($childPrevRepaclers as $key => $val) {
                                        $updateContents[$key] = $val;
                                    }
                                }
                                else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                    $seluruhnya = false;
                                }
                                $dupState = $tru->updateData(array(
                                    "produk_id" => $iID,
                                    "id" => $triID,
                                    //                            "transaksi_id" => $trID,
                                    "transaksi_id" => $triSpec['transaksi_id'],
                                ), $updateContents) or die("Failed to update previous detail entries!");
                                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);
                            }
                        }
                    }

                }
                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());
                    }
                }
            }
            else {
                die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
            }

            if ($seluruhnya) {
                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array("id" => $prevTrID), array(
                    "tail_number" => $stepNum,
                    "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                    "status_4" => $_SESSION[$cCode]['main']['status_4'],
                    "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                )) or die("Failed to update tr next-state!");
                cekHijau(":: UOPDATE transaksi dengan trID -> $prevTrID");
                $mongUpdateList['update']['main'][] = array(
                    "where" => array(
                        "id" => $prevTrID,
                    ),
                    "value" => array(
                        "tail_number" => $stepNum,
                        "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                        "status_4" => $_SESSION[$cCode]['main']['status_4'],
                        "trash_4" => $_SESSION[$cCode]['main']['trash_4'],
                    ),
                );
                cekHijau($this->db->last_query());
            }
            //endregion
            //region cloner items to item_child
            if (sizeof($additionalData) > 0) {
                echo "<script>top.writeProgress('CLONING ITEMS TO ITEM CHILD...','head');</script>";
                cekHitam("ini data");
                $dataMdl = $additionalData["mdlName"];
                $this->load->model("Mdls/" . $dataMdl);
                $da = new $dataMdl();
                $arrColl = $da->getFields();
                $selectedCol = array();
                foreach ($arrColl as $colSpec) {
                    $selectedCol[] = $colSpec['kolom'];
                }

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

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

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

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

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

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

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

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

                            }
                        }


                        //                        arrPrint($arrNew);
                        //


                        //                  arrPrint($itemsMain);
                    }

                }
            }

            //endregion


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


            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(),
                'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),

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

                '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(),
                "jurnal_index" => isset($this->configCore[$this->jenisTr]['components'][$stepNum]) ? $this->configCore[$this->jenisTr]['components'][$stepNum] : array(),
                "postProcessor" => isset($this->configCore[$this->jenisTr]['postProcessor'][$stepNum]) ? $this->configCore[$this->jenisTr]['postProcessor'][$stepNum] : array(),
                "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
            );
            $doWriteReg = $tr->writeRegistries($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


        //        validateAllBalances();

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

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$stepNum]['detail']) ? $this->configCore[$this->jenisTr]['postProcessor'][$stepNum]['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 @" . __LINE__ . " <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(":: $key diisikan dengan " . $subParams['static'][$k]);
                            }
                        }

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

                    if (sizeof($subParams) > 0) {
                        $tmpOutParams[$cCtr][] = $subParams;
                    }
                    echo "<script>top.writeProgress('" . (isset($subParams['static']['name']) ? $subParams['static']['name'] : 'noname') . " " . (isset($subParams['static']['extern_nama']) ? $subParams['static']['extern_nama'] : 'noexternnama') . " " . (isset($subParams['static']['nama']) ? $subParams['static']['nama'] : 'noname') . "');</script>";
                }
            }

            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, sending values @" . __LINE__ . " " . __METHOD__ . " <br>";
                echo "<script>top.writeProgress('SENDING SUB-PROCESSORS ($comName)...', 'head');</script>";
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();
                // cekMerah($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());
            }
        }


        //</editor-fold>
        //endregion

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

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

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

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

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

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

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


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

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

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


                }

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

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


            }
        }


        //</editor-fold>
        //endregion

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

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

        //endregion


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

        $componentGate['master'] = array();
        $componentConfig['master'] = array();
        $iterator = isset($this->configCore[$this->jenisTr]['components'][$stepNum]['master']) ? $this->configCore[$this->jenisTr]['components'][$stepNum]['master'] : array();
        if (sizeof($iterator) > 0) {
            echo "<script>top.writeProgress('KOMPONEN...', 'head');</script>";
            $componentConfig['master'] = $iterator;

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

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

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

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

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


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

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

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


                }

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

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

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

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

                }


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

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

        //        mati_disini(__FUNCTION__ . " *** under maintenance *** <br> TUNGGU SEBENTAR YA... ");
        //</editor-fold>
        //endregion

        //
        //region nulis paymentSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_source");
        if (array_key_exists($stepCode, $paymentSources)) {
            $payConfigs = isset($paymentSources[$stepCode][$stepNum]) ? $paymentSources[$stepCode][$stepNum] : array();
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    $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__);//
                        }
                        $tr->writePaymentSrc($insertID, array(
                            "jenis" => $stepCode,
                            "target_jenis" => $paymentSrcConfig['jenisTarget'],
                            "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                            "extern_id" => isset($_SESSION[$cCode]['main'][$externSrc['id']]) ? $_SESSION[$cCode]['main'][$externSrc['id']] : "",
                            "extern_nama" => isset($_SESSION[$cCode]['main'][$externSrc['nama']]) ? $_SESSION[$cCode]['main'][$externSrc['nama']] : "",
                            "nomer" => $tmpNomorNota2,
                            "label" => $paymentSrcConfig['label'],
                            "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                            "terbayar" => 0,
                            "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                            "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                            "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "fulldate" => date("Y-m-d"),
                            "valas_id" => isset($externSrc['valasId']) && isset($_SESSION[$cCode]['main'][$externSrc['valasId']]) ? $_SESSION[$cCode]['main'][$externSrc['valasId']] : '',
                            "valas_nama" => isset($externSrc['valasLabel']) && isset($_SESSION[$cCode]['main'][$externSrc['valasLabel']]) ? $_SESSION[$cCode]['main'][$externSrc['valasLabel']] : '',
                            "valas_nilai" => isset($externSrc['valasValue']) && isset($_SESSION[$cCode]['main'][$externSrc['valasValue']]) ? $_SESSION[$cCode]['main'][$externSrc['valasValue']] : '',
                            "tagihan_valas" => isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : '',
                            "terbayar_valas" => 0,
                            "sisa_valas" => isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',
                            //                            "extern_label2" => isset($_SESSION[$cCode]['main']['pihakMainName']) ? $_SESSION[$cCode]['main']['pihakMainName'] : "",
                            "extern_label2" => (isset($externSrc['extern_label2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_label2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_label2']] : "",

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

                            "npwp" => (isset($externSrc['npwp']) && ($_SESSION[$cCode]['main'][$externSrc['npwp']])) ? $_SESSION[$cCode]['main'][$externSrc['npwp']] : "",
                            "extern2_id" => (isset($externSrc['extern2_id']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_id']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_id']] : "",
                            "extern2_nama" => (isset($externSrc['extern2_nama']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_nama']] : "",
                            "ppn_pph_faktor" => (isset($externSrc['ppn_pph_faktor']) && ($_SESSION[$cCode]['main'][$externSrc['ppn_pph_faktor']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn_pph_faktor']] : "",
                            "extern_jenis" => (isset($externSrc['extern_jenis']) && ($_SESSION[$cCode]['main'][$externSrc['extern_jenis']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_jenis']] : "",
                            "extern_nilai3" => (isset($externSrc['extern_nilai3']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai3']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai3']] : "",
                            "extern_nilai4" => (isset($externSrc['extern_nilai4']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai4']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai4']] : "",
                            "npwp" => (isset($externSrc['npwp']) && ($_SESSION[$cCode]['main'][$externSrc['npwp']])) ? $_SESSION[$cCode]['main'][$externSrc['npwp']] : "",
                            //                            "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : "",
                        ));

                        //                        cekLime($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']]);
                        //                        matiHEre($_SESSION[$cCode]['main'][$externSrc['pph_23']]);
                    }

                    //cekHitam($valueSrc);
                    //                    cekHitam($_SESSION[$cCode]['main'][$valueSrc]);

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

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

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

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

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

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

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

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

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

        cekKuning(":: mulai cek rek besar dan rek pembantu @" . __LINE__);
        $cabangID_validate = $this->session->login['cabang_id'];
        validateBalancesComparison($cabangID_validate, $componentGate, $componentConfig, "master", $insertID, $tmpNomorNota2);

        validateAllBalances();


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

        //        mati_disini("STOPP... sebelum CONNECTING");

        //
        //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();
        $mongoListConnect = array();
        $mongRegIDConnect = 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");

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


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

                $_SESSION[$cCode] = array();

                $_SESSION[$cCode] = array(
                    "main" => $_SESSION[$oldCode]['main'],
                    "items" => $_SESSION[$oldCode]['items'],
                    "items2" => $_SESSION[$oldCode]['items2'],
                    "items2_sum" => $_SESSION[$oldCode]['items2_sum'],

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

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

                //==replace pertama
                $masterReplacersO = array(
                    "jenisTr" => $connector,
                    "jenisTrMaster" => $connector,
                    "jenisTrTop" => $this->configUi[$connector]['steps'][1]['target'],
                    "jenis" => $this->configUi[$connector]['steps'][1]['target'],
                    "jenis_label" => $this->configUi[$connector]['steps'][1]['label'],
                    "transaksi_jenis" => $this->configUi[$connector]['steps'][1]['target'],
                    "stepCode" => $this->configUi[$connector]['steps'][1]['target'],
                    "placeID" => 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" => $this->configUi[$connector]['steps'][1]['target'],
                    "jenis" => $this->configUi[$connector]['steps'][1]['target'],
                    "jenis_label" => $this->configUi[$connector]['steps'][1]['label'],
                    "transaksi_jenis" => $this->configUi[$connector]['steps'][1]['target'],
                    "cabang_id" => 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($this->configUi[$connector]['steps']),
                    "step_current" => 1,
                    "step_number" => 1,
                    "next_step_code" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['target'] : "",
                    "next_step_label" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['label'] : "",
                    "next_group_code" => isset($this->configUi[$connector]['steps'][2]) ? $this->configUi[$connector]['steps'][2]['userGroup'] : "",
                    "next_step_num" => isset($this->configUi[$connector]['steps'][2]) ? 2 : "0",
                    "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($this->configCore[$connector]['formatNota']);
                if (!in_array($counterForNumber[0], $this->configCore[$connector]['counters'])) {
                    die(__LINE__ . " Used number should be registered in 'counters' config as well");
                }

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

                }

                $tmpNomorNota2 = $paramSpec['paramString'];


                //</editor-fold>
                //endregion

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

                        $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                        switch ($paramSpec['id']) {
                            case 0: //===counter type is new
                                $addData = array(
                                    "toko_id" => $tokoID,
                                    "toko_nama" => $tokoNama,
                                );
                                $paramKeyRaw = print_r($cParams, true);
                                $paramValuesRaw = print_r($cValues[$i], true);
                                $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                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,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                foreach ($masterReplacers as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }

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


                //region ----------write transaksi & transaksi_data #2
                if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                    $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'] : "",

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

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

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

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

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


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

                            }
                        }
                    }
                }

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

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


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

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


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


                    //cekMerah($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,
                    "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(),
                    'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                    'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                    'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                    'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                    'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                    'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                    'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                    'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                    'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                    // --
                    'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                    'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                    // --
                    '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(),
                    "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                );
                //                arrPrint($baseRegistries);
                $doWriteReg = $tr->writeRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                $mongRegIDConnect = $doWriteReg;
                //endregion
                //                arrPrint($baseRegistries);


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


        //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'");
        $tmpReg = $trr->lookupRegistries()->result();

        $origRequest = array();
        $stockActive = array();
        $pushToRequestPO = array();
        $pushToDisribution = array();

        $totalUnitToPush = 0;
        if (isset($this->configUi[$this->jenisTr]['pushPurchas'][$stepNum])) {
            //                matidisini("under maintenance ".__LINE__);
            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;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }


        //        cekHitam("## origRequest ##");
        //        arrPrint($origRequest);
        //        cekHitam("## stockActive ##");
        //        arrPrint($stockActive);
        //        cekHitam("## pushToRequestPO ##");
        //        arrPrint($pushToRequestPO);
        //        cekHitam("## pushToDisribution ##");
        //        arrPrint($pushToDisribution);
        //
        //        cekOrange("## totalUnitToPush: $totalUnitToPush ##");
        //matiHere();
        //        }

        //endregion check stock produk

        //region connecting connectToPrePurchase
        $mongPrePurcash = array();
        $mongPrePurcashReg = array();
        if ($totalUnitToPush > 0) {

            cekMerah("total Unit To Push: $totalUnitToPush || ada yg akan masuk purchase...!");
            //cekMerah("//cek connecting dari $origJenis========================================");
            $steps = isset($this->configUi[$origJenis]['steps']) ? $this->configUi[$origJenis]['steps'] : array();
            $connector = isset($this->configUi[$origJenis]['connectToPrePurchase']) ? $this->configUi[$origJenis]['connectToPrePurchase'] : "";

            if (strlen($connector) > 0) {
                cekMerah("to be connected to $connector");
                if ($stepNum == sizeof($steps)) {
                    cekMerah("now connecting to $connector");
                    if (!array_key_exists($connector, $this->configUi)) {
                        die("kode connector tidak dikenali!");
                    }
                    if (sizeof($this->configUi[$connector]['steps']) < 2) {
                        die("konfigurasi connector harus memiliki step lebih dari satu!");
                    }

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

                    $_SESSION[$cCode] = array();
                    $_SESSION[$cCode] = array(
                        "main" => $_SESSION[$oldCode]['main'],
                        "items" => $_SESSION[$oldCode]['items'],
                        "tableIn_master" => $_SESSION[$oldCode]['tableIn_master'],
                        "tableIn_detail" => $_SESSION[$oldCode]['tableIn_detail'],
                        "rsltItems" => $_SESSION[$oldCode]['rsltItems'],
                        //                    "out_detail_rsltItems" => $_SESSION[$oldCode]['out_detail_rsltItems'],
                        "tableIn_detail_rsltItems" => $_SESSION[$oldCode]['tableIn_detail_rsltItems'],
                        "tableIn_master_values" => $_SESSION[$oldCode]['tableIn_master_values'],
                        "tableIn_detail_values" => $_SESSION[$oldCode]['tableIn_detail_values'],
                        "tableIn_detail_values_rsltItems" => $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'],
                    );

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

                    );
                    //                arrPrint($masterReplacersO);
                    //                matiHere();
                    foreach ($masterReplacersO as $key => $val) {
                        $_SESSION[$cCode]['main'][$key] = $val;
                    }

                    //                arrPrint($_SESSION[$cCode]['main']);
                    //                matiHere();
                    $masterReplacers = array(
                        //                    "referensi_id" => $masterID, (dimatikan)
                        "inv" => $tmpNomorNota,
                        "jenis_master" => $connector,
                        "jenis_top" => $this->configUi[$connector]['steps'][1]['target'],
                        "jenis" => $this->configUi[$connector]['steps'][1]['target'],
                        "jenis_label" => $this->configUi[$connector]['steps'][1]['label'],
                        "transaksi_jenis" => $this->configUi[$connector]['steps'][1]['target'],
                        "cabang_id" => $_SESSION[$cCode]['tableIn_master']['cabang_id'],
                        "cabang_nama" => $_SESSION[$cCode]['tableIn_master']['cabang_nama'],
                        "cabang2_id" => $_SESSION[$cCode]['tableIn_master']['cabang2_id'],
                        "cabang2_nama" => $_SESSION[$cCode]['tableIn_master']['cabang2_nama'],
                        "gudang_id" => $_SESSION[$cCode]['tableIn_master']['gudang_id'],
                        "gudang_nama" => $_SESSION[$cCode]['tableIn_master']['gudang_nama'],
                        "gudang2_id" => $_SESSION[$cCode]['tableIn_master']['gudang2_id'],
                        "gudang2_nama" => $_SESSION[$cCode]['tableIn_master']['gudang2_nama'],
                        "gudang" => "",
                        "gudang__name" => "",
                        "gudang__label" => "",

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

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

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

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

                    }

                    $tmpNomorNota2 = $paramSpec['paramString'];


                    //</editor-fold>
                    //endregion

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

                            $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                            switch ($paramSpec['id']) {
                                case 0: //===counter type is new
                                    $addData = array(
                                        "toko_id" => $tokoID,
                                        "toko_nama" => $tokoNama,
                                    );
                                    $paramKeyRaw = print_r($cParams, true);
                                    $paramValuesRaw = print_r($cValues[$i], true);
                                    $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                    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,
                        "counters" => $appliedCounters2,
                        "counters_intext" => $appliedCounters_inText2,
                    );
                    foreach ($masterReplacers as $key => $val) {
                        $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                    }

                    //===cloning detail/items cabang1 ke cabang2
                    //===yang direplace: sub_step_number, sub_step_current, sub_step_avail, next_substep_num, next_substep_code, next_substep_label, next_subgroup_code

                    //                arrPrint($_SESSION[$cCode]['tableIn_detail']);

                    if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                        foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                            if (isset($pushToRequestPO)) {
                                foreach ($pushToRequestPO as $pid => $vals) {

                                    $detailReplacers[$pid] = array(
                                        "valid_qty" => $vals,
                                        "sub_step_avail" => sizeof($this->configUi[$connector]['steps']),
                                        "sub_step_current" => 1,
                                        "sub_step_number" => 1,
                                        "next_substep_num" => $_SESSION[$cCode]['tableIn_master']['next_step_num'],
                                        "next_substep_code" => $_SESSION[$cCode]['tableIn_master']['next_step_code'],
                                        "next_substep_label" => $_SESSION[$cCode]['tableIn_master']['next_step_label'],
                                        "next_subgroup_code" => $_SESSION[$cCode]['tableIn_master']['next_group_code'],
                                    );

                                    if ($vals > 0) {
                                        foreach ($dSpec as $key => $val) {
                                            if ($pid == $k) {
                                                $_SESSION[$cCode]['tableIn_detail'][$pid][$key] = isset($detailReplacers[$pid][$key]) ? $detailReplacers[$pid][$key] : $val;
                                                //                                            cekMerah("pid build: " . $pid);
                                            }
                                        }

                                    }
                                    else {
                                        foreach ($dSpec as $key => $val) {
                                            if ($pid == $k) {
                                                unset($_SESSION[$cCode]['tableIn_detail'][$pid]);
                                                //                                            cekMerah("pid delete: " . $pid);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else {
                        //                    cekmerah("GAGAL tulis rincian transaksi kedua");
                    }

                    //region ----------write transaksi & transaksi_data #2
                    if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                        $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();
                        foreach ($_SESSION[$cCode]['tableIn_detail'] 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_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                        $insertIDs = array();
                        foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                            $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                            $mongPrePurcash['detail'] = $insertIDs;
                            if ($epID != 999) {
                                $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                $mongPrePurcash['detail'] = $insertIDs;
                            }
                        }
                    }

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

                                }
                            }
                        }
                    }


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

                                }
                            }
                        }
                    }

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

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


                        //cekMerah(__LINE__. " " .$this->db->last_query());

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

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


                        //cekMerah(__LINE__. " " .$this->db->last_query());

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

                    $idHis_decode[$stepNum] = array(
                        "step" => $stepNum,
                        "trID" => $insertID,
                        "nomer" => $tmpNomorNota2,
                        "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(),
                        'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                        'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : 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(),
                    );
                    $doWriteReg = $tr->writeRegistries($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("link_id=0");
            $l->addFilter("produk_id in (" . implode(",", array_keys($_SESSION[$cCode]['items'])) . ")");
            $tmp = $l->lookupJoined()->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 --");
        matiHere("DONE belum comit yuaaa " . __METHOD__ . " @" . __LINE__);
        //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

        echo "<script>top.close_holdon()</script>";
        // mati_disini(__FUNCTION__ . " *** TRANSAKSI BERHASIL (UNDER MAINTENANCE) *** <br> silahkan tutup browser terlebih dahulu ");

        //        if($this->jenisTr == "1119"){
        //            mati_disini(__FUNCTION__ . " *** TRANSAKSI BERHASIL (UNDER MAINTENANCE) *** <br> silahkan tutup browser terlebih dahulu ");
        //        }
        //        arrPrint($mongoList);
        //        arrPrint($mongUpdateList);
        //        arrPrint($mongRegID);

        //        arrPrint($mongoListConnect);
        //        arrPrint($mongRegIDConnect);
        //        arrPrint($mongPrePurcash);
        //        arrPrint($mongPrePurcashReg);
        // matiHEre("selesai complitt");
        // $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");


        //region cloning ke mongo
        //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) {
                            //                            arrPrint($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

        // by pass mongo
        $mongRegID = array();
        cekBlue($mongRegID, __METHOD__ . " @" . __LINE__);
        //region write Registry mongo current
        if (sizeof($mongRegID) > 0) {
            //            $mongRegID = $mongoList['main'];
            $tr->setTableName("transaksi_registry");
            $tr->setFilters(array());
            $tr->setSortBy(array());
            $tr->addFilter("id in (" . implode(",", $mongRegID) . ")");
            $tmpTrm = $tr->lookUpAll()->result();

            $mong->setTableName("transaksi_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_registry");
            $tr->setFilters(array());
            $tr->setSortBy(array());
            $tr->addFilter("id in (" . implode(",", $mongRegIDConnect) . ")");
            $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

        //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])) {
            unset($_SESSION[$cCode]);
        }

        if (isset($_SESSION["_TR_" . $origJenis])) {
            unset($_SESSION["_TR_" . $origJenis]);
        }

        if (isset($oldCode)) {
            if (isset($_SESSION[$oldCode])) {
                unset($_SESSION[$oldCode]);
            }
        }

        //region feedback msg
        $this->session->errMsg = "transaction entry has been saved<br>";
        $nextNum = $nextProp["num"];
        if (isset($this->configUi[$this->jenisTr]['steps'][$nextNum])) {
            $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . "</strong><br>";
            $this->session->errMsg .= "This entry needs to be authorized by <strong class='text-blue'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['userGroup'] . "</strong><br>";
            $trBackLink = base_url() . get_class($this) . "/viewIncomplete/" . $this->jenisTr;

        }
        else {
            $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white'>" . $this->configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . "</strong><br>";
            $trBackLink = base_url() . get_class($this) . "/viewHistory/" . $this->jenisTr;

        }
        $trBackClick = "location.href='$trBackLink'";
        //        $this->session->errMsg .= "<br><a href='JavaScript:void(0)' onclick=\"$trBackClick\">view entry</a><br>";
        //endregion

        if (isset($this->configLayout[$this->jenisTr]['allowPrint'][$stepNum])) {
            $printLocation = $this->configLayout[$this->jenisTr]['printLocation'];
            $printException = isset($this->configLayout[$this->jenisTr]['printException'][$stepNum]) ? "/" . $this->configLayout[$this->jenisTr]['printException'][$stepNum] : "";
            $printSettings = isset($this->configLayout[$this->jenisTr]['allowPrint'][$stepNum]) ? $this->configLayout[$this->jenisTr]['allowPrint'][$stepNum] : array();
            if (isset($printSettings['size'])) {
                switch ($printSettings['size']) {
                    case "normal":
                        //                        cekkuning("size: NORMAL");
                        echo "<script>";
                        echo "top.popBig('" . base_url() . $printLocation . "$tmpNomorNota2$printException');";
                        echo "top.location.reload();";
                        echo "</script>";
                        break;
                    case "small":
                        //                        cekkuning("size: SMALL");
                        echo "<script>";
                        echo "top.popSmall('" . base_url() . $printLocation . "$tmpNomorNota2$printException');";
                        echo "top.location.reload();";
                        echo "</script>";
                        break;
                    default:
                        //                        cekkuning("size: UNKNOWN");
                        break;
                }
            }
            else {
                $arrAlert = array(
                    "type" => "success",
                    "title" => "Transaction saved",
                    //                        "html" => "your order has been saved and ready to process",
                    "html" => $this->session->errMsg,
                    "timer" => "1500",
                    "showConfirmButton" => false,
                    "allowOutsideClick" => false,
                );
                echo swalAlert($arrAlert);
                // echo "<script>topReload(1500)</script>";
                echo topReload();
                // echo "</script>";
                unset($this->session->errMsg);
            }

        }
        else {
            $arrAlert = array(
                "type" => "success",
                "title" => "Transaction saved",
                //                        "html" => "your order has been saved and ready to process",
                "html" => $this->session->errMsg,
                "timer" => "1500",
                "showConfirmButton" => false,
                "allowOutsideClick" => false,
            );
            echo swalAlert($arrAlert);
            // echo "<script>topReload(1500)</script>";
            echo topReload();
            // echo "</script>";
            unset($this->session->errMsg);
        }


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


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

        $rejectException = $this->config->item('heTransaksi_rejectException') != NULL ? $this->config->item('heTransaksi_rejectException') : array();
        $referenceRevertConfigs = isset($this->configUi[$jenisTr]['referenceRevert']) ? $this->configUi[$jenisTr]['referenceRevert'] : array();
        $prepConfigs = null != $this->config->item('hePreProcessors') ? $this->config->item('hePreProcessors') : array();
        $postConfigs = null != $this->config->item('hePostProcessors') ? $this->config->item('hePostProcessors') : array();

        //region swap from registry, transaksi yang dibuka saat ini
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tmpReg = $tr->lookupDataRegistriesByMasterID($no)->result();
        cekmerah($this->db->last_query());
        if (sizeof($tmpReg) > 0) {
            foreach ($tmpReg as $row) {
                foreach ($row as $key_reg => $val_reg) {
                    if ($key_reg != "transaksi_id") {
                        $var = $key_reg;
                        $$var = unserialize(base64_decode($val_reg));
                    }
                }
            }
        }
        //endregion

        //region swap from main transaksi, transaksi yang dibuka saat ini
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        $tr->addFilter("id='$no'");
        $tmpTr = $tr->lookupMainTransaksi()->result();
        cekOrange($this->db->last_query());
        $currentInsertID = $insertID = $tmpTr[0]->id;
        $currentMasterID = $tmpTr[0]->id_master;
        $currentNomer = $insertNum = $tmpTr[0]->nomer;
        $thisStepNumber = $tmpTr[0]->step_number;
        //endregion


        echo "no saat ini : $no<br>";
        echo "no reference : " . $tmpTr[0]->id_top . "<br>";
        echo "masterTargetStepNum: $masterTargetStepNum<br>";
        echo "childTargetStepNum: $childTargetStepNum<br>";
        echo "stepNumCurrent: $stepNumCurrent<br>";


        $this->db->trans_start();
        //
        // jika ada connecting antar-cabang...
        cekHitam("jenisTr -> $jenisTr");
        cekhitam("checking dulu connecting antar cabang... (connecto transaksi_ui)");
        $connector = isset($this->configUi[$jenisTr]['connectTo']) ? $this->configUi[$jenisTr]['connectTo'] : "";
        $mongListUpadte = array();
        $mongoList = array();
        if (strlen($connector) > 0) {
            cekUngu(":: ADA CONNECTING :: connector-> $connector ::");
            cekBiru("bila ada normal, yang membatalkan pihak source/sumber/asal...");


            //region update step2an di masternya
            $nextMasterStep = $stepNumCurrent;
            $nextProp = array(
                "num" => $nextMasterStep,
                "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
            );
            echo "nextMasterStep: $nextMasterStep<br>";
            arrPrint($nextProp);

            //update masternya, transaksi TOP
            if ($tmpTr[0]->id_top != $no) {
                $arrData = array(
                    "next_step_code" => $nextProp['code'],
                    "next_step_label" => $nextProp['label'],
                    "next_group_code" => $nextProp['groupID'],
                    "next_step_num" => $nextProp['num'],
                    "step_current" => $masterTargetStepNum,
                    "step_number" => $masterTargetStepNum,
                );
                $arrData_detail = array(
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                    "next_substep_num" => $nextProp['num'],
                    "sub_step_current" => $masterTargetStepNum,
                    "sub_step_number" => $masterTargetStepNum,
                    //                "valid_qty" => $new_valid_qty,
                );
            }
            else {
                $arrData = array(
                    "next_step_code" => $nextProp['code'],
                    "next_step_label" => $nextProp['label'],
                    "next_group_code" => $nextProp['groupID'],
                    "next_step_num" => $nextProp['num'],
                    "step_current" => $masterTargetStepNum,
                    "step_number" => $childTargetStepNum,
                    "trash_4" => "1",
                    "cancel_dtime" => date("Y-m-d H:i:s"),
                    "cancel_name" => $this->session->login['id'],
                    "cancel_id" => $this->session->login['nama'],
                );
                $arrData_detail = array(
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                    "next_substep_num" => $nextProp['num'],
                    //            "sub_step_current" => 0,
                    "sub_step_number" => 0,
                );
            }
            $tr = new MdlTransaksi();
            $dupState = $tr->updateData(array(
                //                "id" => $no,
                "id" => $tmpTr[0]->id_top,
            ), $arrData) or die("Failed to update tr next-state!");

            $mongListUpadte['update']['main'][] = array(
                "where" => array(
                    "id" => $tmpTr[0]->id_top,
                ),
                "value" => $arrData,
            );
            cekHijau("UPDATE transaksi step sebelumnya...");
            cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
            //endregion

            //region update step transaksi 1 step sebelumnya (detail)
            if (sizeof($tmpTr) > 0) {
                $arrPrevID = $tmpTr[0]->ids_prev != null ? blobDecode($tmpTr[0]->ids_prev) : array($tmpTr[0]->id_top);
                arrPrint($arrPrevID);
                foreach ($arrPrevID as $prevID) {
                    $tb = new MdlTransaksi();
                    $tb->setFilters(array());
                    $dupState = $tb->updateData(array(
                        "id" => $prevID,
                    ), array(
                        "status_4" => "11",
                    )) or die("Failed to update tr next-state!");

                    $mongListUpadte['update']['main'][] = array(
                        "where" => array(
                            "id" => $prevID,
                        ),
                        "value" => array("status_4" => "11",),
                    );
                    cekKuning("UPDATE transaksi 1 step sebelumnya...");
                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");


                    $td = new MdlTransaksi();
                    $td->setFilters(array());
                    $rslt = $td->lookupJoinedByID($prevID)->result();
                    if (sizeof($rslt) > 0) {
                        foreach ($rslt as $rsltSpec) {
                            if (array_key_exists($rsltSpec->produk_id, $items)) {
                                $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                //                            cekHitam(":: $prevID :: $rsltSpec->valid_qty :: " . $items[$rsltSpec->produk_id]['qty'] . " :: $new_valid_qty ::");

                                if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                    $new_valid_qty = $rsltSpec->valid_qty;
                                    //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                }
                                else {
                                    $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                }
                                //                            cekHitam("ROLLBACK... :: valid_qty-> " . $rsltSpec->valid_qty . " :: kembali-> " . $items[$rsltSpec->produk_id]['qty'] . " :: " . $new_valid_qty);

                                $arrData_detail["valid_qty"] = $new_valid_qty;
                                $tr = new MdlTransaksi();
                                $tr->setFilters(array());
                                $tr->setTableName($tr->getTableNames()['detail']);
                                $dupState = $tr->updateData(array(
                                    "transaksi_id" => $prevID,
                                    "produk_id" => $rsltSpec->produk_id,
                                ), $arrData_detail) or die("Failed to update tr next-state!");
                                $mongListUpadte['update']['detail'][] = array(
                                    "where" => array(
                                        "transaksi_id" => $prevID,
                                        "produk_id" => $rsltSpec->produk_id,
                                    ),
                                    "value" => $arrData_detail,
                                );
                                cekKuning("UPDATE transaksi data...");
                                cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                            }
                        }
                    }

                }
            }
            //endregion

            //region update step yang sebelumnya aktif, transaksi yang dibuka sekarang
            // cekUngu($tmpTr[0]->id_top);
            // cekUngu("$no");
            // if ($tmpTr[0]->id_top != $no) {
            $tp = new MdlTransaksi();
            $dupState = $tp->updateData(array(
                "id" => $no,
                "step_number" => $stepNumCurrent,
            ), array(
                "step_number" => $childTargetStepNum,
                "trash_4" => "1",
                "cancel_dtime" => date("Y-m-d H:i:s"),
                "cancel_name" => $this->session->login['nama'],
                "cancel_id" => $this->session->login['id'],

            )) or die("Failed to update tr next-state!");
            $mongListUpadte['update']['main'][] = array(
                "where" => array(
                    "id" => $no,
                    "step_number" => $stepNumCurrent,
                ),
                "value" => array(
                    "step_number" => $childTargetStepNum,
                    "trash_4" => "1",
                    "cancel_dtime" => date("Y-m-d H:i:s"),
                    "cancel_name" => $this->session->login['nama'],
                    "cancel_id" => $this->session->login['id']),
            );
            cekLime("UPDATE transaksi ini... yang dibuka sekarang...");
            cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

            $to = new MdlTransaksi();
            $to->setFilters(array());
            $to->setTableName($to->getTableNames()['detail']);
            $dupState = $to->updateData(array(
                "transaksi_id" => $no,
            ), array(
                "next_substep_code" => $nextProp['code'],
                "next_substep_label" => $nextProp['label'],
                "next_subgroup_code" => $nextProp['groupID'],
                "next_substep_num" => $nextProp['num'],
                //            "sub_step_current" => 0,
                "sub_step_number" => 0,
            )) or die("Failed to update tr next-state!");
            $mongListUpadte['update']['main'][] = array(
                "where" => array(
                    "transaksi_id" => $no,
                ),
                "value" => array(
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                    "next_substep_num" => $nextProp['num'],
                    //            "sub_step_current" => 0,
                    "sub_step_number" => 0,
                ),
            );
            cekLime("UPDATE transaksi data...");
            cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
            // }
            //endregion

            //region sesuaikan signature untuk cloningan, ikut minus
            //        $dwsign = $tr->writeSignature($no, array(
            $dwsign = $tr->writeSignature($tmpTr[0]->id_top, array(
                "prev_id" => $no,
                "nomer" => "rejection",
                "step_number" => $childTargetStepNum,
                // ini minus step number
                "step_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['target'],
                "step_name" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'],
                "group_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['userGroup'],
                "oleh_id" => $this->session->login['id'],
                "oleh_nama" => $this->session->login['nama'],
                "keterangan" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                //            "transaksi_id" => $no,
            )) or die("Failed to write signature");
            $mongoList['sign'][] = $dwsign;
            cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
            //endregion

            // region netralisasi payment source
            $tr = New MdlTransaksi();
            $tr->setFilters(array());
            $tr->addFilter("sisa>0");
            $paymentSrc = $tr->lookupPaymentSrcByTransID($no)->result();
            cekBiru($this->db->last_query());
            if (sizeof($paymentSrc) > 0) {
                //            arrPrint($paymentSrc);
                foreach ($paymentSrc as $pSpec) {
                    if ($pSpec->terbayar == 0) {
                        $where = array(
                            "id" => $pSpec->id,
                            "transaksi_id" => $pSpec->transaksi_id,
                        );
                        $data = array(
                            "sisa" => 0,
                            "returned" => $pSpec->sisa,
                            "sisa_valas" => 0,
                            "returned_valas" => $pSpec->sisa_valas,
                        );

                        $tra = New MdlTransaksi();
                        $tra->setFilters(array());
                        $tra->updatePaymentSrc($where, $data);
                        cekUngu(":: mereject payment source bila ada...");
                        cekUngu($this->db->last_query());
                    }
                    else {
                        mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                    }
                }
            }
            else {
                cekBiru(":: tidak ada payment source... ::");
            }
            // endregion netralisasi payment source

            // region netralisasi extended step
            $tr = New MdlTransaksi();
            $tr->setFilters(array());
            $exTmp = $tr->lookupExtStepByTrID($no);
            if (sizeof($exTmp) > 0) {
                foreach ($exTmp as $exSpec) {

                    $tra = New MdlTransaksi();
                    $tra->setFilters(array());
                    $tra->rejectExtStepByID($exSpec['id']);
                    $mongListUpadte['update']['extra'][] = array(
                        "where" => array(
                            "id" => $exSpec['id'],
                        ),
                        "value" => array(
                            "state" => "-1",
                        ),
                    );
                    cekUngu(":: mereject extended step bila ada...");
                    cekUngu($this->db->last_query());
                }
            }
            else {
                cekBiru(":: tidak ada extended step... ::");
            }

            // endregion netralisasi extended step

            //==entry point
            if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {

                if (isset($this->configUiJenis["connectToReject"][$stepNumCurrent])) {
                    if ($this->configUiJenis["connectToReject"][$stepNumCurrent]["enabled"] == true) {
                        $masterID = $currentMasterID;
                        $connecTo = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                        cekHijau("START menjalankan REJECT... [$masterID] [$connecTo]");
                        if ($connecTo == NULL) {
                            mati_disini("kode edit transaksi tidak dikenali. segera hubungi admin.");
                        }
                        $oldCode = $cCode;
                        $cCode = "_TR_" . $connecTo;
                        $_SESSION[$cCode] = array(
                            'main' => isset($_SESSION[$oldCode]['main']) ? $_SESSION[$oldCode]['main'] : array(),
                            'items' => isset($_SESSION[$oldCode]['items']) ? $_SESSION[$oldCode]['items'] : array(),
                            'items2' => isset($_SESSION[$oldCode]['items2']) ? $_SESSION[$oldCode]['items2'] : array(),
                            'items2_sum' => isset($_SESSION[$oldCode]['items2_sum']) ? $_SESSION[$oldCode]['items2_sum'] : array(),
                            'itemSrc' => isset($_SESSION[$oldCode]['itemSrc']) ? $_SESSION[$oldCode]['itemSrc'] : array(),
                            'itemSrc_sum' => isset($_SESSION[$oldCode]['itemSrc_sum']) ? $_SESSION[$oldCode]['itemSrc_sum'] : array(),
                            'items3' => isset($_SESSION[$oldCode]['items3']) ? $_SESSION[$oldCode]['items3'] : array(),
                            'items3_sum' => isset($_SESSION[$oldCode]['items3_sum']) ? $_SESSION[$oldCode]['items3_sum'] : array(),
                            'items4' => isset($_SESSION[$oldCode]['items4']) ? $_SESSION[$oldCode]['items4'] : array(),
                            'items4_sum' => isset($_SESSION[$oldCode]['items4_sum']) ? $_SESSION[$oldCode]['items4_sum'] : array(),
                            'items5_sum' => isset($_SESSION[$oldCode]['items5_sum']) ? $_SESSION[$oldCode]['items5_sum'] : array(),
                            'items6_sum' => isset($_SESSION[$oldCode]['items6_sum']) ? $_SESSION[$oldCode]['items6_sum'] : array(),
                            'items7_sum' => isset($_SESSION[$oldCode]['items7_sum']) ? $_SESSION[$oldCode]['items7_sum'] : array(),
                            'items8_sum' => isset($_SESSION[$oldCode]['items8_sum']) ? $_SESSION[$oldCode]['items8_sum'] : array(),
                            'items9_sum' => isset($_SESSION[$oldCode]['items9_sum']) ? $_SESSION[$oldCode]['items9_sum'] : array(),
                            'items10_sum' => isset($_SESSION[$oldCode]['items10_sum']) ? $_SESSION[$oldCode]['items10_sum'] : array(),
                            'rsltItems' => isset($_SESSION[$oldCode]['rsltItems']) ? $_SESSION[$oldCode]['rsltItems'] : array(),
                            'rsltItems2' => isset($_SESSION[$oldCode]['rsltItems2']) ? $_SESSION[$oldCode]['rsltItems2'] : array(),
                            'rsltItems3' => isset($_SESSION[$oldCode]['rsltItems3']) ? $_SESSION[$oldCode]['rsltItems3'] : array(),
                            'tableIn_master' => isset($_SESSION[$oldCode]['tableIn_master']) ? $_SESSION[$oldCode]['tableIn_master'] : array(),
                            'tableIn_detail' => isset($_SESSION[$oldCode]['tableIn_detail']) ? $_SESSION[$oldCode]['tableIn_detail'] : array(),
                            'tableIn_detail2_sum' => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                            'tableIn_detail_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems'] : array(),
                            'tableIn_detail_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems2'] : array(),
                            'tableIn_master_values' => isset($_SESSION[$oldCode]['tableIn_master_values']) ? $_SESSION[$oldCode]['tableIn_master_values'] : array(),
                            'tableIn_detail_values' => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                            'tableIn_detail_values_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                            'tableIn_detail_values_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems2'] : array(),
                            'tableIn_detail_values2_sum' => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                            'main_add_values' => isset($_SESSION[$oldCode]['main_add_values']) ? $_SESSION[$oldCode]['main_add_values'] : array(),
                            'main_add_fields' => isset($_SESSION[$oldCode]['main_add_fields']) ? $_SESSION[$oldCode]['main_add_fields'] : array(),
                            'main_elements' => isset($_SESSION[$oldCode]['main_elements']) ? $_SESSION[$oldCode]['main_elements'] : array(),
                            'main_inputs' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                            'main_inputs_orig' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                            "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                            "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                            "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                            "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                            "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                            "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                            "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                            "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                            "revert" => isset($_SESSION[$oldCode]['revert']) ? $_SESSION[$oldCode]['revert'] : array(),
                            "items_komposisi" => isset($_SESSION[$oldCode]['items_komposisi']) ? $_SESSION[$oldCode]['items_komposisi'] : array(),
                            "items_noapprove" => isset($_SESSION[$oldCode]['items_noapprove']) ? $_SESSION[$oldCode]['items_noapprove'] : array(),
                            "jurnalItems" => isset($_SESSION[$oldCode]['jurnalItems']) ? $_SESSION[$oldCode]['jurnalItems'] : array(),
                            "componentsBuilder" => isset($_SESSION[$oldCode]['componentsBuilder']) ? $_SESSION[$oldCode]['componentsBuilder'] : array(),
                        );
                        // masuk ke gerbang TableInMaster, tabel transaksi
                        $masterReplacers = array(
//                        "inv" => $tmpNomorNota,
                            "jenis_master" => $this->jenisTr,
                            "jenis_top" => $connecTo,
                            "jenis" => $connecTo,
                            "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "transaksi_jenis" => $connecTo,
                            "step_avail" => 1,
                            "step_current" => 1,
                            "step_number" => 1,
                            "next_step_code" => "",
                            "next_step_label" => "",
                            "next_group_code" => "",
                            "next_step_num" => "0",
                            "trash_4" => 1,
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],
                            "deskripsi" => "rejection",

                        );
                        // masuk ke gerbang main
                        $masterReplacersO = array(
                            "stepCode" => $connecTo,
                            "jenisTrTop" => $connecTo,
                            "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
//                        "inv" => $tmpNomorNota,
                            "jenis_master" => $this->jenisTr,
                            "jenis_top" => $connecTo,
                            "jenis" => $connecTo,
                            "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "transaksi_jenis" => $connecTo,
                            "stepCode" => $connecTo,
                            "jenisTrTop" => $connecTo,
                            "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "step_avail" => 1,
                            "step_current" => 1,
                            "step_number" => 1,
                            "next_step_code" => "",
                            "next_step_label" => "",
                            "next_group_code" => "",
                            "next_step_num" => "0",
                        );
                        foreach ($masterReplacersO as $key => $val) {
                            $_SESSION[$cCode]['main'][$key] = $val;
                        }
                        foreach ($masterReplacers as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }

                        $tokoID = $_SESSION[$cCode]['main']['tokoID'];
                        $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];

                        //region penomoran receipt
                        $this->load->model("CustomCounter");
                        $cn = new CustomCounter("transaksi");
                        $cn->setType("transaksi");
                        $counterForNumber = array($this->configValues[$this->jenisTr]['formatNotaReject']);
                        if (!in_array($counterForNumber[0], $this->configValues[$this->jenisTr]['countersReject'])) {
                            die(__LINE__ . " Used number should be registered in 'counters' config as well");
                        }
                        echo "<div style='background:#ff7766;'>";
                        foreach ($counterForNumber as $i => $cRawParams) {
                            $cParams = explode("|", $cRawParams);
                            $cValues = array();
                            foreach ($cParams as $param) {
                                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                            }
                            $cRawValues = implode("|", $cValues[$i]);
                            $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                        }
                        echo "</div style='background:#ff7766;'>";

                        $stepNumber = 1;
                        $tmpNomorNota = $paramSpec['paramString'];
                        $tmpNomorNotaAlias = formatNota("nomer_nolink", $tmpNomorNota);
                        $nextProp = array(
                            "num" => 0,
                            "code" => "",
                            "label" => "",
                            "groupID" => "",
                        );
                        //endregion

                        //region dynamic counters
                        // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                        $cn = new CustomCounter("transaksi");
                        $cn->setType("transaksi");
                        $configCustomParams = $this->configValues[$this->jenisTr]['countersReject'];
                        arrPrintHijau($configCustomParams);
                        $configCustomParams[] = "stepCode";
                        //arrPrint($configCustomParams);
                        if (sizeof($configCustomParams) > 0) {
                            $cContent = array();
                            foreach ($configCustomParams as $i => $cRawParams) {
                                $cParams = explode("|", $cRawParams);
                                $cValues = array();
                                foreach ($cParams as $param) {
                                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                }
                                $cRawValues = implode("|", $cValues[$i]);
                                $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                                $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                                switch ($paramSpec['id']) {
                                    case 0: //===counter type is new
                                        $addData = array(
                                            "toko_id" => $tokoID,
                                            "toko_nama" => $tokoNama,
                                        );
                                        $paramKeyRaw = print_r($cParams, true);
                                        $paramValuesRaw = print_r($cValues[$i], true);
                                        $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                        break;
                                    default: //===counter to be updated
                                        $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                        break;
                                }
                                //echo "<hr>";
                            }
                        }
                        $appliedCounters = base64_encode(serialize($cContent));
                        $appliedCounters_inText = print_r($cContent, true);
                        //mati_disini();

                        //
                        //region addition on master


                        $addValues = array(
                            'counters' => $appliedCounters,
                            'counters_intext' => $appliedCounters_inText,
                            'nomer' => $tmpNomorNota,
                            'nomer2' => $tmpNomorNotaAlias,
                            'dtime' => date("Y-m-d H:i:s"),
                            'fulldate' => date("Y-m-d"),
                            "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                            "step_number" => 1,
                            "step_current" => 1,
                            "next_step_num" => $nextProp['num'],
                            "next_step_code" => $nextProp['code'],
                            "next_step_label" => $nextProp['label'],
                            "next_group_code" => $nextProp['groupID'],
                            "tail_number" => 1,
                            "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


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

                        //
                        //region addition on detail
                        $addSubValues = array(
                            "sub_step_number" => 1,
                            "sub_step_current" => 1,
                            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                            "next_substep_num" => $nextProp['num'],
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "sub_tail_number" => 1,
                            "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                        );
                        foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                            foreach ($addSubValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                            }
                        }
                        //endregion
                        // </editor-fold>
                        //endregion

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


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

                        $addValues = array(
                            'counters' => $appliedCounters,
                            'counters_intext' => $appliedCounters_inText,
                            'nomer' => $tmpNomorNota,
                            'nomer2' => $tmpNomorNotaAlias,
                            'dtime' => date("Y-m-d H:i:s"),
                            'fulldate' => date("Y-m-d"),
                        );
                        foreach ($addValues as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }
                        $masterReplacers = array(
                            "nomer" => $tmpNomorNota,
                            "nomer2" => $tmpNomorNotaAlias,
                            "counters" => $appliedCounters,
                            "counters_intext" => $appliedCounters_inText,
                        );
                        foreach ($masterReplacers as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }
                        $detailReplacers = array(
                            "sub_step_avail" => 1,
                            "sub_step_current" => 1,
                            "sub_step_number" => 1,
                            "next_substep_num" => "",
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                        );

                        arrPrintHijau($_SESSION[$cCode]['tableIn_master']);

                        if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                            foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                                foreach ($dSpec as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                                }
                            }
                        }
                        $itemsReplacers = array(
                            "next_substep_num" => "",
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                        );
                        if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                            foreach ($_SESSION[$cCode]['items'] as $k => $dSpec) {
                                foreach ($dSpec as $key => $val) {
                                    $_SESSION[$cCode]['items'][$k][$key] = isset($itemsReplacers[$key]) ? $itemsReplacers[$key] : $val;
                                }
                            }
                        }

                        //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
                        if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                            $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
                            $_SESSION[$cCode]['tableIn_master']['trash_4'] = 1;
                            $_SESSION[$cCode]['tableIn_master']['cli'] = 1;

                            $tr = new MdlTransaksi();
                            $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                            $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                            cekHitam("[$insertID] :: " . $this->db->last_query());
                            $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                            $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                            $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                            if ($insertID < 1) {
                                die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                            }
                            $mongoList['main'] = array($insertID, $epID);
                            //==transaksi_id dan nomor nota diinject kan ke gate utama
                            $injectors = array(
                                "transaksi_id" => $insertID,
                                "nomer" => $tmpNomorNota,
                                "nomer2" => $tmpNomorNotaAlias,
                            );
                            $arrInjectorsTarget = array(
                                "items",
                                "items2_sum",
                                "rsltItems",
                            );
                            foreach ($injectors as $key => $val) {
                                $_SESSION[$cCode]['main'][$key] = $val;
                                foreach ($arrInjectorsTarget as $target) {
                                    if (isset($_SESSION[$cCode][$target])) {
                                        foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                            $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                            if (isset($_SESSION[$cCode][$target][$id])) {
                                                $_SESSION[$cCode][$target][$id][$key] = $val;
                                            }
                                        }
                                    }
                                }
                            }

                            //===signature
                            $dwsign = $tr->writeSignature($insertID, array(
                                "nomer" => $_SESSION[$cCode]['main']['nomer'],
                                "step_number" => 1,
                                "step_code" => $connecTo,
                                "step_name" => $this->configUiJenis["connectToEdit"][1]["label"],
                                "group_code" => "",
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                                "transaksi_id" => $masterID,
                                "deskripsi" => "edit transaksi",
                                "cabang_id" => $this->session->login['cabang_id'],
                                "cabang_nama" => $this->session->login['cabang_nama'],
                                "current_transaksi_id" => $masterID,
                                "current_nomer" => $_SESSION[$cCode]['main']['nomer'],
                            )) or die("Failed to write signature");
                            showLast_query("kuning");
                            $mongoList['sign'][] = $dwsign;
                            $idHis = array(
                                $stepNumber => array(
                                    "olehID" => $_SESSION[$cCode]['main']['olehID'],
                                    "olehName" => $_SESSION[$cCode]['main']['olehName'],
                                    "step" => $stepNumber,
                                    "trID" => $insertID,
                                    "nomer" => $tmpNomorNota,
                                    "nomer2" => $tmpNomorNotaAlias,
                                    "counters" => $appliedCounters,
                                    "counters_intext" => $appliedCounters_inText,
                                ),
                            );
                            $idHis_blob = blobEncode($idHis);
                            $idHis_intext = print_r($idHis, true);
                            $tr = new MdlTransaksi();
                            $dupState = $tr->updateData(array("id" => $insertID), array(
                                "next_step_num" => $nextProp['num'],
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],

                                //===references
//                            "id_master" => $insertID,
                                "id_master" => $masterID,// milik transkasiID yang diedit
                                "id_top" => $insertID,
                                "ids_prev" => "",
                                "ids_prev_intext" => "",
                                "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                "nomers_prev" => "",
                                "nomers_prev_intext" => "",
                                "jenises_prev" => "",
                                "jenises_prev_intext" => "",
                                "ids_his" => $idHis_blob,
                                "ids_his_intext" => $idHis_intext,

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

                            $addValues = array(
                                //===references
                                "id_master" => $insertID,
                                "id_top" => $insertID,
                                "ids_prev" => "",
                                "ids_prev_intext" => "",
                                "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                "nomers_prev" => "",
                                "nomers_prev_intext" => "",
                                "jenises_prev" => "",
                                "jenises_prev_intext" => "",
                                "ids_his" => $idHis_blob,
                                "ids_his_intext" => $idHis_intext,
                            );
                            foreach ($addValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }

                        }
                        if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                            $inserMainValues = array();
                            if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                                //matiHEre("hooppp");
                                $inserMainValues = array();
                                foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                                    if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                                        $dd = $tr->writeMainValues($insertID, array(
                                            "key" => $key,
                                            "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                                        ));

                                        $inserMainValues[] = $dd;
                                        $mongoList['mainValues'][] = $dd;
                                    }
                                }
                            }

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

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

                            if (sizeof($inserMainValues) > 0) {
                                $arrBlob = blobEncode($inserMainValues);
                                $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                            foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                                $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                //                    cekkuning("making a clone for input key $key / $val");
                                //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                                //                    $replacers=array(
                                //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                                //                    );
                                //                    foreach($replacers as $key=>$val){
                                //                        $tmpTableIn[$key]=$val;
                                //                    }
                                //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                            foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                                $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                            foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                                $tr->writeMainApplets($insertID, array(
                                    "mdl_name" => $amdl,
                                    "key" => $aSpec['key'],
                                    "label" => $aSpec['labelValue'],
                                    "description" => $aSpec['description'],
                                ));
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                            foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                                $tr->writeMainElements($insertID, array(
                                    "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                                    "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                                    "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                                    "name" => $aSpec['name'],
                                    "label" => $aSpec['label'],
                                    "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                                    "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                                ));
                                //==nebeng bikin inputLabels
//                                $currentValue = "";
//                                switch ($aSpec['elementType']) {
//                                    case "dataModel":
//                                        $currentValue = $aSpec['key'];
//                                        break;
//                                    case "dataField":
//                                        $currentValue = $aSpec['value'];
//                                        break;
//                                }
//                                if (array_key_exists($elName, $relOptionConfigs)) {
//                                    //					cekhijau("$eName terdaftar pada relInputs");
//
//
//                                    if (isset($relOptionConfigs[$elName][$currentValue])) {
//                                        if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
//                                            foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
//                                                $inputLabels[$oValueName] = $oValSpec['label'];
//                                                if (isset($oValSpec['auth'])) {
//                                                    if (isset($oValSpec['auth']['groupID'])) {
//                                                        $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                    else {
//                                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
//                                    }
//
//                                }

                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

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


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

                                foreach ($indexing_details as $k => $arrID) {
                                    $arrBlob = blobEncode($arrID);
                                    $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                                    cekOrange($this->db->last_query());
                                }
                            }
                        }
                        else {
                            die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                                $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                                $mongoList['detail'] = $insertIDs;
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detail'] = $insertIDs;
                                }
                                cekUngu($this->db->last_query());
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                                $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                $insertIDs[] = $insertDetailID;
                                $mongoList['detail'][] = $insertDetailID;
                                if ($epID != 999) {
                                    $dd = $tr->writeDetailEntries($epID, $dSpec);
                                    $insertIDs[] = $dd;
                                    $mongoList['detail'][] = $dd;
                                }
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                                $dd = $tr->writeDetailEntries($insertID, $dSpec);
                                $insertIDs[] = $dd;
                                $mongoList['detil'][] = $dd;
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detil'] = $insertIDs;
                                }
                                cekUngu($this->db->last_query());
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

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

                                        }
                                    }
                                }
                            }

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

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

                        $baseRegistries = array(
                            'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                            'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                            'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                            'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                            'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                            'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                            'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                            'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                            'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                            'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                            'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                            'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                            'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                            'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                            'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                            'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                            'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                            'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                            'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                            'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                            'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                            'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                            'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                            'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                            'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                            'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                            'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                            'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                            'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                            'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                            'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                            'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                            'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                            'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                            "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                            "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                            "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                            "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                            "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                            "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                            "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                            "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                            "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                            "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                            "items_noapprove" => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),
                            "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                            "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                            //----
                            'mainOriginal' => isset($_SESSION[$cCode]['mainOriginal']) ? $_SESSION[$cCode]['mainOriginal'] : array(),
                            'itemsOriginal' => isset($_SESSION[$cCode]['itemsOriginal']) ? $_SESSION[$cCode]['itemsOriginal'] : array(),
                            //----
                        );
                        $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                        showLast_query("hijau");
                        cekHijau("SELESAI menjalankan EDITOR...");
                    }
                }
                else {
                    $tableIn_master['trash_4'] = 1;
                    $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                    $tableIn_master['cancel_name'] = $this->session->login['nama'];
                    $tableIn_master['cancel_id'] = $this->session->login['id'];
                    $tableIn_master['deskripsi'] = "rejection";
                    $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                    $mongoList['main'][] = $epID;
                    if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                        $insertIDs = array();
                        foreach ($tableIn_detail as $dSpec) {
                            if ($epID != 999) {
                                $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                $mongoList['detail'] = $insertIDs;
                            }
                        }
                    }
                }

            }
//            mati_disini(__LINE__);
            $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;
            $tokoID = $_SESSION[$cCode]['main']['tokoID'];
            $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];
            $transaksiMode = isset($this->configUi[$this->jenisTr]["transaksiMode"]) ? $this->configUi[$this->jenisTr]["transaksiMode"] : mati_disini("Mode transaksi silahkan diseting di coTransaksiUi " . $this->jenisTr);
            $runCoreAkunting = isset($this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["runCoreAkunting"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["runCoreAkunting"] : false;
            $core = isset($this->config->item('heTransaksi_core')[$this->modul][$transaksiMode]) ? $this->config->item('heTransaksi_core')[$this->modul][$transaksiMode] : array();

            //===if rollback is needed
            //rollback preproc, master
            if (isset($core['preProcessor'][$jenisTr_component]['master'])) {
                $iterator = isset($core['preProcessor'][$jenisTr_component]['master']) ? $core['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($core['preProcessor'][$jenisTr_component]['detail'])) {
                $iterator = isset($core['preProcessor'][$jenisTr_component]['detail']) ? $core['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->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                $iterator = isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configValues[$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->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {
                $iterator = isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configValues[$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!");
                    $mongListUpadte['update']['main'][] = array(
                        "where" => array(
                            "id" => $connectorID,
                        ),
                        "value" => array(
                            "status_4" => "11",
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],
                        ),
                    );
                    cekHitam("UPDATE transaksi connector -- selanjutnya yang digenerate by system");
                    cekHitam($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    $to = new MdlTransaksi();
                    $to->setFilters(array());
                    $to->setTableName($to->getTableNames()['detail']);
                    $dupState = $to->updateData(array(
                        "transaksi_id" => $connectorID,
                    ), array(
                        "next_substep_code" => "",
                        "next_substep_label" => "",
                        "next_subgroup_code" => "",
                        "next_substep_num" => 0,
                        //            "sub_step_current" => 0,
                        "sub_step_number" => 0,
                    )) or die("Failed to update tr next-state!");
                    $mongListUpadte['update']['detail'][] = array(
                        "where" => array(
                            "transaksi_id" => $connectorID,
                        ),
                        "value" => array(
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                            "next_substep_num" => 0,
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        ),
                    );
                    cekHitam("UPDATE transaksi data connector -- selanjutnya yang digenerate by system");
                    cekHitam($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                }
            }
            //endregion

        }
        else {
            cekUngu(":: CHECK CONNECTING MUNDUR :: $jenisTr ::");
//mati_disini("cek konekting mundur...");
//            $origTCode = heGetOriginTCode_orig($jenisTr); // mencari transaksi yang connecto 110
            $origTCode = heGetOriginTCode_orig_he_stepping($jenisTr, $this->configUi); // mencari transaksi yang connecto ke $jenisTr
            cekMerah("origTCode: $origTCode");

            if (strlen($origTCode) > 2) {
                cekMerah("origTCode: $origTCode, ADA CONNECTING MUNDUR...");
                cekBiru("bila tidak normal, yang membatalkan pihak target/tujuan...");
                cekBiru("dan ada connecting ke belakang...");
                cekKuning("[$origTCode] step transaksi ini " . $thisStepNumber);

                if ($thisStepNumber == 1) {

                    //region transaksi connector -> 583 / 759
                    $arrSteps = isset($this->configUi[$origTCode]['steps']) ? $this->configUi[$origTCode]['steps'] : "";
                    $lastCode = $origTCode;
                    if (sizeof($arrSteps) > 0) {
                        foreach ($arrSteps as $stSpec) {
                            $lastCode = $stSpec['target'];
                        }
                    }
                    if (sizeof($rejectException) > 0 && (!in_array($lastCode, $rejectException['code']))) {
                        $tb = new MdlTransaksi();
                        $tb->setFilters(array());
                        $tb->addFilter("id_master='" . $tmpTr[0]->id_master . "'");
                        $tb->addFilter("jenis_master='$origTCode'");
                        $tb->addFilter("jenis='$lastCode'");
                        $tb->setSortBy(array("kolom" => "id", "mode" => "DESC"));
                        $trTmp = $tb->lookupAll()->result();
                    }
                    else {
                        $trTmp = array();
                    }
                    cekHere($this->db->last_query() . " --> [" . count($trTmp) . "]");

                    if (sizeof($trTmp) > 0) {
                        cekHere(":: BENER BENER CONNECTING ANTAR INSTANSI - PUSAT -> CABANG ::");

                        $jenisTr = $origTCode;
                        $stepNumCurrent = $trTmp[0]->step_number;

                        cekHere("jenisTR $jenisTr, idTR " . $trTmp[0]->id);


                        //region swap from registry
                        $tr = new MdlTransaksi();
                        $tmpReg = $tr->lookupDataRegistriesByMasterID($trTmp[0]->id)->result();
                        cekmerah($this->db->last_query());
                        if (sizeof($tmpReg) > 0) {
                            foreach ($tmpReg as $row) {
                                foreach ($row as $key_reg => $val_reg) {
                                    if ($key_reg != "transaksi_id") {
                                        $var = $key_reg;
                                        $$var = unserialize(base64_decode($val_reg));
                                    }
                                }
                            }
                        }
                        //        arrPrint($items);
                        //endregion

                        $nextMasterStep = $stepNumCurrent;
                        $nextProp = array(
                            "num" => $nextMasterStep,
                            "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                            "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                            "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
                        );
                        echo __LINE__ . " :: nextMasterStep: $nextMasterStep<br>";
                        arrPrint($nextProp);

                        $arrData = array(
                            "next_step_code" => $nextProp['code'],
                            "next_step_label" => $nextProp['label'],
                            "next_group_code" => $nextProp['groupID'],
                            "next_step_num" => $nextProp['num'],
                            "step_current" => $masterTargetStepNum,
                            "step_number" => $childTargetStepNum,
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],
                        );
                        $arrData_detail = array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        );

                        //region update step transaksi connector dan TOP-nya
                        if (sizeof($trTmp) > 0) {
                            cekUngu(":: trID -> " . $trTmp[0]->id);

                            //region update transaksi connector-nya
                            $prevID = $trTmp[0]->id;
                            $tc = new MdlTransaksi();
                            $tc->setFilters(array());
                            $dupState = $tc->updateData(array(
                                "id" => $prevID,
                            ), $arrData) or die("Failed to update tr next-state!");
                            cekKuning("UPDATE transaksi connector...");
                            cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                            $mongListUpadte['update']['main'][] = array(
                                "where" => array(
                                    "id" => $prevID,
                                ),
                                "value" => $arrData,
                            );
                            $td = new MdlTransaksi();
                            $td->setFilters(array());
                            $rslt = $td->lookupJoinedByID($prevID)->result();
                            if (sizeof($rslt) > 0) {
                                foreach ($rslt as $rsltSpec) {
                                    if (array_key_exists($rsltSpec->produk_id, $items)) {
                                        $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];

                                        if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                            $new_valid_qty = $rsltSpec->valid_qty;
                                            //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                        }
                                        else {
                                            $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                        }


                                        $arrData_detail["valid_qty"] = $new_valid_qty;
                                        $arrData_detail["sub_step_number"] = 0;
                                        $tr = new MdlTransaksi();
                                        $tr->setFilters(array());
                                        $tr->setTableName($tr->getTableNames()['detail']);
                                        $dupState = $tr->updateData(array(
                                            "transaksi_id" => $prevID,
                                            "produk_id" => $rsltSpec->produk_id,
                                        ), $arrData_detail) or die("Failed to update tr next-state!");
                                        $mongListUpadte['update']['detail'][] = array(
                                            "where" => array(
                                                "transaksi_id" => $prevID,
                                                "produk_id" => $rsltSpec->produk_id,
                                            ),
                                            "value" => $arrData_detail,
                                        );
                                        cekKuning("UPDATE transaksi data...");
                                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                                    }
                                }
                            }
                            //endregion


                            //region update transaksi ID TOP, transaksi induk-nya
                            $arrData = array(
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],
                                "next_step_num" => $nextProp['num'],
                                //                            "step_current" => $masterTargetStepNum,
                                //                            "step_number" => $masterTargetStepNum,
                                //                            "trash_4" => "1",
                                "step_current" => $nextProp['num'] - 1,
                                "step_number" => $nextProp['num'] - 1,
                            );
                            $arrData_detail = array(
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "next_substep_num" => $nextProp['num'],
                                //                            "sub_step_current" => $masterTargetStepNum,
                                //                            "sub_step_number" => $masterTargetStepNum,
                                "sub_step_current" => $nextProp['num'] - 1,
                                "sub_step_number" => $nextProp['num'] - 1,
                            );
                            $prevID = $trTmp[0]->id_top;
                            $tc = new MdlTransaksi();
                            $tc->setFilters(array());
                            $dupState = $tc->updateData(array(
                                "id" => $prevID,
                            ), $arrData) or die("Failed to update tr next-state!");
                            $mongListUpadte['update']['main'][] = array(
                                "where" => array("id" => $prevID,),
                                "value" => $arrData,
                            );
                            cekLime("UPDATE transaksi 1 step sebelumnya...");
                            cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                            $td = new MdlTransaksi();
                            $td->setFilters(array());
                            $rslt = $td->lookupJoinedByID($prevID)->result();
                            if (sizeof($rslt) > 0) {
                                foreach ($rslt as $rsltSpec) {
                                    if (array_key_exists($rsltSpec->produk_id, $items)) {
                                        $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];

                                        if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                            $new_valid_qty = $rsltSpec->valid_qty;
                                            //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                        }
                                        else {
                                            $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                        }


                                        $arrData_detail["valid_qty"] = $new_valid_qty;
                                        $tr = new MdlTransaksi();
                                        $tr->setFilters(array());
                                        $tr->setTableName($tr->getTableNames()['detail']);
                                        $dupState = $tr->updateData(array(
                                            "transaksi_id" => $prevID,
                                            "produk_id" => $rsltSpec->produk_id,
                                        ), $arrData_detail) or die("Failed to update tr next-state!");
                                        $mongListUpadte['update']['detail'][] = array(
                                            "where" => array(
                                                "transaksi_id" => $prevID,
                                                "produk_id" => $rsltSpec->produk_id,
                                            ),
                                            "value" => $arrData_detail,
                                        );
                                        cekLime("UPDATE transaksi data...");
                                        cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                                    }
                                }
                            }
                            //endregion


                        }

                        //endregion

                        //region sesuaikan signature untuk cloningan, ikut minus
                        //        $dwsign = $tr->writeSignature($no, array(
                        $dwsign = $tb->writeSignature($trTmp[0]->id, array(
                            "prev_id" => $trTmp[0]->id,
                            "nomer" => "rejection",
                            "step_number" => $childTargetStepNum, // ini minus step number
                            "step_code" => $this->configUi[$origTCode]['steps'][abs($childTargetStepNum)]['target'],
                            "step_name" => $this->configUi[$origTCode]['steps'][abs($childTargetStepNum)]['label'],
                            "group_code" => $this->configUi[$origTCode]['steps'][abs($childTargetStepNum)]['userGroup'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "keterangan" => $this->configUi[$origTCode]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                            //            "transaksi_id" => $no,
                        )) or die("Failed to write signature");
                        $mongoList['sign'][] = $dwsign;
                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        //endregion

                        // region netralisasi payment source
                        $tr = New MdlTransaksi();
                        $tr->setFilters(array());
                        $tr->addFilter("sisa>0");
                        $paymentSrc = $tr->lookupPaymentSrcByTransID($trTmp[0]->id)->result();
                        cekBiru($this->db->last_query());
                        if (sizeof($paymentSrc) > 0) {
                            //            arrPrint($paymentSrc);
                            foreach ($paymentSrc as $pSpec) {
                                if ($pSpec->terbayar == 0) {
                                    $where = array(
                                        "id" => $pSpec->id,
                                        "transaksi_id" => $pSpec->transaksi_id,
                                    );
                                    $data = array(
                                        "sisa" => 0,
                                        "returned" => $pSpec->sisa,
                                        "sisa_valas" => 0,
                                        "returned_valas" => $pSpec->sisa_valas,
                                    );

                                    $tra = New MdlTransaksi();
                                    $tra->setFilters(array());
                                    $tra->updatePaymentSrc($where, $data);
                                    cekUngu(":: mereject payment source bila ada...");
                                    cekUngu($this->db->last_query());
                                }
                                else {
                                    mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                                }
                            }
                        }
                        else {
                            cekBiru(":: tidak ada payment source... ::");
                        }
                        // endregion netralisasi payment source

                        // region netralisasi extended step
                        $tr = New MdlTransaksi();
                        $tr->setFilters(array());
                        $exTmp = $tr->lookupExtStepByTrID($trTmp[0]->id);
                        if (sizeof($exTmp) > 0) {
                            foreach ($exTmp as $exSpec) {

                                $tra = New MdlTransaksi();
                                $tra->setFilters(array());
                                $tra->rejectExtStepByID($exSpec['id']);
                                $mongListUpadte['update']['extra'][] = array(
                                    "where" => array(
                                        "id" => $exSpec['id'],
                                    ),
                                    "value" => array(
                                        "state" => "-1",
                                    ),
                                );
                                cekUngu(":: mereject extended step bila ada...");
                                cekUngu($this->db->last_query());
                            }
                        }
                        else {
                            cekBiru(":: tidak ada extended step... ::");
                        }

                        // endregion netralisasi extended step

                        //==entry point
                        if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                            if (isset($this->configUiJenis["connectToReject"][$stepNumCurrent])) {
                                if ($this->configUiJenis["connectToReject"][$stepNumCurrent]["enabled"] == true) {
                                    $masterID = $currentMasterID;
                                    $connecTo = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                                    cekHijau("START menjalankan REJECT... [$masterID] [$connecTo]");
                                    if ($connecTo == NULL) {
                                        mati_disini("kode edit transaksi tidak dikenali. segera hubungi admin.");
                                    }
                                    $oldCode = $cCode;
                                    $cCode = "_TR_" . $connecTo;
                                    $_SESSION[$cCode] = array(
                                        'main' => isset($_SESSION[$oldCode]['main']) ? $_SESSION[$oldCode]['main'] : array(),
                                        'items' => isset($_SESSION[$oldCode]['items']) ? $_SESSION[$oldCode]['items'] : array(),
                                        'items2' => isset($_SESSION[$oldCode]['items2']) ? $_SESSION[$oldCode]['items2'] : array(),
                                        'items2_sum' => isset($_SESSION[$oldCode]['items2_sum']) ? $_SESSION[$oldCode]['items2_sum'] : array(),
                                        'itemSrc' => isset($_SESSION[$oldCode]['itemSrc']) ? $_SESSION[$oldCode]['itemSrc'] : array(),
                                        'itemSrc_sum' => isset($_SESSION[$oldCode]['itemSrc_sum']) ? $_SESSION[$oldCode]['itemSrc_sum'] : array(),
                                        'items3' => isset($_SESSION[$oldCode]['items3']) ? $_SESSION[$oldCode]['items3'] : array(),
                                        'items3_sum' => isset($_SESSION[$oldCode]['items3_sum']) ? $_SESSION[$oldCode]['items3_sum'] : array(),
                                        'items4' => isset($_SESSION[$oldCode]['items4']) ? $_SESSION[$oldCode]['items4'] : array(),
                                        'items4_sum' => isset($_SESSION[$oldCode]['items4_sum']) ? $_SESSION[$oldCode]['items4_sum'] : array(),
                                        'items5_sum' => isset($_SESSION[$oldCode]['items5_sum']) ? $_SESSION[$oldCode]['items5_sum'] : array(),
                                        'items6_sum' => isset($_SESSION[$oldCode]['items6_sum']) ? $_SESSION[$oldCode]['items6_sum'] : array(),
                                        'items7_sum' => isset($_SESSION[$oldCode]['items7_sum']) ? $_SESSION[$oldCode]['items7_sum'] : array(),
                                        'items8_sum' => isset($_SESSION[$oldCode]['items8_sum']) ? $_SESSION[$oldCode]['items8_sum'] : array(),
                                        'items9_sum' => isset($_SESSION[$oldCode]['items9_sum']) ? $_SESSION[$oldCode]['items9_sum'] : array(),
                                        'items10_sum' => isset($_SESSION[$oldCode]['items10_sum']) ? $_SESSION[$oldCode]['items10_sum'] : array(),
                                        'rsltItems' => isset($_SESSION[$oldCode]['rsltItems']) ? $_SESSION[$oldCode]['rsltItems'] : array(),
                                        'rsltItems2' => isset($_SESSION[$oldCode]['rsltItems2']) ? $_SESSION[$oldCode]['rsltItems2'] : array(),
                                        'rsltItems3' => isset($_SESSION[$oldCode]['rsltItems3']) ? $_SESSION[$oldCode]['rsltItems3'] : array(),
                                        'tableIn_master' => isset($_SESSION[$oldCode]['tableIn_master']) ? $_SESSION[$oldCode]['tableIn_master'] : array(),
                                        'tableIn_detail' => isset($_SESSION[$oldCode]['tableIn_detail']) ? $_SESSION[$oldCode]['tableIn_detail'] : array(),
                                        'tableIn_detail2_sum' => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                                        'tableIn_detail_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems'] : array(),
                                        'tableIn_detail_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems2'] : array(),
                                        'tableIn_master_values' => isset($_SESSION[$oldCode]['tableIn_master_values']) ? $_SESSION[$oldCode]['tableIn_master_values'] : array(),
                                        'tableIn_detail_values' => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                                        'tableIn_detail_values_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                                        'tableIn_detail_values_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems2'] : array(),
                                        'tableIn_detail_values2_sum' => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                                        'main_add_values' => isset($_SESSION[$oldCode]['main_add_values']) ? $_SESSION[$oldCode]['main_add_values'] : array(),
                                        'main_add_fields' => isset($_SESSION[$oldCode]['main_add_fields']) ? $_SESSION[$oldCode]['main_add_fields'] : array(),
                                        'main_elements' => isset($_SESSION[$oldCode]['main_elements']) ? $_SESSION[$oldCode]['main_elements'] : array(),
                                        'main_inputs' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                                        'main_inputs_orig' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                                        "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                                        "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                                        "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                                        "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                                        "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                                        "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                                        "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                                        "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                                        "revert" => isset($_SESSION[$oldCode]['revert']) ? $_SESSION[$oldCode]['revert'] : array(),
                                        "items_komposisi" => isset($_SESSION[$oldCode]['items_komposisi']) ? $_SESSION[$oldCode]['items_komposisi'] : array(),
                                        "items_noapprove" => isset($_SESSION[$oldCode]['items_noapprove']) ? $_SESSION[$oldCode]['items_noapprove'] : array(),
                                        "jurnalItems" => isset($_SESSION[$oldCode]['jurnalItems']) ? $_SESSION[$oldCode]['jurnalItems'] : array(),
                                        "componentsBuilder" => isset($_SESSION[$oldCode]['componentsBuilder']) ? $_SESSION[$oldCode]['componentsBuilder'] : array(),
                                    );
                                    // masuk ke gerbang TableInMaster, tabel transaksi
                                    $masterReplacers = array(
//                        "inv" => $tmpNomorNota,
                                        "jenis_master" => $this->jenisTr,
                                        "jenis_top" => $connecTo,
                                        "jenis" => $connecTo,
                                        "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                        "transaksi_jenis" => $connecTo,
                                        "step_avail" => 1,
                                        "step_current" => 1,
                                        "step_number" => 1,
                                        "next_step_code" => "",
                                        "next_step_label" => "",
                                        "next_group_code" => "",
                                        "next_step_num" => "0",
                                        "trash_4" => 1,
                                        "cancel_dtime" => date("Y-m-d H:i:s"),
                                        "cancel_name" => $this->session->login['nama'],
                                        "cancel_id" => $this->session->login['id'],
                                        "deskripsi" => "rejection",
                                        "oleh_id" => my_id(),
                                        "oleh_nama" => my_name()
                                    );
                                    // masuk ke gerbang main
                                    $masterReplacersO = array(
                                        "stepCode" => $connecTo,
                                        "jenisTrTop" => $connecTo,
                                        "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
//                        "inv" => $tmpNomorNota,
                                        "jenis_master" => $this->jenisTr,
                                        "jenis_top" => $connecTo,
                                        "jenis" => $connecTo,
                                        "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                        "transaksi_jenis" => $connecTo,
                                        "stepCode" => $connecTo,
                                        "jenisTrTop" => $connecTo,
                                        "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                        "step_avail" => 1,
                                        "step_current" => 1,
                                        "step_number" => 1,
                                        "next_step_code" => "",
                                        "next_step_label" => "",
                                        "next_group_code" => "",
                                        "next_step_num" => "0",
                                        "olehID" => my_id(),
                                        "olehName" => my_name()
                                    );
                                    foreach ($masterReplacersO as $key => $val) {
                                        $_SESSION[$cCode]['main'][$key] = $val;
                                    }
                                    foreach ($masterReplacers as $key => $val) {
                                        $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                                    }

                                    $tokoID = $_SESSION[$cCode]['main']['tokoID'];
                                    $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];

                                    //region penomoran receipt
                                    $this->load->model("CustomCounter");
                                    $cn = new CustomCounter("transaksi");
                                    $cn->setType("transaksi");
                                    $counterForNumber = array($this->configValues[$this->jenisTr]['formatNotaReject']);
                                    if (!in_array($counterForNumber[0], $this->configValues[$this->jenisTr]['countersReject'])) {
                                        die(__LINE__ . " Used number should be registered in 'counters' config as well");
                                    }
                                    echo "<div style='background:#ff7766;'>";
                                    foreach ($counterForNumber as $i => $cRawParams) {
                                        $cParams = explode("|", $cRawParams);
                                        $cValues = array();
                                        foreach ($cParams as $param) {
                                            $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                        }
                                        $cRawValues = implode("|", $cValues[$i]);
                                        $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                                    }
                                    echo "</div style='background:#ff7766;'>";

                                    $stepNumber = 1;
                                    $tmpNomorNota = $paramSpec['paramString'];
                                    $tmpNomorNotaAlias = formatNota("nomer_nolink", $tmpNomorNota);
                                    $nextProp = array(
                                        "num" => 0,
                                        "code" => "",
                                        "label" => "",
                                        "groupID" => "",
                                    );
                                    //endregion

                                    //region dynamic counters
                                    // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                                    $cn = new CustomCounter("transaksi");
                                    $cn->setType("transaksi");
                                    $configCustomParams = $this->configValues[$this->jenisTr]['countersReject'];
                                    arrPrintHijau($configCustomParams);
                                    $configCustomParams[] = "stepCode";
                                    //arrPrint($configCustomParams);
                                    if (sizeof($configCustomParams) > 0) {
                                        $cContent = array();
                                        foreach ($configCustomParams as $i => $cRawParams) {
                                            $cParams = explode("|", $cRawParams);
                                            $cValues = array();
                                            foreach ($cParams as $param) {
                                                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                            }
                                            $cRawValues = implode("|", $cValues[$i]);
                                            $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                                            $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                                            switch ($paramSpec['id']) {
                                                case 0: //===counter type is new
                                                    $addData = array(
                                                        "toko_id" => $tokoID,
                                                        "toko_nama" => $tokoNama,
                                                    );
                                                    $paramKeyRaw = print_r($cParams, true);
                                                    $paramValuesRaw = print_r($cValues[$i], true);
                                                    $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                                    break;
                                                default: //===counter to be updated
                                                    $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                                    break;
                                            }
                                            //echo "<hr>";
                                        }
                                    }
                                    $appliedCounters = base64_encode(serialize($cContent));
                                    $appliedCounters_inText = print_r($cContent, true);
                                    //mati_disini();
//arrPrintPink($cContent);
                                    //
                                    //region addition on master


                                    $addValues = array(
                                        'counters' => $appliedCounters,
                                        'counters_intext' => $appliedCounters_inText,
                                        'nomer' => $tmpNomorNota,
                                        'nomer2' => $tmpNomorNotaAlias,
                                        'dtime' => date("Y-m-d H:i:s"),
                                        'fulldate' => date("Y-m-d"),
                                        "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                                        "step_number" => 1,
                                        "step_current" => 1,
                                        "next_step_num" => $nextProp['num'],
                                        "next_step_code" => $nextProp['code'],
                                        "next_step_label" => $nextProp['label'],
                                        "next_group_code" => $nextProp['groupID'],
                                        "tail_number" => 1,
                                        "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


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

                                    //
                                    //region addition on detail
                                    $addSubValues = array(
                                        "sub_step_number" => 1,
                                        "sub_step_current" => 1,
                                        "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                                        "next_substep_num" => $nextProp['num'],
                                        "next_substep_code" => $nextProp['code'],
                                        "next_substep_label" => $nextProp['label'],
                                        "next_subgroup_code" => $nextProp['groupID'],
                                        "sub_tail_number" => 1,
                                        "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                                    );
                                    foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                                        foreach ($addSubValues as $key => $val) {
                                            $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                                        }
                                    }
                                    //endregion
                                    // </editor-fold>
                                    //endregion

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


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

                                    $addValues = array(
                                        'counters' => $appliedCounters,
                                        'counters_intext' => $appliedCounters_inText,
                                        'nomer' => $tmpNomorNota,
                                        'nomer2' => $tmpNomorNotaAlias,
                                        'dtime' => date("Y-m-d H:i:s"),
                                        'fulldate' => date("Y-m-d"),
                                    );
                                    foreach ($addValues as $key => $val) {
                                        $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                                    }
                                    $masterReplacers = array(
                                        "nomer" => $tmpNomorNota,
                                        "nomer2" => $tmpNomorNotaAlias,
                                        "counters" => $appliedCounters,
                                        "counters_intext" => $appliedCounters_inText,
                                    );
                                    foreach ($masterReplacers as $key => $val) {
                                        $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                                    }
                                    $detailReplacers = array(
                                        "sub_step_avail" => 1,
                                        "sub_step_current" => 1,
                                        "sub_step_number" => 1,
                                        "next_substep_num" => "",
                                        "next_substep_code" => "",
                                        "next_substep_label" => "",
                                        "next_subgroup_code" => "",
                                    );
                                    if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                                        foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                                            foreach ($dSpec as $key => $val) {
                                                $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                                            }
                                        }
                                    }
                                    $itemsReplacers = array(
                                        "next_substep_num" => "",
                                        "next_substep_code" => "",
                                        "next_substep_label" => "",
                                        "next_subgroup_code" => "",
                                    );
                                    if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                                        foreach ($_SESSION[$cCode]['items'] as $k => $dSpec) {
                                            foreach ($dSpec as $key => $val) {
                                                $_SESSION[$cCode]['items'][$k][$key] = isset($itemsReplacers[$key]) ? $itemsReplacers[$key] : $val;
                                            }
                                        }
                                    }

                                    //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
                                    if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                                        $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
                                        $_SESSION[$cCode]['tableIn_master']['trash_4'] = 1;// dibatalkan
                                        $_SESSION[$cCode]['tableIn_master']['cli'] = 1;

                                        $tr = new MdlTransaksi();
                                        $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                                        $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                                        cekHitam("[$insertID] :: " . $this->db->last_query());
                                        $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                                        $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                                        $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                                        if ($insertID < 1) {
                                            die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                                        }
                                        $mongoList['main'] = array($insertID, $epID);
                                        //==transaksi_id dan nomor nota diinject kan ke gate utama
                                        $injectors = array(
                                            "transaksi_id" => $insertID,
                                            "nomer" => $tmpNomorNota,
                                            "nomer2" => $tmpNomorNotaAlias,
                                        );
                                        $arrInjectorsTarget = array(
                                            "items",
                                            "items2_sum",
                                            "rsltItems",
                                        );
                                        foreach ($injectors as $key => $val) {
                                            $_SESSION[$cCode]['main'][$key] = $val;
                                            foreach ($arrInjectorsTarget as $target) {
                                                if (isset($_SESSION[$cCode][$target])) {
                                                    foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                                        $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                                        if (isset($_SESSION[$cCode][$target][$id])) {
                                                            $_SESSION[$cCode][$target][$id][$key] = $val;
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        //===signature
                                        $dwsign = $tr->writeSignature($insertID, array(
                                            "nomer" => $_SESSION[$cCode]['main']['nomer'],
                                            "step_number" => 1,
                                            "step_code" => $connecTo,
                                            "step_name" => $this->configUiJenis["connectToEdit"][1]["label"],
                                            "group_code" => "",
                                            "oleh_id" => $this->session->login['id'],
                                            "oleh_nama" => $this->session->login['nama'],
                                            "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                                            "transaksi_id" => $masterID,
                                            "deskripsi" => "edit transaksi",
                                            "cabang_id" => $this->session->login['cabang_id'],
                                            "cabang_nama" => $this->session->login['cabang_nama'],
                                            "current_transaksi_id" => $masterID,
                                            "current_nomer" => $_SESSION[$cCode]['main']['nomer'],
                                        )) or die("Failed to write signature");
                                        showLast_query("kuning");
                                        $mongoList['sign'][] = $dwsign;
                                        $idHis = array(
                                            $stepNumber => array(
                                                "olehID" => $_SESSION[$cCode]['main']['olehID'],
                                                "olehName" => $_SESSION[$cCode]['main']['olehName'],
                                                "step" => $stepNumber,
                                                "trID" => $insertID,
                                                "nomer" => $tmpNomorNota,
                                                "nomer2" => $tmpNomorNotaAlias,
                                                "counters" => $appliedCounters,
                                                "counters_intext" => $appliedCounters_inText,
                                            ),
                                        );
                                        $idHis_blob = blobEncode($idHis);
                                        $idHis_intext = print_r($idHis, true);
                                        $tr = new MdlTransaksi();
                                        $dupState = $tr->updateData(array("id" => $insertID), array(
                                            "next_step_num" => $nextProp['num'],
                                            "next_step_code" => $nextProp['code'],
                                            "next_step_label" => $nextProp['label'],
                                            "next_group_code" => $nextProp['groupID'],

                                            //===references
//                            "id_master" => $insertID,
                                            "id_master" => $masterID,// milik transkasiID yang diedit
                                            "id_top" => $insertID,
                                            "ids_prev" => "",
                                            "ids_prev_intext" => "",
                                            "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                            "nomers_prev" => "",
                                            "nomers_prev_intext" => "",
                                            "jenises_prev" => "",
                                            "jenises_prev_intext" => "",
                                            "ids_his" => $idHis_blob,
                                            "ids_his_intext" => $idHis_intext,

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

                                        $addValues = array(
                                            //===references
                                            "id_master" => $insertID,
                                            "id_top" => $insertID,
                                            "ids_prev" => "",
                                            "ids_prev_intext" => "",
                                            "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                            "nomers_prev" => "",
                                            "nomers_prev_intext" => "",
                                            "jenises_prev" => "",
                                            "jenises_prev_intext" => "",
                                            "ids_his" => $idHis_blob,
                                            "ids_his_intext" => $idHis_intext,
                                        );
                                        foreach ($addValues as $key => $val) {
                                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                                        }

                                    }
                                    if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                                        $inserMainValues = array();
                                        if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                                            //matiHEre("hooppp");
                                            $inserMainValues = array();
                                            foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                                                if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                                                    $dd = $tr->writeMainValues($insertID, array(
                                                        "key" => $key,
                                                        "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                                                    ));

                                                    $inserMainValues[] = $dd;
                                                    $mongoList['mainValues'][] = $dd;
                                                }
                                            }
                                        }

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

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

                                        if (sizeof($inserMainValues) > 0) {
                                            $arrBlob = blobEncode($inserMainValues);
                                            $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                                        }
                                    }
                                    if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                                        foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                                            $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                            //                    cekkuning("making a clone for input key $key / $val");
                                            //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                                            //                    $replacers=array(
                                            //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                                            //                    );
                                            //                    foreach($replacers as $key=>$val){
                                            //                        $tmpTableIn[$key]=$val;
                                            //                    }
                                            //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                                        }
                                    }
                                    if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                                        foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                                            $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                                        }
                                    }
                                    if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                                        foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                                            $tr->writeMainApplets($insertID, array(
                                                "mdl_name" => $amdl,
                                                "key" => $aSpec['key'],
                                                "label" => $aSpec['labelValue'],
                                                "description" => $aSpec['description'],
                                            ));
                                        }
                                    }
                                    if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                                        foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                                            $tr->writeMainElements($insertID, array(
                                                "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                                                "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                                                "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                                                "name" => $aSpec['name'],
                                                "label" => $aSpec['label'],
                                                "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                                                "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                                            ));
                                            //==nebeng bikin inputLabels
//                                $currentValue = "";
//                                switch ($aSpec['elementType']) {
//                                    case "dataModel":
//                                        $currentValue = $aSpec['key'];
//                                        break;
//                                    case "dataField":
//                                        $currentValue = $aSpec['value'];
//                                        break;
//                                }
//                                if (array_key_exists($elName, $relOptionConfigs)) {
//                                    //					cekhijau("$eName terdaftar pada relInputs");
//
//
//                                    if (isset($relOptionConfigs[$elName][$currentValue])) {
//                                        if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
//                                            foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
//                                                $inputLabels[$oValueName] = $oValSpec['label'];
//                                                if (isset($oValSpec['auth'])) {
//                                                    if (isset($oValSpec['auth']['groupID'])) {
//                                                        $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                    else {
//                                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
//                                    }
//
//                                }

                                        }
                                    }
                                    if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

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


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

                                            foreach ($indexing_details as $k => $arrID) {
                                                $arrBlob = blobEncode($arrID);
                                                $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                                                cekOrange($this->db->last_query());
                                            }
                                        }
                                    }
                                    else {
                                        die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                                    }
                                    if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                                        $insertIDs = array();
                                        foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                                            $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                                            $mongoList['detail'] = $insertIDs;
                                            if ($epID != 999) {
                                                $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                                $mongoList['detail'] = $insertIDs;
                                            }
                                            cekUngu($this->db->last_query());
                                        }
                                    }
                                    if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                                        $insertIDs = array();
                                        foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                                            $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                            $insertIDs[] = $insertDetailID;
                                            $mongoList['detail'][] = $insertDetailID;
                                            if ($epID != 999) {
                                                $dd = $tr->writeDetailEntries($epID, $dSpec);
                                                $insertIDs[] = $dd;
                                                $mongoList['detail'][] = $dd;
                                            }
                                        }
                                    }
                                    if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                                        $insertIDs = array();
                                        foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                                            $dd = $tr->writeDetailEntries($insertID, $dSpec);
                                            $insertIDs[] = $dd;
                                            $mongoList['detil'][] = $dd;
                                            if ($epID != 999) {
                                                $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                                $mongoList['detil'] = $insertIDs;
                                            }
                                            cekUngu($this->db->last_query());
                                        }
                                    }
                                    if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

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

                                                    }
                                                }
                                            }
                                        }

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

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

                                    $baseRegistries = array(
                                        'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                                        'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                                        'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                                        'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                                        'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                                        'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                                        'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                                        'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                                        'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                                        'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                                        'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                                        'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                                        'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                                        'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                                        'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                                        'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                                        'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                                        'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                                        'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                                        'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                                        'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                                        'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                                        'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                                        'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                                        'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                                        'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                                        'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                                        'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                                        'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                                        'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                                        'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                                        'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                                        'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                                        'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                                        "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                                        "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                                        "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                                        "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                                        "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                                        "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                                        "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                                        "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                                        "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                                        "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                                        "items_noapprove" => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),
                                        "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                                        "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                                        //----
                                        'mainOriginal' => isset($_SESSION[$cCode]['mainOriginal']) ? $_SESSION[$cCode]['mainOriginal'] : array(),
                                        'itemsOriginal' => isset($_SESSION[$cCode]['itemsOriginal']) ? $_SESSION[$cCode]['itemsOriginal'] : array(),
                                        //----
                                    );
                                    $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                                    showLast_query("hijau");
                                    cekHijau("SELESAI menjalankan EDITOR...");
                                }
                            }
                            else {
                                $tableIn_master['trash_4'] = 1;
                                $tableIn_master['cancel_id'] = $this->session->login['id'];
                                $tableIn_master['cancel_name'] = $this->session->login['nama'];
                                $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                                $tableIn_master['deskripsi'] = "rejection";
                                $epID = $tr->writeMainEntries_entryPoint($trTmp[0]->id, $tableIn_master['id_master'], $tableIn_master);
                                $mongoList['main'][] = $epID;
                                if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                                    $insertIDs = array();
                                    foreach ($tableIn_detail as $dSpec) {
                                        if ($epID != 999) {
                                            $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                            $mongoList['detail'] = $insertIDs;

                                        }
                                    }
                                }
                            }
                        }
                        cekKuning("stepNumCurrent -> $stepNumCurrent, jenisTR -> $jenisTr");
                        $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;
                        $tokoID = $_SESSION[$cCode]['main']['tokoID'];
                        $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];
                        $transaksiMode = isset($this->configUi[$this->jenisTr]["transaksiMode"]) ? $this->configUi[$this->jenisTr]["transaksiMode"] : mati_disini("Mode transaksi silahkan diseting di coTransaksiUi " . $this->jenisTr);
                        $runCoreAkunting = isset($this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["runCoreAkunting"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["runCoreAkunting"] : false;
                        $core = isset($this->config->item('heTransaksi_core')[$this->modul][$transaksiMode]) ? $this->config->item('heTransaksi_core')[$this->modul][$transaksiMode] : array();

                        //===if rollback is needed
                        //rollback preproc, master
                        if (isset($core['preProcessor'][$jenisTr_component]['master'])) {
                            $iterator = isset($core['preProcessor'][$jenisTr_component]['master']) ? $core['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($core['preProcessor'][$jenisTr_component]['detail'])) {
                            //            cekbiru("ada config pre-proc detail $stepNumCurrent");
                            $iterator = isset($core['preProcessor'][$jenisTr_component]['detail']) ? $core['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->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                            $iterator = isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master'] : array();
                            if (sizeof($iterator) > 0) {
                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'];
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    echo "rollback main post-processor: $comName [$srcGateName]<br>";

                                    $dSpec = $_SESSION[$cCode][$srcGateName];
                                    $tmpOutParams = array();
                                    if (isset($tComSpec['loop'])) {
                                        foreach ($tComSpec['loop'] as $key => $value) {
                                            //                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                            $realValue = makeValue($value, $$srcGateName, $$srcGateName, 0);
                                            $tmpOutParams['loop'][$key] = $realValue;
                                        }
                                    }
                                    if (isset($tComSpec['static'])) {
                                        //cekHere("DISINI OIII");
                                        foreach ($tComSpec['static'] as $key => $value) {
                                            //                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                                            $realValue = makeValue($value, $$srcGateName, $$srcGateName, 0);
                                            $tmpOutParams['static'][$key] = $realValue;
                                        }
                                        if (!isset($tmpOutParams['static']["transaksi_id"])) {
                                            $tmpOutParams['static']["transaksi_id"] = $insertID;
                                        }
                                        if (!isset($tmpOutParams['static']["transaksi_no"])) {
                                            $tmpOutParams['static']["transaksi_no"] = $insertNum;
                                        }

                                        $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                                        $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                                        $tmpOutParams['static']["keterangan"] = $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['label'] . " nomor " . $no . " oleh " . $this->session->login['nama'];
                                    }
                                    if (isset($tComSpec['static2'])) {
                                        //cekHere("DISINI OIII");
                                        foreach ($tComSpec['static2'] as $key => $value) {
                                            //                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                                            $realValue = makeValue($value, $$srcGateName, $$srcGateName, 0);
                                            $tmpOutParams['static2'][$key] = $realValue;
                                        }
                                        if (!isset($tmpOutParams['static2']["transaksi_id"])) {
                                            $tmpOutParams['static2']["transaksi_id"] = $insertID;
                                        }
                                        if (!isset($tmpOutParams['static2']["transaksi_no"])) {
                                            $tmpOutParams['static2']["transaksi_no"] = $insertNum;
                                        }

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


                                    if (array_key_exists($oriComName, $postConfigs)) {
                                        if (sizeof($postConfigs[$oriComName]) > 0) {
                                            foreach ($postConfigs[$oriComName] as $key) {
                                                $oldVal = isset($tmpOutParams['static'][$key]) ? $tmpOutParams['static'][$key] : 0;
                                                cekbiru("oldVal: $oldVal");
                                                $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                cekHijau("newVal: $newVal");

                                                $tmpOutParams['static'][$key] = $newVal;
                                            }
                                        }
                                    }

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

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


                                }
                            }
                            else {
                                cekHitam(":: tidak ada config postproc master yang harus rollback ::");
                            }
                        }
                        else {
                            cekbiru("TIDAK ada config post-proc master $jenisTr :: $stepNumCurrent");
                        }
                        //rollback postproc, detail

                        if (isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {
                            $iterator = isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail'] : array();
                            if (sizeof($iterator) > 0) {
                                foreach ($iterator as $cCtr => $tComSpec) {
                                    $oriComName = $tComSpec['comName'];
                                    $comName = $tComSpec['comName'];
                                    $srcGateName = $tComSpec['srcGateName'];
                                    $srcRawGateName = $tComSpec['srcRawGateName'];
                                    echo "rollback sub-postProcessor: $comName, initializing values <br>";

                                    $tmpOutParams[$cCtr] = array();
                                    foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                                        $subParams = array();
                                        if (isset($tComSpec['loop'])) {
                                            foreach ($tComSpec['loop'] as $key => $value) {
                                                $gateItems = $$srcGateName;
                                                //                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                                $realValue = makeValue($value, $gateItems[$cnt], $gateItems[$cnt], 0);
                                                $subParams['loop'][$key] = $realValue;
                                            }
                                        }
                                        if (isset($tComSpec['static'])) {
                                            foreach ($tComSpec['static'] as $key => $value) {
                                                $gateItems = $$srcGateName;
                                                //                                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                                                $realValue = makeValue($value, $gateItems[$cnt], $gateItems[$cnt], 0);
                                                $subParams['static'][$key] = $realValue;
                                            }

                                            if (array_key_exists($oriComName, $postConfigs)) {
                                                if (sizeof($postConfigs[$oriComName]) > 0) {
                                                    foreach ($postConfigs[$oriComName] as $key) {
                                                        $oldVal = isset($subParams['static'][$key]) ? $subParams['static'][$key] : 0;
                                                        cekbiru("oldVal2: $oldVal");
                                                        $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                        cekHijau("newVal2: $newVal");
                                                        $subParams['static'][$key] = $newVal;
                                                    }
                                                }
                                            }
                                            else {
                                                //                                cekhitam("TIDAK terdapat di dalam prepConfig");
                                            }

                                            //                            $subParams['static']["transaksi_id"] = $insertID;
                                            if (!isset($subParams['static']["transaksi_id"])) {
                                                $subParams['static']["transaksi_id"] = $no;
                                            }
                                            if (!isset($subParams['static']["transaksi_no"])) {
                                                $subParams['static']["transaksi_no"] = $no;
                                            }
                                            $subParams['static']["fulldate"] = date("Y-m-d");
                                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                            $subParams['static']["keterangan"] = "rollback of $no";
                                        }


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

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

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


                                    cekBiru("kiriman rollback detail-postproc $comName");
                                    arrPrint($tmpOutParams[$cCtr]);
                                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                    $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                }
                            }
                            else {
                                cekHitam(":: tidak ada config postproc detail yang harus rollback ::");
                            }
                        }
                        else {
                            cekbiru("TIDAK ada config post-proc detail $jenisTr :: $stepNumCurrent");
                        }


                        //region transaksi stanby di pihak tujuan...
                        $nextMasterStep = $stepNumCurrent_son;
                        $childTargetStepNum = $childTargetStepNum_con;
                        $jenisTr = $jenisTr_con;
                        $nextProp = array(
                            "num" => $nextMasterStep,
                            "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                            "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                            "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
                        );

                        //region swap from registry, transaksi yang dibuka saat ini
                        $tr = new MdlTransaksi();
                        $tmpReg = $tr->lookupDataRegistriesByMasterID($no)->result();
                        cekmerah($this->db->last_query());
                        if (sizeof($tmpReg) > 0) {
                            foreach ($tmpReg as $row) {
                                foreach ($row as $key_reg => $val_reg) {
                                    if ($key_reg != "transaksi_id") {
                                        $var = $key_reg;
                                        $$var = unserialize(base64_decode($val_reg));
                                    }
                                }
                            }
                        }
                        //endregion

                        //region swap from main transaksi, transaksi yang dibuka saat ini
                        $tr = new MdlTransaksi();
                        $tr->setFilters(array());
                        $tr->addFilter("id='$no'");
                        $tmpTr = $tr->lookupMainTransaksi()->result();
                        cekOrange($this->db->last_query());
                        //endregion

                        //region transaksi yang stanby di pihak ke-2
                        $tb = new MdlTransaksi();
                        $tb->setFilters(array());
                        $dupState = $tb->updateData(array(
                            "id" => $no,
                        ), array(
                            "status_4" => "11",
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],

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

                        $mongListUpadte['update']['main'][] = array(
                            "where" => array(
                                "id" => $no,
                            ),
                            "value" => array(
                                "status_4" => "11",
                                "trash_4" => "1",
                                "cancel_dtime" => date("Y-m-d H:i:s"),
                                "cancel_name" => $this->session->login['nama'],
                                "cancel_id" => $this->session->login['id'],
                            ),
                        );
                        cekHitam("UPDATE transaksi yang stanby di pihak ke-2");
                        cekHitam($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                        $to = new MdlTransaksi();
                        $to->setFilters(array());
                        $to->setTableName($to->getTableNames()['detail']);
                        $dupState = $to->updateData(array(
                            "transaksi_id" => $no,
                        ), array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        )) or die("Failed to update tr next-state!");
                        $mongListUpadte['update']['main'][] = array(
                            "where" => array(
                                "transaksi_id" => $no,
                            ),
                            "value" => array(
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "next_substep_num" => $nextProp['num'],
                                //            "sub_step_current" => 0,
                                "sub_step_number" => 0,
                            ),
                        );
                        cekHitam("UPDATE transaksi data yang stanby di pihak ke-2");
                        cekHitam($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        //endregion

                        //region sesuaikan signature untuk cloningan, ikut minus
                        //        $dwsign = $tr->writeSignature($no, array(
                        $dwsign = $tr->writeSignature($no, array(
                            "prev_id" => $no,
                            "nomer" => "rejection",
                            "step_number" => $childTargetStepNum, // ini minus step number
                            "step_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['target'],
                            "step_name" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'],
                            "group_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['userGroup'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "keterangan" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                            //            "transaksi_id" => $no,
                        )) or die("Failed to write signature");
                        $mongoList['sign'][] = $dwsign;
                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        //endregion

                        //==entry point
                        if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                            $tableIn_master['trash_4'] = 1;
                            $tableIn_master['cancel_id'] = $this->session->login['id'];
                            $tableIn_master['cancel_name'] = $this->session->login['nama'];
                            $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                            $tableIn_master['deskripsi'] = "rejection";
                            $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                            $mongoList['main'][] = $epID;

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

                        //endregion

                    }
                    else {
                        cekMerah(":: CONNECTING, SATU INSTANSI (PUSAT DOANG / CABANG DOANG)::");
                        cekHitam(":: jenisTR > $jenisTr, jenis_master > $jenisTr, id_master > " . $tmpTr[0]->id_master . " ::");
                        //                    mati_disini(":: transaksi gagal karena transaksi yang dimaksud tidak valid.");


                        //region :: update ID-nya sendiri...

                        //region update step2an di masternya
                        $nextMasterStep = $stepNumCurrent;
                        $nextProp = array(
                            "num" => $nextMasterStep,
                            "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                            "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                            "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
                        );
                        echo "nextMasterStep: $nextMasterStep<br>";
                        arrPrint($nextProp);
                        cekKuning($masterTargetStepNum);
                        //update masternya, transaksi TOP
                        if ($tmpTr[0]->id_top != $no) {
                            $arrData = array(
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],
                                "next_step_num" => $nextProp['num'],
                                "step_current" => $masterTargetStepNum,
                                "step_number" => $masterTargetStepNum,
                            );
                            $arrData_detail = array(
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "next_substep_num" => $nextProp['num'],
                                "sub_step_current" => $masterTargetStepNum,
                                "sub_step_number" => $masterTargetStepNum,
                                //                "valid_qty" => $new_valid_qty,
                            );
                        }
                        else {
                            $arrData = array(
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],
                                "next_step_num" => $nextProp['num'],
                                "step_current" => $masterTargetStepNum,
                                "step_number" => $masterTargetStepNum,
                                //                        "step_number" => $childTargetStepNum,
                                "trash_4" => "1",
                            );
                            $arrData_detail = array(
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "next_substep_num" => $nextProp['num'],
                                //            "sub_step_current" => 0,
                                "sub_step_number" => 0,
                            );
                        }
                        $tr = new MdlTransaksi();
                        $dupState = $tr->updateData(array(
                            //                "id" => $no,
                            "id" => $tmpTr[0]->id_top,
                        ), $arrData) or die("Failed to update tr next-state!");
                        $mongListUpadte['update']['main'][] = array(
                            "where" => array("id" => $tmpTr[0]->id_top),
                            "value" => $arrData,
                        );
                        cekHijau("UPDATE transaksi step sebelumnya...");
                        cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        //endregion

                        //region update step transaksi 1 step sebelumnya (detail)
                        if (sizeof($tmpTr) > 0) {
                            $arrPrevID = $tmpTr[0]->ids_prev != null ? blobDecode($tmpTr[0]->ids_prev) : array($tmpTr[0]->id_top);
                            arrPrint($arrPrevID);
                            foreach ($arrPrevID as $prevID) {
                                $tb = new MdlTransaksi();
                                $tb->setFilters(array());
                                $dupState = $tb->updateData(array(
                                    "id" => $prevID,
                                ), array(
                                    "status_4" => "11",
                                )) or die("Failed to update tr next-state!");
                                $mongListUpadte['update']['main'][] = array(
                                    "where" => array("id" => $prevID),
                                    "value" => $arrData,
                                );
                                cekKuning("UPDATE transaksi 1 step sebelumnya...");
                                cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");


                                $td = new MdlTransaksi();
                                $td->setFilters(array());
                                $rslt = $td->lookupJoinedByID($prevID)->result();
                                if (sizeof($rslt) > 0) {
                                    foreach ($rslt as $rsltSpec) {
                                        if (array_key_exists($rsltSpec->produk_id, $items)) {
                                            $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                            //                            cekHitam(":: $prevID :: $rsltSpec->valid_qty :: " . $items[$rsltSpec->produk_id]['qty'] . " :: $new_valid_qty ::");

                                            if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                                $new_valid_qty = $rsltSpec->valid_qty;
                                                //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                            }
                                            else {
                                                $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                            }
                                            //                            cekHitam("ROLLBACK... :: valid_qty-> " . $rsltSpec->valid_qty . " :: kembali-> " . $items[$rsltSpec->produk_id]['qty'] . " :: " . $new_valid_qty);

                                            $arrData_detail["valid_qty"] = $new_valid_qty;
                                            $tr = new MdlTransaksi();
                                            $tr->setFilters(array());
                                            $tr->setTableName($tr->getTableNames()['detail']);
                                            $dupState = $tr->updateData(array(
                                                "transaksi_id" => $prevID,
                                                "produk_id" => $rsltSpec->produk_id,
                                            ), $arrData_detail) or die("Failed to update tr next-state!");
                                            $mongListUpadte['update']['detail'][] = array(
                                                "where" => array(
                                                    "transaksi_id" => $prevID,
                                                    "produk_id" => $rsltSpec->produk_id,
                                                ),
                                                "value" => $arrData_detail,
                                            );
                                            cekKuning("UPDATE transaksi data...");
                                            cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                                        }
                                    }
                                }

                            }
                        }
                        //endregion

                        //region update step yang sebelumnya aktif, transaksi yang dibuka sekarang
                        // cekUngu($tmpTr[0]->id_top);
                        // cekUngu("$no");
                        // if ($tmpTr[0]->id_top != $no) {
                        $tp = new MdlTransaksi();
                        $dupState = $tp->updateData(array(
                            "id" => $no,
                            "step_number" => $stepNumCurrent,
                        ), array(
                            "step_number" => $masterTargetStepNum,
                            //                    "step_number" => $childTargetStepNum,
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],

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

                        $mongListUpadte['update']['main'][] = array(
                            "where" => array(
                                "id" => $no,
                                "step_number" => $stepNumCurrent,
                            ),
                            "value" => array(
                                "step_number" => $masterTargetStepNum,
                                //                    "step_number" => $childTargetStepNum,
                                "trash_4" => "1",
                                "cancel_dtime" => date("Y-m-d H:i:s"),
                                "cancel_name" => $this->session->login['nama'],
                                "cancel_id" => $this->session->login['id'],
                            ),
                        );
                        cekLime("UPDATE transaksi ini... yang dibuka sekarang...");
                        cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                        $to = new MdlTransaksi();
                        $to->setFilters(array());
                        $to->setTableName($to->getTableNames()['detail']);
                        $dupState = $to->updateData(array(
                            "transaksi_id" => $no,
                        ), array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        )) or die("Failed to update tr next-state!");
                        $mongListUpadte['update']['main'][] = array(
                            "where" => array(
                                "transaksi_id" => $no,
                            ),
                            "value" => array(
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "next_substep_num" => $nextProp['num'],
                                //            "sub_step_current" => 0,
                                "sub_step_number" => 0,
                            ),
                        );
                        cekLime("UPDATE transaksi data...");
                        cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        // }
                        //endregion

                        //region sesuaikan signature untuk cloningan, ikut minus
                        //        $dwsign = $tr->writeSignature($no, array(
                        $dwsign = $tr->writeSignature($tmpTr[0]->id_top, array(
                            "prev_id" => $no,
                            "nomer" => "rejection",
                            "step_number" => $childTargetStepNum, // ini minus step number
                            "step_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['target'],
                            "step_name" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'],
                            "group_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['userGroup'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "keterangan" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                            //            "transaksi_id" => $no,
                        )) or die("Failed to write signature");
                        $mongoList['sign'][] = $dwsign;
                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                        //endregion

                        // region netralisasi payment source
                        $tr = New MdlTransaksi();
                        $tr->setFilters(array());
                        $tr->addFilter("sisa>0");
                        $paymentSrc = $tr->lookupPaymentSrcByTransID($no)->result();
                        cekBiru($this->db->last_query());
                        if (sizeof($paymentSrc) > 0) {
                            //            arrPrint($paymentSrc);
                            foreach ($paymentSrc as $pSpec) {
                                if ($pSpec->terbayar == 0) {
                                    $where = array(
                                        "id" => $pSpec->id,
                                        "transaksi_id" => $pSpec->transaksi_id,
                                    );
                                    $data = array(
                                        "sisa" => 0,
                                        "returned" => $pSpec->sisa,
                                        "sisa_valas" => 0,
                                        "returned_valas" => $pSpec->sisa_valas,
                                    );

                                    $tra = New MdlTransaksi();
                                    $tra->setFilters(array());
                                    $tra->updatePaymentSrc($where, $data);
                                    cekUngu(":: mereject payment source bila ada...");
                                    cekUngu($this->db->last_query());
                                }
                                else {
                                    mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                                }
                            }
                        }
                        else {
                            cekBiru(":: tidak ada payment source... ::");
                        }
                        // endregion netralisasi payment source

                        // region netralisasi extended step
                        $tr = New MdlTransaksi();
                        $tr->setFilters(array());
                        $exTmp = $tr->lookupExtStepByTrID($no);
                        if (sizeof($exTmp) > 0) {
                            foreach ($exTmp as $exSpec) {

                                $tra = New MdlTransaksi();
                                $tra->setFilters(array());
                                $tra->rejectExtStepByID($exSpec['id']);
                                $mongListUpadte['update']['extra'][] = array(
                                    "where" => array(
                                        "id" => $valID,
                                    ),
                                    "value" => array(
                                        "state" => "-1",
                                    ),
                                );
                                cekUngu(":: mereject extended step bila ada...");
                                cekUngu($this->db->last_query());
                            }
                        }
                        else {
                            cekBiru(":: tidak ada extended step... ::");
                        }

                        // endregion netralisasi extended step


                        //region entry point
                        if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                            $tableIn_master['trash_4'] = 1;
                            $tableIn_master['cancel_id'] = $this->session->login['id'];
                            $tableIn_master['cancel_name'] = $this->session->login['nama'];
                            $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                            $tableIn_master['deskripsi'] = "rejection";
                            $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                            $mongoList['main'][] = $epID;
                            //                        cekHitam($this->db->last_query());
                            if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                                $insertIDs = array();
                                foreach ($tableIn_detail as $dSpec) {
                                    if ($epID != 999) {
                                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                        $mongoList['detil'] = $insertIDs;
                                        //                                    cekHitam($this->db->last_query());
                                    }
                                }
                            }
                        }
                        //endregion

                        $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;
                        $tokoID = $_SESSION[$cCode]['main']['tokoID'];
                        $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];
                        $transaksiMode = isset($this->configUi[$this->jenisTr]["transaksiMode"]) ? $this->configUi[$this->jenisTr]["transaksiMode"] : mati_disini("Mode transaksi silahkan diseting di coTransaksiUi " . $this->jenisTr);
                        $runCoreAkunting = isset($this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["runCoreAkunting"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["runCoreAkunting"] : false;
                        $core = isset($this->config->item('heTransaksi_core')[$this->modul][$transaksiMode]) ? $this->config->item('heTransaksi_core')[$this->modul][$transaksiMode] : array();

                        //===if rollback is needed
                        //rollback preproc, master
                        if (isset($core['preProcessor'][$jenisTr_component]['master'])) {
                            //            cekbiru("ada config pre-proc master $stepNumCurrent");
                            $iterator = isset($core['preProcessor'][$jenisTr_component]['master']) ? $core['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($core['preProcessor'][$jenisTr_component]['detail'])) {
                            //            cekbiru("ada config pre-proc detail $stepNumCurrent");
                            $iterator = isset($core['preProcessor'][$jenisTr_component]['detail']) ? $core['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->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                            //            cekbiru("ada config pre-proc master $stepNumCurrent");
                            $iterator = isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configValues[$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->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {

                            $iterator = isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configValues[$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

//                    mati_disini("=== masuk sini ===");
                }
                else {
                    // hanya mundur 1 langkah di pihak target
//mati_disini(__LINE__);
                    //region update step2an di masternya
                    $nextMasterStep = $stepNumCurrent;
                    $nextProp = array(
                        "num" => $nextMasterStep,
                        "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                        "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                        "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
                    );
                    echo "nextMasterStep: $nextMasterStep<br>";
//                    arrPrint($nextProp);
//                    cekKuning($masterTargetStepNum);
                    //update masternya, transaksi TOP
                    if ($tmpTr[0]->id_top != $no) {
                        $arrData = array(
                            "next_step_code" => $nextProp['code'],
                            "next_step_label" => $nextProp['label'],
                            "next_group_code" => $nextProp['groupID'],
                            "next_step_num" => $nextProp['num'],
                            "step_current" => $masterTargetStepNum,
                            "step_number" => $masterTargetStepNum,
                        );
                        $arrData_detail = array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            "sub_step_current" => $masterTargetStepNum,
                            "sub_step_number" => $masterTargetStepNum,
                            //                "valid_qty" => $new_valid_qty,
                        );
                    }
                    else {
                        $arrData = array(
                            "next_step_code" => $nextProp['code'],
                            "next_step_label" => $nextProp['label'],
                            "next_group_code" => $nextProp['groupID'],
                            "next_step_num" => $nextProp['num'],
                            "step_current" => $masterTargetStepNum,
                            "step_number" => $masterTargetStepNum,
                            //                        "step_number" => $childTargetStepNum,
                            "trash_4" => "1",
                            "cancel_dtime" => dtime("Y-m-d H:i:s"),
                            "cancel_id" => $this->session->login['id'],
                            "cancel_name" => $this->session->login['nama'],
                        );
                        $arrData_detail = array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        );
                    }
                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array(
                        //                "id" => $no,
                        "id" => $tmpTr[0]->id_top,
                    ), $arrData) or die("Failed to update tr next-state!");
                    $mongListUpadte['update']['main'][] = array(
                        "where" => array(
                            "id" => $tmpTr[0]->id_top
                        ),
                        "value" => $arrData,
                    );
                    cekHijau("UPDATE transaksi step sebelumnya...");
                    cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                    //endregion

                    //region update step transaksi 1 step sebelumnya (detail)
                    if (sizeof($tmpTr) > 0) {
                        $arrPrevID = $tmpTr[0]->ids_prev != null ? blobDecode($tmpTr[0]->ids_prev) : array($tmpTr[0]->id_top);
//                        arrPrint($arrPrevID);
                        foreach ($arrPrevID as $prevID) {
                            $tb = new MdlTransaksi();
                            $tb->setFilters(array());
                            $dupState = $tb->updateData(array(
                                "id" => $prevID,
                            ), array(
                                "status_4" => "11",
                            )) or die("Failed to update tr next-state!");
                            $mongListUpadte['update']['main'][] = array(
                                "where" => array(
                                    "id" => $prevID
                                ),
                                "value" => array(
                                    "status_4" => "11",
                                ),
                            );
                            cekKuning("UPDATE transaksi 1 step sebelumnya...");
                            cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                            $td = new MdlTransaksi();
                            $td->setFilters(array());
                            $rslt = $td->lookupJoinedByID($prevID)->result();
                            if (sizeof($rslt) > 0) {
                                foreach ($rslt as $rsltSpec) {
                                    if (array_key_exists($rsltSpec->produk_id, $items)) {
                                        $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                        //                            cekHitam(":: $prevID :: $rsltSpec->valid_qty :: " . $items[$rsltSpec->produk_id]['qty'] . " :: $new_valid_qty ::");

                                        if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                            $new_valid_qty = $rsltSpec->valid_qty;
                                            //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                        }
                                        else {
                                            $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                        }
                                        //                            cekHitam("ROLLBACK... :: valid_qty-> " . $rsltSpec->valid_qty . " :: kembali-> " . $items[$rsltSpec->produk_id]['qty'] . " :: " . $new_valid_qty);

                                        $arrData_detail["valid_qty"] = $new_valid_qty;
                                        $tr = new MdlTransaksi();
                                        $tr->setFilters(array());
                                        $tr->setTableName($tr->getTableNames()['detail']);
                                        $dupState = $tr->updateData(array(
                                            "transaksi_id" => $prevID,
                                            "produk_id" => $rsltSpec->produk_id,
                                        ), $arrData_detail) or die("Failed to update tr next-state!");
                                        $mongListUpadte['update']['detail'][] = array(
                                            "where" => array(
                                                "transaksi_id" => $prevID,
                                                "produk_id" => $rsltSpec->produk_id,
                                            ),
                                            "value" => $arrData_detail,
                                        );
                                        cekKuning("UPDATE transaksi data...");
                                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                                    }
                                }
                            }

                        }
                    }
                    //endregion

                    //region update step yang sebelumnya aktif, transaksi yang dibuka sekarang
                    $tp = new MdlTransaksi();
                    $dupState = $tp->updateData(array(
                        "id" => $no,
                        "step_number" => $stepNumCurrent,
                    ), array(
                        "step_number" => $masterTargetStepNum,
                        //                    "step_number" => $childTargetStepNum,
                        "trash_4" => "1",
                        "cancel_dtime" => date("Y-m-d H:i:s"),
                        "cancel_name" => $this->session->login['nama'],
                        "cancel_id" => $this->session->login['id'],

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

                    $mongListUpadte['update']['main'][] = array(
                        "where" => array(
                            "id" => $no,
                            "step_number" => $stepNumCurrent,
                        ),
                        "value" => array(
                            "step_number" => $masterTargetStepNum,
                            //                    "step_number" => $childTargetStepNum,
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],
                        ),
                    );
                    cekLime("UPDATE transaksi ini... yang dibuka sekarang...");
                    cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
//arrPrintWebs($mongListUpadte);
                    $to = new MdlTransaksi();
                    $to->setFilters(array());
                    $to->setTableName($to->getTableNames()['detail']);
                    $dupState = $to->updateData(array(
                        "transaksi_id" => $no,
                    ), array(
                        "next_substep_code" => $nextProp['code'],
                        "next_substep_label" => $nextProp['label'],
                        "next_subgroup_code" => $nextProp['groupID'],
                        "next_substep_num" => $nextProp['num'],
                        //            "sub_step_current" => 0,
                        "sub_step_number" => 0,
                    )) or die("Failed to update tr next-state!");
                    $mongListUpadte['update']['detail'][] = array(
                        "where" => array(
                            "transaksi_id" => $no, "id" => $no,
                        ),
                        "value" => array(
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "next_substep_num" => $nextProp['num'],
                            //            "sub_step_current" => 0,
                            "sub_step_number" => 0,
                        ),
                    );
                    cekLime("UPDATE transaksi data...");
                    cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    //endregion

                    //region sesuaikan signature untuk cloningan, ikut minus
                    //        $dwsign = $tr->writeSignature($no, array(
                    $dwsign = $tr->writeSignature($tmpTr[0]->id_top, array(
                        "prev_id" => $no,
                        "nomer" => "rejection",
                        "step_number" => $childTargetStepNum, // ini minus step number
                        "step_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['target'],
                        "step_name" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'],
                        "group_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['userGroup'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "keterangan" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                        //            "transaksi_id" => $no,
                    )) or die("Failed to write signature");
                    $mongoList['sign'][] = $dwsign;
                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                    //endregion

                    // region netralisasi payment source
                    $tr = New MdlTransaksi();
                    $tr->setFilters(array());
                    $tr->addFilter("sisa>0");
                    $paymentSrc = $tr->lookupPaymentSrcByTransID($no)->result();
                    cekBiru($this->db->last_query());
                    if (sizeof($paymentSrc) > 0) {
                        //            arrPrint($paymentSrc);
                        foreach ($paymentSrc as $pSpec) {
                            if ($pSpec->terbayar == 0) {
                                $where = array(
                                    "id" => $pSpec->id,
                                    "transaksi_id" => $pSpec->transaksi_id,
                                );
                                $data = array(
                                    "sisa" => 0,
                                    "returned" => $pSpec->sisa,
                                    "sisa_valas" => 0,
                                    "returned_valas" => $pSpec->sisa_valas,
                                );

                                $tra = New MdlTransaksi();
                                $tra->setFilters(array());
                                $tra->updatePaymentSrc($where, $data);
                                cekUngu(":: mereject payment source bila ada...");
                                cekUngu($this->db->last_query());
                            }
                            else {
                                mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                            }
                        }
                    }
                    else {
                        cekBiru(":: tidak ada payment source... ::");
                    }
                    // endregion netralisasi payment source

                    // region netralisasi extended step
                    $tr = New MdlTransaksi();
                    $tr->setFilters(array());
                    $exTmp = $tr->lookupExtStepByTrID($no);
                    if (sizeof($exTmp) > 0) {
                        foreach ($exTmp as $exSpec) {

                            $tra = New MdlTransaksi();
                            $tra->setFilters(array());
                            $tra->rejectExtStepByID($exSpec['id']);
                            $mongListUpadte['update']['extra'][] = array(
                                "where" => array(
                                    "id" => $exSpec['id'],
                                ),
                                "value" => array(
                                    "state" => "-1",
                                ),
                            );
                            cekUngu(":: mereject extended step bila ada...");
                            cekUngu($this->db->last_query());
                        }
                    }
                    else {
                        cekBiru(":: tidak ada extended step... ::");
                    }

                    // endregion netralisasi extended step

                    //==entry point
                    if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                        if (isset($this->configUiJenis["connectToReject"][$stepNumCurrent])) {
                            if ($this->configUiJenis["connectToReject"][$stepNumCurrent]["enabled"] == true) {
                                $masterID = $currentMasterID;
                                $connecTo = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                                cekHijau("START menjalankan REJECT... [$masterID] [$connecTo]");
                                if ($connecTo == NULL) {
                                    mati_disini("kode edit transaksi tidak dikenali. segera hubungi admin.");
                                }
                                $oldCode = $cCode;
                                $cCode = "_TR_" . $connecTo;
                                $_SESSION[$cCode] = array(
                                    'main' => isset($_SESSION[$oldCode]['main']) ? $_SESSION[$oldCode]['main'] : array(),
                                    'items' => isset($_SESSION[$oldCode]['items']) ? $_SESSION[$oldCode]['items'] : array(),
                                    'items2' => isset($_SESSION[$oldCode]['items2']) ? $_SESSION[$oldCode]['items2'] : array(),
                                    'items2_sum' => isset($_SESSION[$oldCode]['items2_sum']) ? $_SESSION[$oldCode]['items2_sum'] : array(),
                                    'itemSrc' => isset($_SESSION[$oldCode]['itemSrc']) ? $_SESSION[$oldCode]['itemSrc'] : array(),
                                    'itemSrc_sum' => isset($_SESSION[$oldCode]['itemSrc_sum']) ? $_SESSION[$oldCode]['itemSrc_sum'] : array(),
                                    'items3' => isset($_SESSION[$oldCode]['items3']) ? $_SESSION[$oldCode]['items3'] : array(),
                                    'items3_sum' => isset($_SESSION[$oldCode]['items3_sum']) ? $_SESSION[$oldCode]['items3_sum'] : array(),
                                    'items4' => isset($_SESSION[$oldCode]['items4']) ? $_SESSION[$oldCode]['items4'] : array(),
                                    'items4_sum' => isset($_SESSION[$oldCode]['items4_sum']) ? $_SESSION[$oldCode]['items4_sum'] : array(),
                                    'items5_sum' => isset($_SESSION[$oldCode]['items5_sum']) ? $_SESSION[$oldCode]['items5_sum'] : array(),
                                    'items6_sum' => isset($_SESSION[$oldCode]['items6_sum']) ? $_SESSION[$oldCode]['items6_sum'] : array(),
                                    'items7_sum' => isset($_SESSION[$oldCode]['items7_sum']) ? $_SESSION[$oldCode]['items7_sum'] : array(),
                                    'items8_sum' => isset($_SESSION[$oldCode]['items8_sum']) ? $_SESSION[$oldCode]['items8_sum'] : array(),
                                    'items9_sum' => isset($_SESSION[$oldCode]['items9_sum']) ? $_SESSION[$oldCode]['items9_sum'] : array(),
                                    'items10_sum' => isset($_SESSION[$oldCode]['items10_sum']) ? $_SESSION[$oldCode]['items10_sum'] : array(),
                                    'rsltItems' => isset($_SESSION[$oldCode]['rsltItems']) ? $_SESSION[$oldCode]['rsltItems'] : array(),
                                    'rsltItems2' => isset($_SESSION[$oldCode]['rsltItems2']) ? $_SESSION[$oldCode]['rsltItems2'] : array(),
                                    'rsltItems3' => isset($_SESSION[$oldCode]['rsltItems3']) ? $_SESSION[$oldCode]['rsltItems3'] : array(),
                                    'tableIn_master' => isset($_SESSION[$oldCode]['tableIn_master']) ? $_SESSION[$oldCode]['tableIn_master'] : array(),
                                    'tableIn_detail' => isset($_SESSION[$oldCode]['tableIn_detail']) ? $_SESSION[$oldCode]['tableIn_detail'] : array(),
                                    'tableIn_detail2_sum' => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                                    'tableIn_detail_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems'] : array(),
                                    'tableIn_detail_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems2'] : array(),
                                    'tableIn_master_values' => isset($_SESSION[$oldCode]['tableIn_master_values']) ? $_SESSION[$oldCode]['tableIn_master_values'] : array(),
                                    'tableIn_detail_values' => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                                    'tableIn_detail_values_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                                    'tableIn_detail_values_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems2'] : array(),
                                    'tableIn_detail_values2_sum' => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                                    'main_add_values' => isset($_SESSION[$oldCode]['main_add_values']) ? $_SESSION[$oldCode]['main_add_values'] : array(),
                                    'main_add_fields' => isset($_SESSION[$oldCode]['main_add_fields']) ? $_SESSION[$oldCode]['main_add_fields'] : array(),
                                    'main_elements' => isset($_SESSION[$oldCode]['main_elements']) ? $_SESSION[$oldCode]['main_elements'] : array(),
                                    'main_inputs' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                                    'main_inputs_orig' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                                    "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                                    "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                                    "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                                    "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                                    "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                                    "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                                    "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                                    "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                                    "revert" => isset($_SESSION[$oldCode]['revert']) ? $_SESSION[$oldCode]['revert'] : array(),
                                    "items_komposisi" => isset($_SESSION[$oldCode]['items_komposisi']) ? $_SESSION[$oldCode]['items_komposisi'] : array(),
                                    "items_noapprove" => isset($_SESSION[$oldCode]['items_noapprove']) ? $_SESSION[$oldCode]['items_noapprove'] : array(),
                                    "jurnalItems" => isset($_SESSION[$oldCode]['jurnalItems']) ? $_SESSION[$oldCode]['jurnalItems'] : array(),
                                    "componentsBuilder" => isset($_SESSION[$oldCode]['componentsBuilder']) ? $_SESSION[$oldCode]['componentsBuilder'] : array(),
                                );
                                // masuk ke gerbang TableInMaster, tabel transaksi
                                $masterReplacers = array(
//                        "inv" => $tmpNomorNota,
                                    "jenis_master" => $this->jenisTr,
                                    "jenis_top" => $connecTo,
                                    "jenis" => $connecTo,
                                    "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                    "transaksi_jenis" => $connecTo,
                                    "step_avail" => 1,
                                    "step_current" => 1,
                                    "step_number" => 1,
                                    "next_step_code" => "",
                                    "next_step_label" => "",
                                    "next_group_code" => "",
                                    "next_step_num" => "0",
                                    "trash_4" => 1,
                                    "cancel_dtime" => date("Y-m-d H:i:s"),
                                    "cancel_name" => $this->session->login['nama'],
                                    "cancel_id" => $this->session->login['id'],
                                    "deskripsi" => "rejection",
                                    "oleh_id" => my_id(),
                                    "oleh_nama" => my_name()
                                );
                                // masuk ke gerbang main
                                $masterReplacersO = array(
                                    "stepCode" => $connecTo,
                                    "jenisTrTop" => $connecTo,
                                    "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
//                        "inv" => $tmpNomorNota,
                                    "jenis_master" => $this->jenisTr,
                                    "jenis_top" => $connecTo,
                                    "jenis" => $connecTo,
                                    "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                    "transaksi_jenis" => $connecTo,
                                    "stepCode" => $connecTo,
                                    "jenisTrTop" => $connecTo,
                                    "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                    "step_avail" => 1,
                                    "step_current" => 1,
                                    "step_number" => 1,
                                    "next_step_code" => "",
                                    "next_step_label" => "",
                                    "next_group_code" => "",
                                    "next_step_num" => "0",
                                    "olehID" => my_id(),
                                    "olehName" => my_name()
                                );
                                foreach ($masterReplacersO as $key => $val) {
                                    $_SESSION[$cCode]['main'][$key] = $val;
                                }
                                foreach ($masterReplacers as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                                }

                                $tokoID = $_SESSION[$cCode]['main']['tokoID'];
                                $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];

                                //region penomoran receipt
                                $this->load->model("CustomCounter");
                                $cn = new CustomCounter("transaksi");
                                $cn->setType("transaksi");
                                $counterForNumber = array($this->configValues[$this->jenisTr]['formatNotaReject']);
                                if (!in_array($counterForNumber[0], $this->configValues[$this->jenisTr]['countersReject'])) {
                                    die(__LINE__ . " Used number should be registered in 'counters' config as well");
                                }
                                echo "<div style='background:#ff7766;'>";
                                foreach ($counterForNumber as $i => $cRawParams) {
                                    $cParams = explode("|", $cRawParams);
                                    $cValues = array();
                                    foreach ($cParams as $param) {
                                        $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                    }
                                    $cRawValues = implode("|", $cValues[$i]);
                                    $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                                }
                                echo "</div style='background:#ff7766;'>";

                                $stepNumber = 1;
                                $tmpNomorNota = $paramSpec['paramString'];
                                $tmpNomorNotaAlias = formatNota("nomer_nolink", $tmpNomorNota);
                                $nextProp = array(
                                    "num" => 0,
                                    "code" => "",
                                    "label" => "",
                                    "groupID" => "",
                                );
                                //endregion

                                //region dynamic counters
                                // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                                $cn = new CustomCounter("transaksi");
                                $cn->setType("transaksi");
                                $configCustomParams = $this->configValues[$this->jenisTr]['countersReject'];
                                arrPrintHijau($configCustomParams);
                                $configCustomParams[] = "stepCode";
                                //arrPrint($configCustomParams);
                                if (sizeof($configCustomParams) > 0) {
                                    $cContent = array();
                                    foreach ($configCustomParams as $i => $cRawParams) {
                                        $cParams = explode("|", $cRawParams);
                                        $cValues = array();
                                        foreach ($cParams as $param) {
                                            $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                        }
                                        $cRawValues = implode("|", $cValues[$i]);
                                        $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                                        $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                                        switch ($paramSpec['id']) {
                                            case 0: //===counter type is new
                                                $addData = array(
                                                    "toko_id" => $tokoID,
                                                    "toko_nama" => $tokoNama,
                                                );
                                                $paramKeyRaw = print_r($cParams, true);
                                                $paramValuesRaw = print_r($cValues[$i], true);
                                                $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                                break;
                                            default: //===counter to be updated
                                                $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                                break;
                                        }
                                        //echo "<hr>";
                                    }
                                }
                                $appliedCounters = base64_encode(serialize($cContent));
                                $appliedCounters_inText = print_r($cContent, true);
                                //mati_disini();
//arrPrintPink($cContent);
                                //
                                //region addition on master


                                $addValues = array(
                                    'counters' => $appliedCounters,
                                    'counters_intext' => $appliedCounters_inText,
                                    'nomer' => $tmpNomorNota,
                                    'nomer2' => $tmpNomorNotaAlias,
                                    'dtime' => date("Y-m-d H:i:s"),
                                    'fulldate' => date("Y-m-d"),
                                    "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                                    "step_number" => 1,
                                    "step_current" => 1,
                                    "next_step_num" => $nextProp['num'],
                                    "next_step_code" => $nextProp['code'],
                                    "next_step_label" => $nextProp['label'],
                                    "next_group_code" => $nextProp['groupID'],
                                    "tail_number" => 1,
                                    "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


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

                                //
                                //region addition on detail
                                $addSubValues = array(
                                    "sub_step_number" => 1,
                                    "sub_step_current" => 1,
                                    "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                                    "next_substep_num" => $nextProp['num'],
                                    "next_substep_code" => $nextProp['code'],
                                    "next_substep_label" => $nextProp['label'],
                                    "next_subgroup_code" => $nextProp['groupID'],
                                    "sub_tail_number" => 1,
                                    "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                                );
                                foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                                    foreach ($addSubValues as $key => $val) {
                                        $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                                    }
                                }
                                //endregion
                                // </editor-fold>
                                //endregion

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


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

                                $addValues = array(
                                    'counters' => $appliedCounters,
                                    'counters_intext' => $appliedCounters_inText,
                                    'nomer' => $tmpNomorNota,
                                    'nomer2' => $tmpNomorNotaAlias,
                                    'dtime' => date("Y-m-d H:i:s"),
                                    'fulldate' => date("Y-m-d"),
                                );
                                foreach ($addValues as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                                }
                                $masterReplacers = array(
                                    "nomer" => $tmpNomorNota,
                                    "nomer2" => $tmpNomorNotaAlias,
                                    "counters" => $appliedCounters,
                                    "counters_intext" => $appliedCounters_inText,
                                );
                                foreach ($masterReplacers as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                                }
                                $detailReplacers = array(
                                    "sub_step_avail" => 1,
                                    "sub_step_current" => 1,
                                    "sub_step_number" => 1,
                                    "next_substep_num" => "",
                                    "next_substep_code" => "",
                                    "next_substep_label" => "",
                                    "next_subgroup_code" => "",
                                );
                                if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                                    foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                                        foreach ($dSpec as $key => $val) {
                                            $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                                        }
                                    }
                                }
                                $itemsReplacers = array(
                                    "next_substep_num" => "",
                                    "next_substep_code" => "",
                                    "next_substep_label" => "",
                                    "next_subgroup_code" => "",
                                );
                                if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                                    foreach ($_SESSION[$cCode]['items'] as $k => $dSpec) {
                                        foreach ($dSpec as $key => $val) {
                                            $_SESSION[$cCode]['items'][$k][$key] = isset($itemsReplacers[$key]) ? $itemsReplacers[$key] : $val;
                                        }
                                    }
                                }

                                //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
                                if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                                    $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
                                    $_SESSION[$cCode]['tableIn_master']['trash_4'] = 1;// dibatalkan
                                    $_SESSION[$cCode]['tableIn_master']['cli'] = 1;

                                    $tr = new MdlTransaksi();
                                    $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                                    $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                                    cekHitam("[$insertID] :: " . $this->db->last_query());
                                    $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                                    $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                                    $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                                    if ($insertID < 1) {
                                        die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                                    }
                                    $mongoList['main'] = array($insertID, $epID);
                                    //==transaksi_id dan nomor nota diinject kan ke gate utama
                                    $injectors = array(
                                        "transaksi_id" => $insertID,
                                        "nomer" => $tmpNomorNota,
                                        "nomer2" => $tmpNomorNotaAlias,
                                    );
                                    $arrInjectorsTarget = array(
                                        "items",
                                        "items2_sum",
                                        "rsltItems",
                                    );
                                    foreach ($injectors as $key => $val) {
                                        $_SESSION[$cCode]['main'][$key] = $val;
                                        foreach ($arrInjectorsTarget as $target) {
                                            if (isset($_SESSION[$cCode][$target])) {
                                                foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                                    $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                                    if (isset($_SESSION[$cCode][$target][$id])) {
                                                        $_SESSION[$cCode][$target][$id][$key] = $val;
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    //===signature
                                    $dwsign = $tr->writeSignature($insertID, array(
                                        "nomer" => $_SESSION[$cCode]['main']['nomer'],
                                        "step_number" => 1,
                                        "step_code" => $connecTo,
                                        "step_name" => $this->configUiJenis["connectToEdit"][1]["label"],
                                        "group_code" => "",
                                        "oleh_id" => $this->session->login['id'],
                                        "oleh_nama" => $this->session->login['nama'],
                                        "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                                        "transaksi_id" => $masterID,
                                        "deskripsi" => "edit transaksi",
                                        "cabang_id" => $this->session->login['cabang_id'],
                                        "cabang_nama" => $this->session->login['cabang_nama'],
                                        "current_transaksi_id" => $masterID,
                                        "current_nomer" => $_SESSION[$cCode]['main']['nomer'],
                                    )) or die("Failed to write signature");
                                    showLast_query("kuning");
                                    $mongoList['sign'][] = $dwsign;
                                    $idHis = array(
                                        $stepNumber => array(
                                            "olehID" => $_SESSION[$cCode]['main']['olehID'],
                                            "olehName" => $_SESSION[$cCode]['main']['olehName'],
                                            "step" => $stepNumber,
                                            "trID" => $insertID,
                                            "nomer" => $tmpNomorNota,
                                            "nomer2" => $tmpNomorNotaAlias,
                                            "counters" => $appliedCounters,
                                            "counters_intext" => $appliedCounters_inText,
                                        ),
                                    );
                                    $idHis_blob = blobEncode($idHis);
                                    $idHis_intext = print_r($idHis, true);
                                    $tr = new MdlTransaksi();
                                    $dupState = $tr->updateData(array("id" => $insertID), array(
                                        "next_step_num" => $nextProp['num'],
                                        "next_step_code" => $nextProp['code'],
                                        "next_step_label" => $nextProp['label'],
                                        "next_group_code" => $nextProp['groupID'],

                                        //===references
//                            "id_master" => $insertID,
                                        "id_master" => $masterID,// milik transkasiID yang diedit
                                        "id_top" => $insertID,
                                        "ids_prev" => "",
                                        "ids_prev_intext" => "",
                                        "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                        "nomers_prev" => "",
                                        "nomers_prev_intext" => "",
                                        "jenises_prev" => "",
                                        "jenises_prev_intext" => "",
                                        "ids_his" => $idHis_blob,
                                        "ids_his_intext" => $idHis_intext,

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

                                    $addValues = array(
                                        //===references
                                        "id_master" => $insertID,
                                        "id_top" => $insertID,
                                        "ids_prev" => "",
                                        "ids_prev_intext" => "",
                                        "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                        "nomers_prev" => "",
                                        "nomers_prev_intext" => "",
                                        "jenises_prev" => "",
                                        "jenises_prev_intext" => "",
                                        "ids_his" => $idHis_blob,
                                        "ids_his_intext" => $idHis_intext,
                                    );
                                    foreach ($addValues as $key => $val) {
                                        $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                                    }

                                }
                                if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                                    $inserMainValues = array();
                                    if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                                        //matiHEre("hooppp");
                                        $inserMainValues = array();
                                        foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                                            if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                                                $dd = $tr->writeMainValues($insertID, array(
                                                    "key" => $key,
                                                    "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                                                ));

                                                $inserMainValues[] = $dd;
                                                $mongoList['mainValues'][] = $dd;
                                            }
                                        }
                                    }

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

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

                                    if (sizeof($inserMainValues) > 0) {
                                        $arrBlob = blobEncode($inserMainValues);
                                        $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                                    }
                                }
                                if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                                    foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                                        $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                        //                    cekkuning("making a clone for input key $key / $val");
                                        //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                                        //                    $replacers=array(
                                        //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                                        //                    );
                                        //                    foreach($replacers as $key=>$val){
                                        //                        $tmpTableIn[$key]=$val;
                                        //                    }
                                        //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                                    }
                                }
                                if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                                    foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                                        $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                                    }
                                }
                                if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                                    foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                                        $tr->writeMainApplets($insertID, array(
                                            "mdl_name" => $amdl,
                                            "key" => $aSpec['key'],
                                            "label" => $aSpec['labelValue'],
                                            "description" => $aSpec['description'],
                                        ));
                                    }
                                }
                                if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                                    foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                                        $tr->writeMainElements($insertID, array(
                                            "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                                            "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                                            "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                                            "name" => $aSpec['name'],
                                            "label" => $aSpec['label'],
                                            "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                                            "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                                        ));
                                        //==nebeng bikin inputLabels
//                                $currentValue = "";
//                                switch ($aSpec['elementType']) {
//                                    case "dataModel":
//                                        $currentValue = $aSpec['key'];
//                                        break;
//                                    case "dataField":
//                                        $currentValue = $aSpec['value'];
//                                        break;
//                                }
//                                if (array_key_exists($elName, $relOptionConfigs)) {
//                                    //					cekhijau("$eName terdaftar pada relInputs");
//
//
//                                    if (isset($relOptionConfigs[$elName][$currentValue])) {
//                                        if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
//                                            foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
//                                                $inputLabels[$oValueName] = $oValSpec['label'];
//                                                if (isset($oValSpec['auth'])) {
//                                                    if (isset($oValSpec['auth']['groupID'])) {
//                                                        $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                    else {
//                                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
//                                    }
//
//                                }

                                    }
                                }
                                if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

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


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

                                        foreach ($indexing_details as $k => $arrID) {
                                            $arrBlob = blobEncode($arrID);
                                            $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                                            cekOrange($this->db->last_query());
                                        }
                                    }
                                }
                                else {
                                    die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                                }
                                if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                                    $insertIDs = array();
                                    foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                                        $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                                        $mongoList['detail'] = $insertIDs;
                                        if ($epID != 999) {
                                            $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                            $mongoList['detail'] = $insertIDs;
                                        }
                                        cekUngu($this->db->last_query());
                                    }
                                }
                                if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                                    $insertIDs = array();
                                    foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                                        $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                        $insertIDs[] = $insertDetailID;
                                        $mongoList['detail'][] = $insertDetailID;
                                        if ($epID != 999) {
                                            $dd = $tr->writeDetailEntries($epID, $dSpec);
                                            $insertIDs[] = $dd;
                                            $mongoList['detail'][] = $dd;
                                        }
                                    }
                                }
                                if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                                    $insertIDs = array();
                                    foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                                        $dd = $tr->writeDetailEntries($insertID, $dSpec);
                                        $insertIDs[] = $dd;
                                        $mongoList['detil'][] = $dd;
                                        if ($epID != 999) {
                                            $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                            $mongoList['detil'] = $insertIDs;
                                        }
                                        cekUngu($this->db->last_query());
                                    }
                                }
                                if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

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

                                                }
                                            }
                                        }
                                    }

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

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

                                $baseRegistries = array(
                                    'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                                    'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                                    'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                                    'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                                    'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                                    'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                                    'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                                    'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                                    'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                                    'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                                    'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                                    'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                                    'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                                    'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                                    'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                                    'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                                    'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                                    'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                                    'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                                    'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                                    'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                                    'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                                    'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                                    'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                                    'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                                    'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                                    'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                                    'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                                    'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                                    'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                                    'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                                    'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                                    'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                                    'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                                    "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                                    "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                                    "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                                    "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                                    "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                                    "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                                    "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                                    "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                                    "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                                    "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                                    "items_noapprove" => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),
                                    "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                                    "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                                    //----
                                    'mainOriginal' => isset($_SESSION[$cCode]['mainOriginal']) ? $_SESSION[$cCode]['mainOriginal'] : array(),
                                    'itemsOriginal' => isset($_SESSION[$cCode]['itemsOriginal']) ? $_SESSION[$cCode]['itemsOriginal'] : array(),
                                    //----
                                );
                                $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                                showLast_query("hijau");
                                cekHijau("SELESAI menjalankan EDITOR...");
                            }
                        }
                        else {
                            $tableIn_master['trash_4'] = 1;
                            $tableIn_master['cancel_id'] = $this->session->login['id'];
                            $tableIn_master['cancel_name'] = $this->session->login['nama'];
                            $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                            $tableIn_master['deskripsi'] = "rejection";
                            $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                            $mongoList['main'][] = $epID;

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

                    $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;
                    $tokoID = $_SESSION[$cCode]['main']['tokoID'];
                    $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];
                    $transaksiMode = isset($this->configUi[$this->jenisTr]["transaksiMode"]) ? $this->configUi[$this->jenisTr]["transaksiMode"] : mati_disini("Mode transaksi silahkan diseting di coTransaksiUi " . $this->jenisTr);
                    $runCoreAkunting = isset($this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["runCoreAkunting"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["runCoreAkunting"] : false;
                    $core = isset($this->config->item('heTransaksi_core')[$this->modul][$transaksiMode]) ? $this->config->item('heTransaksi_core')[$this->modul][$transaksiMode] : array();

                    //===if rollback is needed
                    //rollback preproc, master
                    if (isset($core['preProcessor'][$jenisTr_component]['master'])) {
                        //            cekbiru("ada config pre-proc master $stepNumCurrent");
                        $iterator = isset($core[$jenisTr]['preProcessor'][$jenisTr_component]['master']) ? $core[$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($core[$jenisTr]['preProcessor'][$jenisTr_component]['detail'])) {
                        //            cekbiru("ada config pre-proc detail $stepNumCurrent");
                        $iterator = isset($core[$jenisTr]['preProcessor'][$jenisTr_component]['detail']) ? $core[$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->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                        //            cekbiru("ada config pre-proc master $stepNumCurrent");
                        $iterator = isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configValues[$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->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {

                        $iterator = isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configValues[$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");
                    }
//mati_disini(__LINE__);
                }

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

                //region update step2an di masternya
                $nextMasterStep = $stepNumCurrent;
                $nextProp = array(
                    "num" => $nextMasterStep,
                    "code" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['target']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['target'] : "",
                    "label" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['label']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['label'] : "",
                    "groupID" => isset($this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup']) ? $this->configUi[$jenisTr]['steps'][$nextMasterStep]['userGroup'] : "",
                );
                echo "nextMasterStep: $nextMasterStep<br>";
                arrPrint($nextProp);
                cekKuning($masterTargetStepNum);
                //update masternya, transaksi TOP
                if ($tmpTr[0]->id_top != $no) {
                    $arrData = array(
                        "next_step_code" => $nextProp['code'],
                        "next_step_label" => $nextProp['label'],
                        "next_group_code" => $nextProp['groupID'],
                        "next_step_num" => $nextProp['num'],
                        "step_current" => $masterTargetStepNum,
                        "step_number" => $masterTargetStepNum,
                    );
                    $arrData_detail = array(
                        "next_substep_code" => $nextProp['code'],
                        "next_substep_label" => $nextProp['label'],
                        "next_subgroup_code" => $nextProp['groupID'],
                        "next_substep_num" => $nextProp['num'],
                        "sub_step_current" => $masterTargetStepNum,
                        "sub_step_number" => $masterTargetStepNum,
                        //                "valid_qty" => $new_valid_qty,
                    );
                }
                else {
                    $arrData = array(
                        "next_step_code" => $nextProp['code'],
                        "next_step_label" => $nextProp['label'],
                        "next_group_code" => $nextProp['groupID'],
                        "next_step_num" => $nextProp['num'],
                        "step_current" => $masterTargetStepNum,
                        "step_number" => $masterTargetStepNum,
                        //                        "step_number" => $childTargetStepNum,
                        "trash_4" => "1",
                        "cancel_id" => $this->session->login['id'],
                        "cancel_name" => $this->session->login['nama'],
                        "cancel_dtime" => date("Y-m-d H:i:s"),

                    );
                    $arrData_detail = array(
                        "next_substep_code" => $nextProp['code'],
                        "next_substep_label" => $nextProp['label'],
                        "next_subgroup_code" => $nextProp['groupID'],
                        "next_substep_num" => $nextProp['num'],
                        //            "sub_step_current" => 0,
                        "sub_step_number" => 0,
                    );
                }
                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array(
                    //                "id" => $no,
                    "id" => $tmpTr[0]->id_top,
                ), $arrData) or die("Failed to update tr next-state!");
                $mongListUpadte['update']['main'][] = array(
                    "where" => array(
                        "id" => $tmpTr[0]->id_top
                    ),
                    "value" => $arrData,
                );
                cekHijau("UPDATE transaksi step sebelumnya...");
                cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                //endregion

                //region update step transaksi 1 step sebelumnya (detail)
                if (sizeof($tmpTr) > 0) {
                    $arrPrevID = $tmpTr[0]->ids_prev != null ? blobDecode($tmpTr[0]->ids_prev) : array($tmpTr[0]->id_top);
                    arrPrint($arrPrevID);
                    foreach ($arrPrevID as $prevID) {
                        $tb = new MdlTransaksi();
                        $tb->setFilters(array());
                        $dupState = $tb->updateData(array(
                            "id" => $prevID,
                        ), array(
                            "status_4" => "11",
                        )) or die("Failed to update tr next-state!");
                        $mongListUpadte['update']['main'][] = array(
                            "where" => array(
                                "id" => $prevID
                            ),
                            "value" => array(
                                "status_4" => "11",
                            ),
                        );
                        cekKuning("UPDATE transaksi 1 step sebelumnya...");
                        cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");


                        $td = new MdlTransaksi();
                        $td->setFilters(array());
                        $rslt = $td->lookupJoinedByID($prevID)->result();
                        if (sizeof($rslt) > 0) {
                            foreach ($rslt as $rsltSpec) {
                                if (array_key_exists($rsltSpec->produk_id, $items)) {
                                    $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                    //                            cekHitam(":: $prevID :: $rsltSpec->valid_qty :: " . $items[$rsltSpec->produk_id]['qty'] . " :: $new_valid_qty ::");

                                    if ($new_valid_qty > $rsltSpec->produk_ord_jml) {
                                        $new_valid_qty = $rsltSpec->valid_qty;
                                        //                                mati_disini("undo/reject/delete gagal karena valid_qty melebihi produk_ord_jml");
                                    }
                                    else {
                                        $new_valid_qty = $rsltSpec->valid_qty + $items[$rsltSpec->produk_id]['qty'];
                                    }
                                    //                            cekHitam("ROLLBACK... :: valid_qty-> " . $rsltSpec->valid_qty . " :: kembali-> " . $items[$rsltSpec->produk_id]['qty'] . " :: " . $new_valid_qty);

                                    $arrData_detail["valid_qty"] = $new_valid_qty;
                                    $tr = new MdlTransaksi();
                                    $tr->setFilters(array());
                                    $tr->setTableName($tr->getTableNames()['detail']);
                                    $dupState = $tr->updateData(array(
                                        "transaksi_id" => $prevID,
                                        "produk_id" => $rsltSpec->produk_id,
                                    ), $arrData_detail) or die("Failed to update tr next-state!");
                                    $mongListUpadte['update']['detail'][] = array(
                                        "where" => array(
                                            "transaksi_id" => $prevID,
                                            "produk_id" => $rsltSpec->produk_id,
                                        ),
                                        "value" => $arrData_detail,
                                    );
                                    cekKuning("UPDATE transaksi data...");
                                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                                }
                            }
                        }

                    }
                }
                //endregion

                //region update step yang sebelumnya aktif, transaksi yang dibuka sekarang
                $tp = new MdlTransaksi();
                $dupState = $tp->updateData(array(
                    "id" => $no,
                    "step_number" => $stepNumCurrent,
                ), array(
                    "step_number" => $masterTargetStepNum,
                    //                    "step_number" => $childTargetStepNum,
                    "trash_4" => "1",
                    "cancel_dtime" => date("Y-m-d H:i:s"),
                    "cancel_name" => $this->session->login['nama'],
                    "cancel_id" => $this->session->login['id'],

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

                $mongListUpadte['update']['main'][] = array(
                    "where" => array(
                        "id" => $no,
                        "step_number" => $stepNumCurrent,
                    ),
                    "value" => array(
                        "step_number" => $masterTargetStepNum,
                        //                    "step_number" => $childTargetStepNum,
                        "trash_4" => "1",
                        "cancel_dtime" => date("Y-m-d H:i:s"),
                        "cancel_name" => $this->session->login['nama'],
                        "cancel_id" => $this->session->login['id'],
                    ),
                );
                cekLime("UPDATE transaksi ini... yang dibuka sekarang...");
                cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                $to = new MdlTransaksi();
                $to->setFilters(array());
                $to->setTableName($to->getTableNames()['detail']);
                $dupState = $to->updateData(array(
                    "transaksi_id" => $no,
                ), array(
                    "next_substep_code" => $nextProp['code'],
                    "next_substep_label" => $nextProp['label'],
                    "next_subgroup_code" => $nextProp['groupID'],
                    "next_substep_num" => $nextProp['num'],
                    //            "sub_step_current" => 0,
                    "sub_step_number" => 0,
                )) or die("Failed to update tr next-state!");
                $mongListUpadte['update']['detail'][] = array(
                    "where" => array(
                        "transaksi_id" => $no, "id" => $no,
                    ),
                    "value" => array(
                        "next_substep_code" => $nextProp['code'],
                        "next_substep_label" => $nextProp['label'],
                        "next_subgroup_code" => $nextProp['groupID'],
                        "next_substep_num" => $nextProp['num'],
                        //            "sub_step_current" => 0,
                        "sub_step_number" => 0,
                    ),
                );
                cekLime("UPDATE transaksi data...");
                cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                //endregion

                //region sesuaikan signature untuk cloningan, ikut minus
                //        $dwsign = $tr->writeSignature($no, array(
                $dwsign = $tr->writeSignature($tmpTr[0]->id_top, array(
                    "prev_id" => $no,
                    "nomer" => "rejection",
                    "step_number" => $childTargetStepNum, // ini minus step number
                    "step_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['target'],
                    "step_name" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'],
                    "group_code" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['userGroup'],
                    "oleh_id" => $this->session->login['id'],
                    "oleh_nama" => $this->session->login['nama'],
                    "keterangan" => $this->configUi[$jenisTr]['steps'][abs($childTargetStepNum)]['label'] . " oleh " . $this->session->login['nama'],
                    //            "transaksi_id" => $no,
                )) or die("Failed to write signature");
                $mongoList['sign'][] = $dwsign;
                cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                //endregion

                // region netralisasi payment source
                $tr = New MdlTransaksi();
                $tr->setFilters(array());
                $tr->addFilter("sisa>0");
                $paymentSrc = $tr->lookupPaymentSrcByTransID($no)->result();
                cekBiru($this->db->last_query());
                if (sizeof($paymentSrc) > 0) {
                    //            arrPrint($paymentSrc);
                    foreach ($paymentSrc as $pSpec) {
                        if ($pSpec->terbayar == 0) {
                            $where = array(
                                "id" => $pSpec->id,
                                "transaksi_id" => $pSpec->transaksi_id,
                            );
                            $data = array(
                                "sisa" => 0,
                                "returned" => $pSpec->sisa,
                                "sisa_valas" => 0,
                                "returned_valas" => $pSpec->sisa_valas,
                            );

                            $tra = New MdlTransaksi();
                            $tra->setFilters(array());
                            $tra->updatePaymentSrc($where, $data);
                            cekUngu(":: mereject payment source bila ada...");
                            cekUngu($this->db->last_query());
                        }
                        else {
                            mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                        }
                    }
                }
                else {
                    cekBiru(":: tidak ada payment source... ::");
                }
                // endregion netralisasi payment source

                // region netralisasi extended step
                $tr = New MdlTransaksi();
                $tr->setFilters(array());
                $exTmp = $tr->lookupExtStepByTrID($no);
                if (sizeof($exTmp) > 0) {
                    foreach ($exTmp as $exSpec) {

                        $tra = New MdlTransaksi();
                        $tra->setFilters(array());
                        $tra->rejectExtStepByID($exSpec['id']);
                        $mongListUpadte['update']['extra'][] = array(
                            "where" => array(
                                "id" => $exSpec['id'],
                            ),
                            "value" => array(
                                "state" => "-1",
                            ),
                        );
                        cekUngu(":: mereject extended step bila ada...");
                        cekUngu($this->db->last_query());
                    }
                }
                else {
                    cekBiru(":: tidak ada extended step... ::");
                }

                // endregion netralisasi extended step

                //==entry point
                if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                    if (isset($this->configUiJenis["connectToReject"][$stepNumCurrent])) {
                        if ($this->configUiJenis["connectToReject"][$stepNumCurrent]["enabled"] == true) {
                            $masterID = $currentMasterID;
                            $connecTo = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                            cekHijau("START menjalankan REJECT... [$masterID] [$connecTo]");
                            if ($connecTo == NULL) {
                                mati_disini("kode edit transaksi tidak dikenali. segera hubungi admin.");
                            }
                            $oldCode = $cCode;
                            $cCode = "_TR_" . $connecTo;
                            $_SESSION[$cCode] = array(
                                'main' => isset($_SESSION[$oldCode]['main']) ? $_SESSION[$oldCode]['main'] : array(),
                                'items' => isset($_SESSION[$oldCode]['items']) ? $_SESSION[$oldCode]['items'] : array(),
                                'items2' => isset($_SESSION[$oldCode]['items2']) ? $_SESSION[$oldCode]['items2'] : array(),
                                'items2_sum' => isset($_SESSION[$oldCode]['items2_sum']) ? $_SESSION[$oldCode]['items2_sum'] : array(),
                                'itemSrc' => isset($_SESSION[$oldCode]['itemSrc']) ? $_SESSION[$oldCode]['itemSrc'] : array(),
                                'itemSrc_sum' => isset($_SESSION[$oldCode]['itemSrc_sum']) ? $_SESSION[$oldCode]['itemSrc_sum'] : array(),
                                'items3' => isset($_SESSION[$oldCode]['items3']) ? $_SESSION[$oldCode]['items3'] : array(),
                                'items3_sum' => isset($_SESSION[$oldCode]['items3_sum']) ? $_SESSION[$oldCode]['items3_sum'] : array(),
                                'items4' => isset($_SESSION[$oldCode]['items4']) ? $_SESSION[$oldCode]['items4'] : array(),
                                'items4_sum' => isset($_SESSION[$oldCode]['items4_sum']) ? $_SESSION[$oldCode]['items4_sum'] : array(),
                                'items5_sum' => isset($_SESSION[$oldCode]['items5_sum']) ? $_SESSION[$oldCode]['items5_sum'] : array(),
                                'items6_sum' => isset($_SESSION[$oldCode]['items6_sum']) ? $_SESSION[$oldCode]['items6_sum'] : array(),
                                'items7_sum' => isset($_SESSION[$oldCode]['items7_sum']) ? $_SESSION[$oldCode]['items7_sum'] : array(),
                                'items8_sum' => isset($_SESSION[$oldCode]['items8_sum']) ? $_SESSION[$oldCode]['items8_sum'] : array(),
                                'items9_sum' => isset($_SESSION[$oldCode]['items9_sum']) ? $_SESSION[$oldCode]['items9_sum'] : array(),
                                'items10_sum' => isset($_SESSION[$oldCode]['items10_sum']) ? $_SESSION[$oldCode]['items10_sum'] : array(),
                                'rsltItems' => isset($_SESSION[$oldCode]['rsltItems']) ? $_SESSION[$oldCode]['rsltItems'] : array(),
                                'rsltItems2' => isset($_SESSION[$oldCode]['rsltItems2']) ? $_SESSION[$oldCode]['rsltItems2'] : array(),
                                'rsltItems3' => isset($_SESSION[$oldCode]['rsltItems3']) ? $_SESSION[$oldCode]['rsltItems3'] : array(),
                                'tableIn_master' => isset($_SESSION[$oldCode]['tableIn_master']) ? $_SESSION[$oldCode]['tableIn_master'] : array(),
                                'tableIn_detail' => isset($_SESSION[$oldCode]['tableIn_detail']) ? $_SESSION[$oldCode]['tableIn_detail'] : array(),
                                'tableIn_detail2_sum' => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                                'tableIn_detail_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems'] : array(),
                                'tableIn_detail_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems2'] : array(),
                                'tableIn_master_values' => isset($_SESSION[$oldCode]['tableIn_master_values']) ? $_SESSION[$oldCode]['tableIn_master_values'] : array(),
                                'tableIn_detail_values' => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                                'tableIn_detail_values_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                                'tableIn_detail_values_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems2'] : array(),
                                'tableIn_detail_values2_sum' => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                                'main_add_values' => isset($_SESSION[$oldCode]['main_add_values']) ? $_SESSION[$oldCode]['main_add_values'] : array(),
                                'main_add_fields' => isset($_SESSION[$oldCode]['main_add_fields']) ? $_SESSION[$oldCode]['main_add_fields'] : array(),
                                'main_elements' => isset($_SESSION[$oldCode]['main_elements']) ? $_SESSION[$oldCode]['main_elements'] : array(),
                                'main_inputs' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                                'main_inputs_orig' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                                "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                                "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                                "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                                "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                                "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                                "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                                "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                                "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                                "revert" => isset($_SESSION[$oldCode]['revert']) ? $_SESSION[$oldCode]['revert'] : array(),
                                "items_komposisi" => isset($_SESSION[$oldCode]['items_komposisi']) ? $_SESSION[$oldCode]['items_komposisi'] : array(),
                                "items_noapprove" => isset($_SESSION[$oldCode]['items_noapprove']) ? $_SESSION[$oldCode]['items_noapprove'] : array(),
                                "jurnalItems" => isset($_SESSION[$oldCode]['jurnalItems']) ? $_SESSION[$oldCode]['jurnalItems'] : array(),
                                "componentsBuilder" => isset($_SESSION[$oldCode]['componentsBuilder']) ? $_SESSION[$oldCode]['componentsBuilder'] : array(),
                            );
                            // masuk ke gerbang TableInMaster, tabel transaksi
                            $masterReplacers = array(
//                        "inv" => $tmpNomorNota,
                                "jenis_master" => $this->jenisTr,
                                "jenis_top" => $connecTo,
                                "jenis" => $connecTo,
                                "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                "transaksi_jenis" => $connecTo,
                                "step_avail" => 1,
                                "step_current" => 1,
                                "step_number" => 1,
                                "next_step_code" => "",
                                "next_step_label" => "",
                                "next_group_code" => "",
                                "next_step_num" => "0",
                                "trash_4" => 1,
                                "cancel_dtime" => date("Y-m-d H:i:s"),
                                "cancel_name" => $this->session->login['nama'],
                                "cancel_id" => $this->session->login['id'],
                                "deskripsi" => "rejection",
                                "oleh_id" => my_id(),
                                "oleh_nama" => my_name()
                            );
                            // masuk ke gerbang main
                            $masterReplacersO = array(
                                "stepCode" => $connecTo,
                                "jenisTrTop" => $connecTo,
                                "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
//                        "inv" => $tmpNomorNota,
                                "jenis_master" => $this->jenisTr,
                                "jenis_top" => $connecTo,
                                "jenis" => $connecTo,
                                "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                "transaksi_jenis" => $connecTo,
                                "stepCode" => $connecTo,
                                "jenisTrTop" => $connecTo,
                                "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                                "step_avail" => 1,
                                "step_current" => 1,
                                "step_number" => 1,
                                "next_step_code" => "",
                                "next_step_label" => "",
                                "next_group_code" => "",
                                "next_step_num" => "0",
                                "olehID" => my_id(),
                                "olehName" => my_name()
                            );
                            foreach ($masterReplacersO as $key => $val) {
                                $_SESSION[$cCode]['main'][$key] = $val;
                            }
                            foreach ($masterReplacers as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }

                            $tokoID = $_SESSION[$cCode]['main']['tokoID'];
                            $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];

                            //region penomoran receipt
                            $this->load->model("CustomCounter");
                            $cn = new CustomCounter("transaksi");
                            $cn->setType("transaksi");
                            $counterForNumber = array($this->configValues[$this->jenisTr]['formatNotaReject']);
                            if (!in_array($counterForNumber[0], $this->configValues[$this->jenisTr]['countersReject'])) {
                                die(__LINE__ . " Used number should be registered in 'counters' config as well");
                            }
                            echo "<div style='background:#ff7766;'>";
                            foreach ($counterForNumber as $i => $cRawParams) {
                                $cParams = explode("|", $cRawParams);
                                $cValues = array();
                                foreach ($cParams as $param) {
                                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                }
                                $cRawValues = implode("|", $cValues[$i]);
                                $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                            }
                            echo "</div style='background:#ff7766;'>";

                            $stepNumber = 1;
                            $tmpNomorNota = $paramSpec['paramString'];
                            $tmpNomorNotaAlias = formatNota("nomer_nolink", $tmpNomorNota);
                            $nextProp = array(
                                "num" => 0,
                                "code" => "",
                                "label" => "",
                                "groupID" => "",
                            );
                            //endregion

                            //region dynamic counters
                            // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                            $cn = new CustomCounter("transaksi");
                            $cn->setType("transaksi");
                            $configCustomParams = $this->configValues[$this->jenisTr]['countersReject'];
//                            arrPrintHijau($configCustomParams);
                            $configCustomParams[] = "stepCode";
                            //arrPrint($configCustomParams);
                            if (sizeof($configCustomParams) > 0) {
                                $cContent = array();
                                foreach ($configCustomParams as $i => $cRawParams) {
                                    $cParams = explode("|", $cRawParams);
                                    $cValues = array();
                                    foreach ($cParams as $param) {
                                        $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                    }
                                    $cRawValues = implode("|", $cValues[$i]);
                                    $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                                    $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                                    switch ($paramSpec['id']) {
                                        case 0: //===counter type is new
                                            $addData = array(
                                                "toko_id" => $tokoID,
                                                "toko_nama" => $tokoNama,
                                            );
                                            $paramKeyRaw = print_r($cParams, true);
                                            $paramValuesRaw = print_r($cValues[$i], true);
                                            $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                            break;
                                        default: //===counter to be updated
                                            $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                            break;
                                    }
                                    //echo "<hr>";
                                }
                            }
                            $appliedCounters = base64_encode(serialize($cContent));
                            $appliedCounters_inText = print_r($cContent, true);
                            //mati_disini();

                            //
                            //region addition on master


                            $addValues = array(
                                'counters' => $appliedCounters,
                                'counters_intext' => $appliedCounters_inText,
                                'nomer' => $tmpNomorNota,
                                'nomer2' => $tmpNomorNotaAlias,
                                'dtime' => date("Y-m-d H:i:s"),
                                'fulldate' => date("Y-m-d"),
                                "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                                "step_number" => 1,
                                "step_current" => 1,
                                "next_step_num" => $nextProp['num'],
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],
                                "tail_number" => 1,
                                "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


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

                            //
                            //region addition on detail
                            $addSubValues = array(
                                "sub_step_number" => 1,
                                "sub_step_current" => 1,
                                "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                                "next_substep_num" => $nextProp['num'],
                                "next_substep_code" => $nextProp['code'],
                                "next_substep_label" => $nextProp['label'],
                                "next_subgroup_code" => $nextProp['groupID'],
                                "sub_tail_number" => 1,
                                "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                            );
                            foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                                foreach ($addSubValues as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                                }
                            }
                            //endregion
                            // </editor-fold>
                            //endregion

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


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

                            $addValues = array(
                                'counters' => $appliedCounters,
                                'counters_intext' => $appliedCounters_inText,
                                'nomer' => $tmpNomorNota,
                                'nomer2' => $tmpNomorNotaAlias,
                                'dtime' => date("Y-m-d H:i:s"),
                                'fulldate' => date("Y-m-d"),
                            );
                            foreach ($addValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }
                            $masterReplacers = array(
                                "nomer" => $tmpNomorNota,
                                "nomer2" => $tmpNomorNotaAlias,
                                "counters" => $appliedCounters,
                                "counters_intext" => $appliedCounters_inText,
                            );
                            foreach ($masterReplacers as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }
                            $detailReplacers = array(
                                "sub_step_avail" => 1,
                                "sub_step_current" => 1,
                                "sub_step_number" => 1,
                                "next_substep_num" => "",
                                "next_substep_code" => "",
                                "next_substep_label" => "",
                                "next_subgroup_code" => "",
                            );
                            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                                foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                                    foreach ($dSpec as $key => $val) {
                                        $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                                    }
                                }
                            }
                            $itemsReplacers = array(
                                "next_substep_num" => "",
                                "next_substep_code" => "",
                                "next_substep_label" => "",
                                "next_subgroup_code" => "",
                            );
                            if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                                foreach ($_SESSION[$cCode]['items'] as $k => $dSpec) {
                                    foreach ($dSpec as $key => $val) {
                                        $_SESSION[$cCode]['items'][$k][$key] = isset($itemsReplacers[$key]) ? $itemsReplacers[$key] : $val;
                                    }
                                }
                            }

                            //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
                            if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                                $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
                                $_SESSION[$cCode]['tableIn_master']['trash_4'] = 1;// dibatalkan
                                $_SESSION[$cCode]['tableIn_master']['cli'] = 1;

                                $tr = new MdlTransaksi();
                                $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                                $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                                cekHitam("[$insertID] :: " . $this->db->last_query());
                                $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                                $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                                $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                                if ($insertID < 1) {
                                    die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                                }
                                $mongoList['main'] = array($insertID, $epID);
                                //==transaksi_id dan nomor nota diinject kan ke gate utama
                                $injectors = array(
                                    "transaksi_id" => $insertID,
                                    "nomer" => $tmpNomorNota,
                                    "nomer2" => $tmpNomorNotaAlias,
                                );
                                $arrInjectorsTarget = array(
                                    "items",
                                    "items2_sum",
                                    "rsltItems",
                                );
                                foreach ($injectors as $key => $val) {
                                    $_SESSION[$cCode]['main'][$key] = $val;
                                    foreach ($arrInjectorsTarget as $target) {
                                        if (isset($_SESSION[$cCode][$target])) {
                                            foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                                $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                                if (isset($_SESSION[$cCode][$target][$id])) {
                                                    $_SESSION[$cCode][$target][$id][$key] = $val;
                                                }
                                            }
                                        }
                                    }
                                }

                                //===signature
                                $dwsign = $tr->writeSignature($insertID, array(
                                    "nomer" => $_SESSION[$cCode]['main']['nomer'],
                                    "step_number" => 1,
                                    "step_code" => $connecTo,
                                    "step_name" => $this->configUiJenis["connectToEdit"][1]["label"],
                                    "group_code" => "",
                                    "oleh_id" => $this->session->login['id'],
                                    "oleh_nama" => $this->session->login['nama'],
                                    "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                                    "transaksi_id" => $masterID,
                                    "deskripsi" => "edit transaksi",
                                    "cabang_id" => $this->session->login['cabang_id'],
                                    "cabang_nama" => $this->session->login['cabang_nama'],
                                    "current_transaksi_id" => $masterID,
                                    "current_nomer" => $_SESSION[$cCode]['main']['nomer'],
                                )) or die("Failed to write signature");
                                showLast_query("kuning");
                                $mongoList['sign'][] = $dwsign;
                                $idHis = array(
                                    $stepNumber => array(
                                        "olehID" => $_SESSION[$cCode]['main']['olehID'],
                                        "olehName" => $_SESSION[$cCode]['main']['olehName'],
                                        "step" => $stepNumber,
                                        "trID" => $insertID,
                                        "nomer" => $tmpNomorNota,
                                        "nomer2" => $tmpNomorNotaAlias,
                                        "counters" => $appliedCounters,
                                        "counters_intext" => $appliedCounters_inText,
                                    ),
                                );
                                $idHis_blob = blobEncode($idHis);
                                $idHis_intext = print_r($idHis, true);
                                $tr = new MdlTransaksi();
                                $dupState = $tr->updateData(array("id" => $insertID), array(
                                    "next_step_num" => $nextProp['num'],
                                    "next_step_code" => $nextProp['code'],
                                    "next_step_label" => $nextProp['label'],
                                    "next_group_code" => $nextProp['groupID'],

                                    //===references
//                            "id_master" => $insertID,
                                    "id_master" => $masterID,// milik transkasiID yang diedit
                                    "id_top" => $insertID,
                                    "ids_prev" => "",
                                    "ids_prev_intext" => "",
                                    "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                    "nomers_prev" => "",
                                    "nomers_prev_intext" => "",
                                    "jenises_prev" => "",
                                    "jenises_prev_intext" => "",
                                    "ids_his" => $idHis_blob,
                                    "ids_his_intext" => $idHis_intext,

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

                                $addValues = array(
                                    //===references
                                    "id_master" => $insertID,
                                    "id_top" => $insertID,
                                    "ids_prev" => "",
                                    "ids_prev_intext" => "",
                                    "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                    "nomers_prev" => "",
                                    "nomers_prev_intext" => "",
                                    "jenises_prev" => "",
                                    "jenises_prev_intext" => "",
                                    "ids_his" => $idHis_blob,
                                    "ids_his_intext" => $idHis_intext,
                                );
                                foreach ($addValues as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                                }

                            }
                            if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                                $inserMainValues = array();
                                if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                                    //matiHEre("hooppp");
                                    $inserMainValues = array();
                                    foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                                        if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                                            $dd = $tr->writeMainValues($insertID, array(
                                                "key" => $key,
                                                "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                                            ));

                                            $inserMainValues[] = $dd;
                                            $mongoList['mainValues'][] = $dd;
                                        }
                                    }
                                }

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

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

                                if (sizeof($inserMainValues) > 0) {
                                    $arrBlob = blobEncode($inserMainValues);
                                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                                }
                            }
                            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                                foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                                    $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                    //                    cekkuning("making a clone for input key $key / $val");
                                    //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                                    //                    $replacers=array(
                                    //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                                    //                    );
                                    //                    foreach($replacers as $key=>$val){
                                    //                        $tmpTableIn[$key]=$val;
                                    //                    }
                                    //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                                }
                            }
                            if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                                foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                                    $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                                }
                            }
                            if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                                foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                                    $tr->writeMainApplets($insertID, array(
                                        "mdl_name" => $amdl,
                                        "key" => $aSpec['key'],
                                        "label" => $aSpec['labelValue'],
                                        "description" => $aSpec['description'],
                                    ));
                                }
                            }
                            if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                                foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                                    $tr->writeMainElements($insertID, array(
                                        "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                                        "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                                        "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                                        "name" => $aSpec['name'],
                                        "label" => $aSpec['label'],
                                        "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                                        "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                                    ));
                                    //==nebeng bikin inputLabels
//                                $currentValue = "";
//                                switch ($aSpec['elementType']) {
//                                    case "dataModel":
//                                        $currentValue = $aSpec['key'];
//                                        break;
//                                    case "dataField":
//                                        $currentValue = $aSpec['value'];
//                                        break;
//                                }
//                                if (array_key_exists($elName, $relOptionConfigs)) {
//                                    //					cekhijau("$eName terdaftar pada relInputs");
//
//
//                                    if (isset($relOptionConfigs[$elName][$currentValue])) {
//                                        if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
//                                            foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
//                                                $inputLabels[$oValueName] = $oValSpec['label'];
//                                                if (isset($oValSpec['auth'])) {
//                                                    if (isset($oValSpec['auth']['groupID'])) {
//                                                        $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                    else {
//                                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
//                                    }
//
//                                }

                                }
                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

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


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

                                    foreach ($indexing_details as $k => $arrID) {
                                        $arrBlob = blobEncode($arrID);
                                        $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                                        cekOrange($this->db->last_query());
                                    }
                                }
                            }
                            else {
                                die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                                $insertIDs = array();
                                foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                                    $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                                    $mongoList['detail'] = $insertIDs;
                                    if ($epID != 999) {
                                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                        $mongoList['detail'] = $insertIDs;
                                    }
                                    cekUngu($this->db->last_query());
                                }
                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                                $insertIDs = array();
                                foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                    $insertIDs[] = $insertDetailID;
                                    $mongoList['detail'][] = $insertDetailID;
                                    if ($epID != 999) {
                                        $dd = $tr->writeDetailEntries($epID, $dSpec);
                                        $insertIDs[] = $dd;
                                        $mongoList['detail'][] = $dd;
                                    }
                                }
                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                                $insertIDs = array();
                                foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                                    $dd = $tr->writeDetailEntries($insertID, $dSpec);
                                    $insertIDs[] = $dd;
                                    $mongoList['detil'][] = $dd;
                                    if ($epID != 999) {
                                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                        $mongoList['detil'] = $insertIDs;
                                    }
                                    cekUngu($this->db->last_query());
                                }
                            }
                            if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

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

                                            }
                                        }
                                    }
                                }

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

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

                            $baseRegistries = array(
                                'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                                'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                                'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                                'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                                'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                                'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                                'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                                'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                                'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                                'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                                'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                                'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                                'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                                'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                                'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                                'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                                'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                                'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                                'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                                'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                                'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                                'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                                'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                                'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                                'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                                'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                                'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                                'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                                'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                                'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                                'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                                'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                                'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                                'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                                "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                                "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                                "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                                "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                                "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                                "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                                "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                                "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                                "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                                "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                                "items_noapprove" => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),
                                "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                                "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                                //----
                                'mainOriginal' => isset($_SESSION[$cCode]['mainOriginal']) ? $_SESSION[$cCode]['mainOriginal'] : array(),
                                'itemsOriginal' => isset($_SESSION[$cCode]['itemsOriginal']) ? $_SESSION[$cCode]['itemsOriginal'] : array(),
                                //----
                            );
                            $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                            showLast_query("hijau");
                            cekHijau("SELESAI menjalankan EDITOR...");
                        }
                    }
                    else {
                        $tableIn_master['trash_4'] = 1;
                        $tableIn_master['cancel_id'] = $this->session->login['id'];
                        $tableIn_master['cancel_name'] = $this->session->login['nama'];
                        $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                        $tableIn_master['deskripsi'] = "rejection";
                        $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                        $mongoList['main'][] = $epID;
                        if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                            $insertIDs = array();
                            foreach ($tableIn_detail as $dSpec) {
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detail'] = $insertIDs;
                                }
                            }
                        }
                    }
                }

                $jenisTr_component = isset($this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target']) ? $this->configUi[$jenisTr]['steps'][$stepNumCurrent]['target'] : NULL;
                $tokoID = $_SESSION[$cCode]['main']['tokoID'];
                $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];
                $transaksiMode = isset($this->configUi[$this->jenisTr]["transaksiMode"]) ? $this->configUi[$this->jenisTr]["transaksiMode"] : mati_disini("Mode transaksi silahkan diseting di coTransaksiUi " . $this->jenisTr);
                $runCoreAkunting = isset($this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["runCoreAkunting"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNumCurrent]["runCoreAkunting"] : false;
                $core = isset($this->config->item('heTransaksi_core')[$this->modul][$transaksiMode]) ? $this->config->item('heTransaksi_core')[$this->modul][$transaksiMode] : array();

                //===if rollback is needed
                //rollback preproc, master
                if (isset($core['preProcessor'][$jenisTr_component]['master'])) {
                    $iterator = isset($core['preProcessor'][$jenisTr_component]['master']) ? $core['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($core['preProcessor'][$jenisTr_component]['detail'])) {
                    $iterator = isset($core['preProcessor'][$jenisTr_component]['detail']) ? $core['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->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                    $iterator = isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configValues[$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->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {
                    $iterator = isset($this->configValues[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configValues[$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");
                }

            }

        }


        if (sizeof($referenceRevertConfigs) > 0) {
            if (isset($referenceRevertConfigs['enabled']) && ($referenceRevertConfigs['enabled'] == true)) {

                $arrQtyRevert = array();
                foreach ($items as $spec) {
                    $arrQtyRevert[$spec['id']] = $spec['qty'];
                }

                $referenceID = $_SESSION[$cCode]['main'][$referenceRevertConfigs['referenceID']];
                cekHitam(":: $referenceID ::");

                $tr = new MdlTransaksi();
                $tr->setFilters(array());
                $refTr = $tr->lookupDetailTransaksi($referenceID)->result();
                if (sizeof($refTr) > 0) {
                    foreach ($refTr as $spec) {
                        $qty = isset($arrQtyRevert[$spec->produk_id]) ? $arrQtyRevert[$spec->produk_id] : 0;
                        $data = array(
                            "valid_qty" => $spec->valid_qty + $qty,
                            "req_cancel_qty" => $spec->req_cancel_qty - $qty,
                        );
                        $where = array(
                            "produk_id" => $spec->produk_id,
                            "transaksi_id" => $spec->transaksi_id,
                        );
                        $to = new MdlTransaksi();
                        $to->setFilters(array());
                        $to->setTableName($to->getTableNames()['detail']);
                        $dupState = $to->updateData($where, $data);
                        $mongListUpadte['update']['detail'][] = array(
                            "where" => $where,
                            "value" => $data,
                        );
                        cekPink2($this->db->last_query());
                    }
                }

                //arrPrint($arrQtyRevert);
            }
        }

//mati_disini(__LINE__);
        //==================================================================================================
        $this->load->model("Mdls/MdlTransaksiLaporan");
        $lt = New MdlTransaksiLaporan();
        $dataTransaksiLaporan = array(
            "transaksi_id" => $currentInsertID,
            "master_id" => $currentMasterID,
            "nomer" => $currentNomer,
            "metode" => "reject",
        );
        $lt->addData($dataTransaksiLaporan);
        showLast_query("ungu");
        //==================================================================================================
        //==MENGUPDATE LOCKER TRANSAKSI ====================================================================
        $this->load->model("Mdls/MdlLockerTransaksi");
        $lt = New MdlLockerTransaksi();
        $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], $transaksiID_reference, NULL);
        //==================================================================================================


        //==tampilkan receipt
        cekMerah("-- DONE --");


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


        mati_disini(get_class($this) . " " . __FUNCTION__ . " under maintenance...");


        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");


        //region connect ke mongoDB
        $pakai_ini = 0;
        if ($pakai_ini == 1) {
            if (sizeof($mongListUpadte) > 0) {
                $mong = new MdlMongoMother();
                foreach ($mongListUpadte 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']);
                                }
                            }
                        }
                    }
                }
            }

            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("ninsert into :".$this->mongoTableList[$gateList]);
                            //                        arrPrint($transksi_main);
                            $mong->addData($transksi_main);
                        }
                    }
                    //                    cekHitam($listedTable[$gateList]);
                    //                    cekLime($gateList);

                }
            }
        }
        //endregion


        if (isset($_SESSION[$cCode])) {
            unset($_SESSION[$cCode]);
        }
        if (isset($oldCode)) {
            if (isset($_SESSION[$oldCode])) {
                unset($_SESSION[$oldCode]);
            }
        }
        $arrAlert = array(
            "type" => "success",
            "title" => "Transaction updated",
            //                        "html" => "your order has been saved and ready to process",
            "html" => $this->session->errMsg,
            "timer" => "1500",
            "showConfirmButton" => false,
            "allowOutsideClick" => false,
        );

        echo swalAlert($arrAlert);
        echo topReload();

        unset($this->session->errMsg);
    }
    public function doRevertAll_old_unused()
    {
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }


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


        // region transaksi yang dibuka
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        $tr->addFilter("id='$no'");
        $tmpTr = $tr->lookupMainTransaksi()->result();
        //        cekOrange($this->db->last_query());
        $insertID = $tmpTr[0]->id;
        $insertNum = $tmpTr[0]->nomer;
        $masterID = $tmpTr[0]->id_master;
        // endregion transaksi yang dibuka
        cekHitam("trID: $insertID, masterID: $masterID");


        //region membaca transaksi berdasarkan masterID
        $trm = new MdlTransaksi();
        $trm->setFilters(array());
        $trm->addFilter("id_master='$masterID'");
        $trm->addFilter("link_id='0'");
        $trm->addFilter("trash_4='0'");
        $tmpTrm = $trm->lookupMainTransaksi()->result();
        showLast_query("biru");
        $indexReg = array();
        $arrMainDataTrans = array();
        $arrMainDataTransID = array();
        $arrTrIDs = array();
        $regParam = array(
            "main",
            "items",
            "tableIn_master",
            "tableIn_detail",
        );
        foreach ($tmpTrm as $tmpTrmSpec) {
            $arrMainDataTransID[$tmpTrmSpec->id] = array(
                "step" => $tmpTrmSpec->step_number,
                "jenisTr" => $tmpTrmSpec->jenis_master,
                "transaksi_id" => $tmpTrmSpec->id,
                "nomer" => $tmpTrmSpec->nomer,
            );
//            $indexRegTmp = blobDecode($tmpTrmSpec->indexing_registry);
//            foreach ($indexRegTmp as $key => $val) {
//                if (in_array($key, $regParam)) {
//                    $indexReg[] = $val;
//                }
//            }
            $arrTrIDs[$tmpTrmSpec->id] = $tmpTrmSpec->id;
        }
        //endregion

        krsort($arrMainDataTransID);


        //region swap from registry
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
//        $tr->addFilter("transaksi_id in ('" . implode("','", $indexReg) . "')");
        $tr->addFilter("transaksi_id in ('" . implode("','", $arrTrIDs) . "')");
        $tmpReg = $tr->lookupDataRegistries()->result();
        //        cekmerah($this->db->last_query());

        $tmpRegData = array();
        if (sizeof($tmpReg) > 0) {
            foreach ($tmpReg as $row) {
                foreach ($row as $key_reg => $val_reg) {
                    if (in_array($key_reg, $regParam)) {
                        $tmpRegData[$row->transaksi_id][$key_reg] = $val_reg;
                    }
                }

            }
        }
        //endregion
        //arrPrintWebs($arrMainDataTransID);
//        arrPrintWebs($tmpRegData);
//        mati_disini("line " . __LINE__);

        $this->db->trans_start();


        //        $referenceRevertConfigs = isset($this->configUi[$jenisTr]['referenceRevert']) ? $this->configUi[$jenisTr]['referenceRevert'] : array();
        $prepConfigs = null != $this->config->item('hePreProcessors') ? $this->config->item('hePreProcessors') : array();
        $postConfigs = null != $this->config->item('hePostProcessors') ? $this->config->item('hePostProcessors') : array();
        $postDeniedConfigs = null != $this->config->item('hePostProcessorsDenied') ? $this->config->item('hePostProcessorsDenied') : array();


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


        $mongListUpadte = array();
        $mongoList = array();
        foreach ($arrMainDataTransID as $arrMainDataTransIDSpec) {

            $no = $arrMainDataTransIDSpec['transaksi_id'];
            $stepNumCurrent = $arrMainDataTransIDSpec['step'];
            $jenisTr = $arrMainDataTransIDSpec['jenisTr'];
            cekUngu(":: trID yang dibatalkan $no ::");
            $tp = new MdlTransaksi();
            $tp->addFilter("id='$no'");
            $tpTmp = $tp->lookupAll()->result();
            $currentMasterID = $tpTmp[0]->id_master;


            cekHitam("MENGEMBALIKAN PRE & POST UNTUK STEP $stepNumCurrent");

            $arrData = array(
                "next_step_code" => $nextProp['code'],
                "next_step_label" => $nextProp['label'],
                "next_group_code" => $nextProp['groupID'],
                "next_step_num" => $nextProp['num'],
                "step_current" => $stepNumCurrent,
                //                "step_number" => $stepNumCurrent,
                "trash_4" => "1",
                "cancel_dtime" => date("Y-m-d H:i:s"),
                "cancel_name" => $this->session->login['nama'],
                "cancel_id" => $this->session->login['id'],
            );
            $arrData_detail = array(
                "next_substep_code" => $nextProp['code'],
                "next_substep_label" => $nextProp['label'],
                "next_subgroup_code" => $nextProp['groupID'],
                "next_substep_num" => $nextProp['num'],
                "sub_step_number" => 0,
            );

            foreach ($tmpRegData[$no] as $key_reg => $val_reg) {

                $var = $key_reg;
                $$var = blobDecode($val_reg);
            }


            //region update step yang sebelumnya aktif, transaksi yang dibuka sekarang
            $tp = new MdlTransaksi();
            $dupState = $tp->updateData(array(
                "id" => $no,
            ), $arrData) or die("Failed to update tr next-state!");
            $mongListUpadte['update']['main'][] = array(
                "where" => array("id" => $no,),
                "value" => $arrData,
            );
            cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

            $to = new MdlTransaksi();
            $to->setFilters(array());
            $to->setTableName($to->getTableNames()['detail']);
            $dupState = $to->updateData(array(
                "transaksi_id" => $no,
                "trash" => 0,
            ), $arrData_detail) or die("Failed to update tr next-state!");
            $mongListUpadte['update']['detail'][] = array(
                "where" => array(
                    "transaksi_id" => $no,
                    "trash" => 0,
                ),
                "value" => $arrData_detail,
            );
            cekLime($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

            //endregion


            //region sesuaikan signature untuk cloningan, ikut minus
            $arrSign = array(
                "prev_id" => $no,
                "nomer" => "rejection",
                "step_number" => -$stepNumCurrent, // ini minus step number
                "step_code" => $this->configUi[$jenisTr]['steps'][abs($stepNumCurrent)]['target'],
                "step_name" => $this->configUi[$jenisTr]['steps'][abs($stepNumCurrent)]['label'],
                "group_code" => $this->configUi[$jenisTr]['steps'][abs($stepNumCurrent)]['userGroup'],
                "oleh_id" => $this->session->login['id'],
                "oleh_nama" => $this->session->login['nama'],
                "keterangan" => $this->configUi[$jenisTr]['steps'][abs($stepNumCurrent)]['label'] . " oleh " . $this->session->login['nama'],
            );
            $dwsign = $tr->writeSignature($tmpTr[0]->id_top, $arrSign) or die("Failed to write signature");
            $mongoList['sign'][] = $dwsign;
            cekPink2($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
            //endregion


            // region netralisasi payment source
            $tr = New MdlTransaksi();
            $tr->setFilters(array());
            $tr->addFilter("sisa>0");
            $paymentSrc = $tr->lookupPaymentSrcByTransID($no)->result();
            cekBiru($this->db->last_query());
            if (sizeof($paymentSrc) > 0) {
                foreach ($paymentSrc as $pSpec) {
                    if ($pSpec->terbayar == 0) {
                        $where = array(
                            "id" => $pSpec->id,
                            "transaksi_id" => $pSpec->transaksi_id,
                        );
                        $data = array(
                            "sisa" => 0,
                            "returned" => $pSpec->sisa,
                            "sisa_valas" => 0,
                            "returned_valas" => $pSpec->sisa_valas,
                            "cancel_id" => $this->session->login['id'],
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                        );

                        $tra = New MdlTransaksi();
                        $tra->setFilters(array());
                        $tra->updatePaymentSrc($where, $data);
                        cekUngu(":: mereject payment source bila ada...");
                        cekUngu($this->db->last_query());
                    }
                    else {
                        mati_disini("transaksi gagal karena " . $pSpec->_key . " telah diterima oleh finance.");
                    }
                }
            }
            else {
                cekBiru(":: tidak ada payment source... ::");
            }
            // endregion netralisasi payment source

            // region netralisasi extended step
            $tr = New MdlTransaksi();
            $tr->setFilters(array());
            $exTmp = $tr->lookupExtStepByTrID($no);
            if (sizeof($exTmp) > 0) {
                foreach ($exTmp as $exSpec) {

                    $tra = New MdlTransaksi();
                    $tra->setFilters(array());
                    $tra->rejectExtStepByID($exSpec['id']);
                    $mongListUpadte['update']['extra'][] = array(
                        "where" => array(
                            "id" => $exSpec['id'],
                        ),
                        "value" => array(
                            "state" => "-1",
                        ),
                    );
                    cekUngu(":: mereject extended step bila ada...");
                    cekUngu($this->db->last_query());
                }
            }
            else {
                cekBiru(":: tidak ada extended step... ::");
            }

            // endregion netralisasi extended step

            // region menulis entry point
            if (isset($tableIn_master) && sizeof($tableIn_master) > 0) {
                if (isset($this->configUiJenis["connectToReject"][$stepNumCurrent])) {
                    if ($this->configUiJenis["connectToReject"][$stepNumCurrent]["enabled"] == true) {
                        $masterID = $currentMasterID;
                        $connecTo = $this->configUiJenis["connectToReject"][$stepNumCurrent]["connectTo"];
                        cekHijau("START menjalankan REJECT ALL... [$masterID] [$connecTo]");
                        if ($connecTo == NULL) {
                            mati_disini("kode edit transaksi tidak dikenali. segera hubungi admin.");
                        }
                        $oldCode = $cCode;
                        $cCode = "_TR_" . $connecTo;
                        $_SESSION[$cCode] = array(
                            'main' => isset($_SESSION[$oldCode]['main']) ? $_SESSION[$oldCode]['main'] : array(),
                            'items' => isset($_SESSION[$oldCode]['items']) ? $_SESSION[$oldCode]['items'] : array(),
                            'items2' => isset($_SESSION[$oldCode]['items2']) ? $_SESSION[$oldCode]['items2'] : array(),
                            'items2_sum' => isset($_SESSION[$oldCode]['items2_sum']) ? $_SESSION[$oldCode]['items2_sum'] : array(),
                            'itemSrc' => isset($_SESSION[$oldCode]['itemSrc']) ? $_SESSION[$oldCode]['itemSrc'] : array(),
                            'itemSrc_sum' => isset($_SESSION[$oldCode]['itemSrc_sum']) ? $_SESSION[$oldCode]['itemSrc_sum'] : array(),
                            'items3' => isset($_SESSION[$oldCode]['items3']) ? $_SESSION[$oldCode]['items3'] : array(),
                            'items3_sum' => isset($_SESSION[$oldCode]['items3_sum']) ? $_SESSION[$oldCode]['items3_sum'] : array(),
                            'items4' => isset($_SESSION[$oldCode]['items4']) ? $_SESSION[$oldCode]['items4'] : array(),
                            'items4_sum' => isset($_SESSION[$oldCode]['items4_sum']) ? $_SESSION[$oldCode]['items4_sum'] : array(),
                            'items5_sum' => isset($_SESSION[$oldCode]['items5_sum']) ? $_SESSION[$oldCode]['items5_sum'] : array(),
                            'items6_sum' => isset($_SESSION[$oldCode]['items6_sum']) ? $_SESSION[$oldCode]['items6_sum'] : array(),
                            'items7_sum' => isset($_SESSION[$oldCode]['items7_sum']) ? $_SESSION[$oldCode]['items7_sum'] : array(),
                            'items8_sum' => isset($_SESSION[$oldCode]['items8_sum']) ? $_SESSION[$oldCode]['items8_sum'] : array(),
                            'items9_sum' => isset($_SESSION[$oldCode]['items9_sum']) ? $_SESSION[$oldCode]['items9_sum'] : array(),
                            'items10_sum' => isset($_SESSION[$oldCode]['items10_sum']) ? $_SESSION[$oldCode]['items10_sum'] : array(),
                            'rsltItems' => isset($_SESSION[$oldCode]['rsltItems']) ? $_SESSION[$oldCode]['rsltItems'] : array(),
                            'rsltItems2' => isset($_SESSION[$oldCode]['rsltItems2']) ? $_SESSION[$oldCode]['rsltItems2'] : array(),
                            'rsltItems3' => isset($_SESSION[$oldCode]['rsltItems3']) ? $_SESSION[$oldCode]['rsltItems3'] : array(),
                            'tableIn_master' => isset($_SESSION[$oldCode]['tableIn_master']) ? $_SESSION[$oldCode]['tableIn_master'] : array(),
                            'tableIn_detail' => isset($_SESSION[$oldCode]['tableIn_detail']) ? $_SESSION[$oldCode]['tableIn_detail'] : array(),
                            'tableIn_detail2_sum' => isset($_SESSION[$oldCode]['tableIn_detail2_sum']) ? $_SESSION[$oldCode]['tableIn_detail2_sum'] : array(),
                            'tableIn_detail_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems'] : array(),
                            'tableIn_detail_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_rsltItems2'] : array(),
                            'tableIn_master_values' => isset($_SESSION[$oldCode]['tableIn_master_values']) ? $_SESSION[$oldCode]['tableIn_master_values'] : array(),
                            'tableIn_detail_values' => isset($_SESSION[$oldCode]['tableIn_detail_values']) ? $_SESSION[$oldCode]['tableIn_detail_values'] : array(),
                            'tableIn_detail_values_rsltItems' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems'] : array(),
                            'tableIn_detail_values_rsltItems2' => isset($_SESSION[$oldCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$oldCode]['tableIn_detail_values_rsltItems2'] : array(),
                            'tableIn_detail_values2_sum' => isset($_SESSION[$oldCode]['tableIn_detail_values2_sum']) ? $_SESSION[$oldCode]['tableIn_detail_values2_sum'] : array(),
                            'main_add_values' => isset($_SESSION[$oldCode]['main_add_values']) ? $_SESSION[$oldCode]['main_add_values'] : array(),
                            'main_add_fields' => isset($_SESSION[$oldCode]['main_add_fields']) ? $_SESSION[$oldCode]['main_add_fields'] : array(),
                            'main_elements' => isset($_SESSION[$oldCode]['main_elements']) ? $_SESSION[$oldCode]['main_elements'] : array(),
                            'main_inputs' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                            'main_inputs_orig' => isset($_SESSION[$oldCode]['main_inputs']) ? $_SESSION[$oldCode]['main_inputs'] : array(),
                            "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                            "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                            "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                            "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                            "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                            "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                            "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                            "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                            "revert" => isset($_SESSION[$oldCode]['revert']) ? $_SESSION[$oldCode]['revert'] : array(),
                            "items_komposisi" => isset($_SESSION[$oldCode]['items_komposisi']) ? $_SESSION[$oldCode]['items_komposisi'] : array(),
                            "items_noapprove" => isset($_SESSION[$oldCode]['items_noapprove']) ? $_SESSION[$oldCode]['items_noapprove'] : array(),
                            "jurnalItems" => isset($_SESSION[$oldCode]['jurnalItems']) ? $_SESSION[$oldCode]['jurnalItems'] : array(),
                            "componentsBuilder" => isset($_SESSION[$oldCode]['componentsBuilder']) ? $_SESSION[$oldCode]['componentsBuilder'] : array(),
                        );
                        // masuk ke gerbang TableInMaster, tabel transaksi
                        $masterReplacers = array(
//                        "inv" => $tmpNomorNota,
                            "jenis_master" => $this->jenisTr,
                            "jenis_top" => $connecTo,
                            "jenis" => $connecTo,
                            "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "transaksi_jenis" => $connecTo,
                            "step_avail" => 1,
                            "step_current" => 1,
                            "step_number" => 1,
                            "next_step_code" => "",
                            "next_step_label" => "",
                            "next_group_code" => "",
                            "next_step_num" => "0",
                            "trash_4" => 1,
                            "cancel_dtime" => date("Y-m-d H:i:s"),
                            "cancel_name" => $this->session->login['nama'],
                            "cancel_id" => $this->session->login['id'],
                            "deskripsi" => "rejection",
                            "oleh_id" => my_id(),
                            "oleh_nama" => my_name()
                        );
                        // masuk ke gerbang main
                        $masterReplacersO = array(
                            "stepCode" => $connecTo,
                            "jenisTrTop" => $connecTo,
                            "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
//                        "inv" => $tmpNomorNota,
                            "jenis_master" => $this->jenisTr,
                            "jenis_top" => $connecTo,
                            "jenis" => $connecTo,
                            "jenis_label" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "transaksi_jenis" => $connecTo,
                            "stepCode" => $connecTo,
                            "jenisTrTop" => $connecTo,
                            "jenisTrName" => $this->configUiJenis["connectToReject"][$stepNumCurrent]["label"],
                            "step_avail" => 1,
                            "step_current" => 1,
                            "step_number" => 1,
                            "next_step_code" => "",
                            "next_step_label" => "",
                            "next_group_code" => "",
                            "next_step_num" => "0",
                            "olehID" => my_id(),
                            "olehName" => my_name(),
                        );
                        foreach ($masterReplacersO as $key => $val) {
                            $_SESSION[$cCode]['main'][$key] = $val;
                        }
                        foreach ($masterReplacers as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }

                        $tokoID = $_SESSION[$cCode]['main']['tokoID'];
                        $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];

                        //region penomoran receipt
                        $this->load->model("CustomCounter");
                        $cn = new CustomCounter("transaksi");
                        $cn->setType("transaksi");
                        $counterForNumber = array($this->configValues[$this->jenisTr]['formatNotaReject']);
                        if (!in_array($counterForNumber[0], $this->configValues[$this->jenisTr]['countersReject'])) {
                            die(__LINE__ . " Used number should be registered in 'counters' config as well");
                        }
                        echo "<div style='background:#ff7766;'>";
                        foreach ($counterForNumber as $i => $cRawParams) {
                            $cParams = explode("|", $cRawParams);
                            $cValues = array();
                            foreach ($cParams as $param) {
                                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                            }
                            $cRawValues = implode("|", $cValues[$i]);
                            $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                        }
                        echo "</div style='background:#ff7766;'>";

                        $stepNumber = 1;
                        $tmpNomorNota = $paramSpec['paramString'];
                        $tmpNomorNotaAlias = formatNota("nomer_nolink", $tmpNomorNota);
                        $nextProp = array(
                            "num" => 0,
                            "code" => "",
                            "label" => "",
                            "groupID" => "",
                        );
                        //endregion

                        //region dynamic counters
                        // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
                        $cn = new CustomCounter("transaksi");
                        $cn->setType("transaksi");
                        $configCustomParams = $this->configCore[$this->jenisTr]['countersReject'];
                        arrPrintHijau($configCustomParams);
                        $configCustomParams[] = "stepCode";
                        //arrPrint($configCustomParams);
                        if (sizeof($configCustomParams) > 0) {
                            $cContent = array();
                            foreach ($configCustomParams as $i => $cRawParams) {
                                $cParams = explode("|", $cRawParams);
                                $cValues = array();
                                foreach ($cParams as $param) {
                                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                                }
                                $cRawValues = implode("|", $cValues[$i]);
                                $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                                $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                                switch ($paramSpec['id']) {
                                    case 0: //===counter type is new
                                        $addData = array(
                                            "toko_id" => $tokoID,
                                            "toko_nama" => $tokoNama,
                                        );
                                        $paramKeyRaw = print_r($cParams, true);
                                        $paramValuesRaw = print_r($cValues[$i], true);
                                        $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                        showLast_query("biru");
                                        break;
                                    default: //===counter to be updated
                                        $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                                        break;
                                }
                                //echo "<hr>";
                            }
                        }
                        $appliedCounters = base64_encode(serialize($cContent));
                        $appliedCounters_inText = print_r($cContent, true);
//                        mati_disini();
//arrPrintPink($cContent);
                        //
                        //region addition on master


                        $addValues = array(
                            'counters' => $appliedCounters,
                            'counters_intext' => $appliedCounters_inText,
                            'nomer' => $tmpNomorNota,
                            'nomer2' => $tmpNomorNotaAlias,
                            'dtime' => date("Y-m-d H:i:s"),
                            'fulldate' => date("Y-m-d"),
                            "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                            "step_number" => 1,
                            "step_current" => 1,
                            "next_step_num" => $nextProp['num'],
                            "next_step_code" => $nextProp['code'],
                            "next_step_label" => $nextProp['label'],
                            "next_group_code" => $nextProp['groupID'],
                            "tail_number" => 1,
                            "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


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

                        //
                        //region addition on detail
                        $addSubValues = array(
                            "sub_step_number" => 1,
                            "sub_step_current" => 1,
                            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                            "next_substep_num" => $nextProp['num'],
                            "next_substep_code" => $nextProp['code'],
                            "next_substep_label" => $nextProp['label'],
                            "next_subgroup_code" => $nextProp['groupID'],
                            "sub_tail_number" => 1,
                            "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


                        );
                        foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                            foreach ($addSubValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                            }
                        }
                        //endregion
                        // </editor-fold>
                        //endregion

                        $addValues = array(
                            'counters' => $appliedCounters,
                            'counters_intext' => $appliedCounters_inText,
                            'nomer' => $tmpNomorNota,
                            'nomer2' => $tmpNomorNotaAlias,
                            'dtime' => date("Y-m-d H:i:s"),
                            'fulldate' => date("Y-m-d"),
                        );
                        foreach ($addValues as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }
                        $masterReplacers = array(
                            "nomer" => $tmpNomorNota,
                            "nomer2" => $tmpNomorNotaAlias,
                            "counters" => $appliedCounters,
                            "counters_intext" => $appliedCounters_inText,
                        );
                        foreach ($masterReplacers as $key => $val) {
                            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                        }
                        $detailReplacers = array(
                            "sub_step_avail" => 1,
                            "sub_step_current" => 1,
                            "sub_step_number" => 1,
                            "next_substep_num" => "",
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                        );
                        if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                            foreach ($_SESSION[$cCode]['tableIn_detail'] as $k => $dSpec) {
                                foreach ($dSpec as $key => $val) {
                                    $_SESSION[$cCode]['tableIn_detail'][$k][$key] = isset($detailReplacers[$key]) ? $detailReplacers[$key] : $val;
                                }
                            }
                        }
                        $itemsReplacers = array(
                            "next_substep_num" => "",
                            "next_substep_code" => "",
                            "next_substep_label" => "",
                            "next_subgroup_code" => "",
                        );
                        if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
                            foreach ($_SESSION[$cCode]['items'] as $k => $dSpec) {
                                foreach ($dSpec as $key => $val) {
                                    $_SESSION[$cCode]['items'][$k][$key] = isset($itemsReplacers[$key]) ? $itemsReplacers[$key] : $val;
                                }
                            }
                        }

                        //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
                        if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {
                            $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
                            $_SESSION[$cCode]['tableIn_master']['trash_4'] = 1;// dibatalkan
                            $_SESSION[$cCode]['tableIn_master']['cli'] = 1;

                            $tr = new MdlTransaksi();
                            $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                            $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                            cekHitam("[$insertID] :: " . $this->db->last_query());
                            $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
                            $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                            $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                            if ($insertID < 1) {
                                die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                            }
                            $mongoList['main'] = array($insertID, $epID);
                            //==transaksi_id dan nomor nota diinject kan ke gate utama
                            $injectors = array(
                                "transaksi_id" => $insertID,
                                "nomer" => $tmpNomorNota,
                                "nomer2" => $tmpNomorNotaAlias,
                            );
                            $arrInjectorsTarget = array(
                                "items",
                                "items2_sum",
                                "rsltItems",
                            );
                            foreach ($injectors as $key => $val) {
                                $_SESSION[$cCode]['main'][$key] = $val;
                                foreach ($arrInjectorsTarget as $target) {
                                    if (isset($_SESSION[$cCode][$target])) {
                                        foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                            $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                            if (isset($_SESSION[$cCode][$target][$id])) {
                                                $_SESSION[$cCode][$target][$id][$key] = $val;
                                            }
                                        }
                                    }
                                }
                            }

                            //===signature
                            $dwsign = $tr->writeSignature($insertID, array(
                                "nomer" => $_SESSION[$cCode]['main']['nomer'],
                                "step_number" => 1,
                                "step_code" => $connecTo,
                                "step_name" => $this->configUiJenis["connectToEdit"][1]["label"],
                                "group_code" => "",
                                "oleh_id" => $this->session->login['id'],
                                "oleh_nama" => $this->session->login['nama'],
                                "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                                "transaksi_id" => $masterID,
                                "deskripsi" => "edit transaksi",
                                "cabang_id" => $this->session->login['cabang_id'],
                                "cabang_nama" => $this->session->login['cabang_nama'],
                                "current_transaksi_id" => $masterID,
                                "current_nomer" => $_SESSION[$cCode]['main']['nomer'],
                            )) or die("Failed to write signature");
                            showLast_query("kuning");
                            $mongoList['sign'][] = $dwsign;
                            $idHis = array(
                                $stepNumber => array(
                                    "olehID" => $_SESSION[$cCode]['main']['olehID'],
                                    "olehName" => $_SESSION[$cCode]['main']['olehName'],
                                    "step" => $stepNumber,
                                    "trID" => $insertID,
                                    "nomer" => $tmpNomorNota,
                                    "nomer2" => $tmpNomorNotaAlias,
                                    "counters" => $appliedCounters,
                                    "counters_intext" => $appliedCounters_inText,
                                ),
                            );
                            $idHis_blob = blobEncode($idHis);
                            $idHis_intext = print_r($idHis, true);
                            $tr = new MdlTransaksi();
                            $dupState = $tr->updateData(array("id" => $insertID), array(
                                "next_step_num" => $nextProp['num'],
                                "next_step_code" => $nextProp['code'],
                                "next_step_label" => $nextProp['label'],
                                "next_group_code" => $nextProp['groupID'],

                                //===references
//                            "id_master" => $insertID,
                                "id_master" => $masterID,// milik transkasiID yang diedit
                                "id_top" => $insertID,
                                "ids_prev" => "",
                                "ids_prev_intext" => "",
                                "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                "nomers_prev" => "",
                                "nomers_prev_intext" => "",
                                "jenises_prev" => "",
                                "jenises_prev_intext" => "",
                                "ids_his" => $idHis_blob,
                                "ids_his_intext" => $idHis_intext,

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

                            $addValues = array(
                                //===references
                                "id_master" => $insertID,
                                "id_top" => $insertID,
                                "ids_prev" => "",
                                "ids_prev_intext" => "",
                                "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                                "nomers_prev" => "",
                                "nomers_prev_intext" => "",
                                "jenises_prev" => "",
                                "jenises_prev_intext" => "",
                                "ids_his" => $idHis_blob,
                                "ids_his_intext" => $idHis_intext,
                            );
                            foreach ($addValues as $key => $val) {
                                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                            }

                        }
                        if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                            $inserMainValues = array();
                            if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                                //matiHEre("hooppp");
                                $inserMainValues = array();
                                foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                                    if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                                        $dd = $tr->writeMainValues($insertID, array(
                                            "key" => $key,
                                            "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                                        ));

                                        $inserMainValues[] = $dd;
                                        $mongoList['mainValues'][] = $dd;
                                    }
                                }
                            }

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

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

                            if (sizeof($inserMainValues) > 0) {
                                $arrBlob = blobEncode($inserMainValues);
                                $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                            foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                                $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                                //                    cekkuning("making a clone for input key $key / $val");
                                //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                                //                    $replacers=array(
                                //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                                //                    );
                                //                    foreach($replacers as $key=>$val){
                                //                        $tmpTableIn[$key]=$val;
                                //                    }
                                //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                            foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                                $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                            foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                                $tr->writeMainApplets($insertID, array(
                                    "mdl_name" => $amdl,
                                    "key" => $aSpec['key'],
                                    "label" => $aSpec['labelValue'],
                                    "description" => $aSpec['description'],
                                ));
                            }
                        }
                        if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                            foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                                $tr->writeMainElements($insertID, array(
                                    "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                                    "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                                    "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                                    "name" => $aSpec['name'],
                                    "label" => $aSpec['label'],
                                    "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                                    "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                                ));
                                //==nebeng bikin inputLabels
//                                $currentValue = "";
//                                switch ($aSpec['elementType']) {
//                                    case "dataModel":
//                                        $currentValue = $aSpec['key'];
//                                        break;
//                                    case "dataField":
//                                        $currentValue = $aSpec['value'];
//                                        break;
//                                }
//                                if (array_key_exists($elName, $relOptionConfigs)) {
//                                    //					cekhijau("$eName terdaftar pada relInputs");
//
//
//                                    if (isset($relOptionConfigs[$elName][$currentValue])) {
//                                        if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
//                                            foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
//                                                $inputLabels[$oValueName] = $oValSpec['label'];
//                                                if (isset($oValSpec['auth'])) {
//                                                    if (isset($oValSpec['auth']['groupID'])) {
//                                                        $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                    else {
//                                        //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
//                                    }
//
//                                }

                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

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


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

                                foreach ($indexing_details as $k => $arrID) {
                                    $arrBlob = blobEncode($arrID);
                                    $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                                    cekOrange($this->db->last_query());
                                }
                            }
                        }
                        else {
                            die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                                $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                                $mongoList['detail'] = $insertIDs;
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detail'] = $insertIDs;
                                }
                                cekUngu($this->db->last_query());
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                                $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                                $insertIDs[] = $insertDetailID;
                                $mongoList['detail'][] = $insertDetailID;
                                if ($epID != 999) {
                                    $dd = $tr->writeDetailEntries($epID, $dSpec);
                                    $insertIDs[] = $dd;
                                    $mongoList['detail'][] = $dd;
                                }
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                            $insertIDs = array();
                            foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                                $dd = $tr->writeDetailEntries($insertID, $dSpec);
                                $insertIDs[] = $dd;
                                $mongoList['detil'][] = $dd;
                                if ($epID != 999) {
                                    $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                    $mongoList['detil'] = $insertIDs;
                                }
                                cekUngu($this->db->last_query());
                            }
                        }
                        if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

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

                                        }
                                    }
                                }
                            }

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

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

                        $baseRegistries = array(
                            'main' => isset($_SESSION[$cCode]['main']) ? $_SESSION[$cCode]['main'] : array(),
                            'items' => isset($_SESSION[$cCode]['items']) ? $_SESSION[$cCode]['items'] : array(),
                            'items2' => isset($_SESSION[$cCode]['items2']) ? $_SESSION[$cCode]['items2'] : array(),
                            'items2_sum' => isset($_SESSION[$cCode]['items2_sum']) ? $_SESSION[$cCode]['items2_sum'] : array(),
                            'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                            'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : array(),
                            'items3' => isset($_SESSION[$cCode]['items3']) ? $_SESSION[$cCode]['items3'] : array(),
                            'items3_sum' => isset($_SESSION[$cCode]['items3_sum']) ? $_SESSION[$cCode]['items3_sum'] : array(),
                            'items4' => isset($_SESSION[$cCode]['items4']) ? $_SESSION[$cCode]['items4'] : array(),
                            'items4_sum' => isset($_SESSION[$cCode]['items4_sum']) ? $_SESSION[$cCode]['items4_sum'] : array(),
                            'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                            'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                            'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                            'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                            'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                            'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),
                            'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                            'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                            'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                            'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                            'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                            'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                            'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                            'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                            'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                            'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                            'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                            'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                            'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                            'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                            'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                            'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                            'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                            'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                            "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                            "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                            "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                            "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                            "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                            "jurnal_index" => isset($jurnalIndex) ? $jurnalIndex : array(),
                            "postProcessor" => isset($jurnalPostProc) ? $jurnalPostProc : array(),
                            "preProcessor" => isset($jurnalPreProc) ? $jurnalPreProc : array(),
                            "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                            "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                            "items_noapprove" => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),
                            "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                            "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                            //----
                            'mainOriginal' => isset($_SESSION[$cCode]['mainOriginal']) ? $_SESSION[$cCode]['mainOriginal'] : array(),
                            'itemsOriginal' => isset($_SESSION[$cCode]['itemsOriginal']) ? $_SESSION[$cCode]['itemsOriginal'] : array(),
                            //----
                        );
                        $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
                        showLast_query("hijau");
                        cekHijau("SELESAI menjalankan REJECT ALL...");
                    }
                }
                else {
                    $tableIn_master['trash_4'] = 1;
                    $tableIn_master['deskripsi'] = "rejection";
                    $tableIn_master['cancel_dtime'] = date("Y-m-d H:i:s");
                    $tableIn_master['cancel_name'] = $this->session->login['nama'];
                    $tableIn_master['cancel_id'] = $this->session->login['id'];
                    $epID = $tr->writeMainEntries_entryPoint($no, $tableIn_master['id_master'], $tableIn_master);
                    $mongoList['main'][] = $epID;
                    showLast_query("pink");
                    if (isset($tableIn_detail) && sizeof($tableIn_detail) > 0) {
                        $insertIDs = array();
                        foreach ($tableIn_detail as $dSpec) {
                            if ($epID != 999) {
                                $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                                $mongoList['detail'] = $insertIDs;
                                showLast_query("pink2");
                            }
                        }
                    }
                }
            }
            // endregion menulis entry point


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

//mati_disini("jenisTr target $jenisTr_component");
            //rollback preproc, master
            if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'])) {
                $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['master'] : array();
                if (sizeof($iterator) > 0) {
                    $it = 0;
                    cekbiru("ada iterator pre-proc master");
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $it++;
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'] . "_reverse";
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                        $gateItems = $$srcGateName;

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


                        $subParams = array();

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

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

                            }

                            if (array_key_exists($oriComName, $prepConfigs)) {
                                if (sizeof($prepConfigs[$oriComName]) > 0) {
                                    foreach ($prepConfigs[$oriComName] as $key => $src) {
                                        $subParams['static'][$key] = makeValue($src, $gateItems, $gateItems, 0);
                                    }
                                }
                            }

                            if (!isset($subParams['static']["transaksi_id"])) {
                                $subParams['static']["transaksi_id"] = $no;
                            }


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


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


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

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


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

                    }
                }
            }
            else {
                cekbiru("TIDAK ada config pre-proc master $jenisTr :: $stepNumCurrent");
            }
            //rollback preproc, detail
            if (isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'])) {
                $iterator = isset($this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['preProcessor'][$jenisTr_component]['detail'] : array();
                if (sizeof($iterator) > 0) {
                    $it = 0;
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $it++;
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'] . "_reverse";
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $gateItems = $$srcGateName;

                        echo "reverse preproc (detail): $comName, initializing values <br>";
                        foreach ($gateItems as $xid => $dSpec) {
                            $tmpOutParams[$cCtr] = array();
                            //                        $id = $dSpec['id'];
                            $id = $xid;
                            $subParams = array();

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

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

                                }

                                if (array_key_exists($oriComName, $prepConfigs)) {
                                    cekhitam("terdapat di dalam prepConfig");
                                    if (sizeof($prepConfigs[$oriComName]) > 0) {
                                        foreach ($prepConfigs[$oriComName] as $key => $src) {
                                            $subParams['static'][$key] = makeValue($src, $gateItems[$id], $gateItems[$id], 0);
                                        }
                                    }
                                }
                                else {
                                    cekhitam("TIDAK terdapat di dalam prepConfig");
                                }
                                if (!isset($subParams['static']["transaksi_id"])) {
                                    $subParams['static']["transaksi_id"] = $no;
                                }


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

                            if (sizeof($subParams) > 0) {

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


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

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

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


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

                            if ($tobeExecuted) {

                                //                            arrprint($tmpOutParams[$cCtr]);

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

                                //                            cekbiru("gotparams");
                                //                            arrprint($gotParams);

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

                        }
                    }
                }
            }
            else {
                cekbiru("TIDAK ada config pre-proc detail $jenisTr :: $stepNumCurrent");
            }
            //rollback postproc, master
            if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'])) {
                $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['master'] : array();
                if (sizeof($iterator) > 0) {
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $gateItems = $$srcGateName;

                        echo "rollback main post-processor: $comName<br>";
                        if (!in_array($comName, $postDeniedConfigs)) {

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

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

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

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

                                }
                                if (!isset($tmpOutParams['static']["transaksi_id"])) {
                                    $tmpOutParams['static']["transaksi_id"] = $insertID;
                                }
                                if (!isset($tmpOutParams['static']["transaksi_no"])) {
                                    $tmpOutParams['static']["transaksi_no"] = $insertNum;
                                }

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


                            }
                            if (isset($tComSpec['static2'])) {

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

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

                                }
                                if (!isset($tmpOutParams['static2']["transaksi_id"])) {
                                    $tmpOutParams['static2']["transaksi_id"] = $insertID;
                                }
                                if (!isset($tmpOutParams['static2']["transaksi_no"])) {
                                    $tmpOutParams['static2']["transaksi_no"] = $insertNum;
                                }

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


                            }

                            if (array_key_exists($oriComName, $postConfigs)) {
                                if (sizeof($postConfigs[$oriComName]) > 0) {
                                    foreach ($postConfigs[$oriComName] as $key) {
                                        $oldVal = isset($tmpOutParams['static'][$key]) ? $tmpOutParams['static'][$key] : 0;
                                        cekbiru("oldVal: $oldVal");
                                        $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                        cekHijau("newVal: $newVal");
                                        $tmpOutParams['static'][$key] = $newVal;
                                    }
                                }
                            }


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

                            cekBiru("kiriman rollback main-postproc $comName");

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

                        }
                        else {
                            cekHitam("$comName denied");
                        }

                    }
                }
            }
            else {
                cekbiru("TIDAK ada config post-proc master $jenisTr :: $stepNumCurrent");
            }
            //rollback postproc, detail
            if (isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'])) {
                $iterator = isset($this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail']) ? $this->configCore[$jenisTr]['postProcessor'][$jenisTr_component]['detail'] : array();
                if (sizeof($iterator) > 0) {
                    cekHitam("cetak iterator :: $jenisTr :: $stepNumCurrent ||");
                    //                    arrPrintWebs($iterator);
                    $iteratorAdd = array();
                    foreach ($iterator as $cCtr => $tComSpec) {
                        if (isset($tComSpec['static']['state']) && ($tComSpec['static']['state'] == '.hold')) {
                            if (isset($tComSpec['static']['oleh_id']) && ($tComSpec['static']['oleh_id'] != '.0')) {
                                // bila state == .hold dan oleh_id != .0, maka dibuatkan ::
                                // HOLD, +QTY, oleh_id dan ACTIVE, -QTY
                                $tComSpecAddHold = $tComSpec;
                                $tComSpecAddActive = $tComSpec;
                                $staticReplaceHold = array(
                                    "jumlah" => "qty",
                                    "transaksi_no" => ".0",
                                );
                                $staticReplaceActive = array(
                                    "jumlah" => "-qty",
                                    "transaksi_id" => ".0",
                                    "nomer" => ".0",
                                    "state" => ".active",
                                    "oleh_id" => ".0",
                                    "oleh_nama" => "",
                                    "transaksi_no" => ".0",
                                );
                                foreach ($staticReplaceHold as $k_rpc => $v_rpc) {
                                    $tComSpecAddHold['static'][$k_rpc] = $v_rpc;
                                }
                                foreach ($staticReplaceActive as $k_rpc => $v_rpc) {
                                    $tComSpecAddActive['static'][$k_rpc] = $v_rpc;
                                }

                                $iteratorAdd[101] = $tComSpecAddHold; // postprocc hold by orang
                                $iteratorAdd[102] = $tComSpecAddActive; // postprocc active
                            }
                        }
                    }

                    if (sizeof($iteratorAdd) > 0) {
                        foreach ($iteratorAdd as $ii => $spec) {
                            $iterator[$ii] = $spec;
                        }
                    }
                    //                    arrPrintWebs($iterator);
                    //
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $oriComName = $tComSpec['comName'];
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $gateItems = $$srcGateName;

                        echo "rollback sub-postProcessor: $comName, initializing values <br>";
                        if (!in_array($comName, $postDeniedConfigs)) {

                            $tmpOutParams[$cCtr] = array();
                            foreach ($gateItems as $cnt => $dSpec) {

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

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

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

                                        $realValue = makeValue($value, $gateItems[$cnt], $gateItems[$cnt], 0);
                                        $subParams['static'][$key] = $realValue;

                                    }

                                    if (array_key_exists($oriComName, $postConfigs)) {

                                        if (sizeof($postConfigs[$oriComName]) > 0) {
                                            foreach ($postConfigs[$oriComName] as $key) {

                                                $oldVal = isset($subParams['static'][$key]) ? $subParams['static'][$key] : 0;
                                                $newVal = $oldVal < 0 ? abs($oldVal) : -($oldVal);
                                                $subParams['static'][$key] = $newVal;

                                            }
                                        }
                                    }
                                    else {
                                        //                                cekhitam("TIDAK terdapat di dalam prepConfig");
                                    }


                                    if (!isset($subParams['static']["transaksi_id"])) {
                                        $subParams['static']["transaksi_id"] = $no;
                                    }
                                    if (!isset($subParams['static']["transaksi_no"])) {
                                        $subParams['static']["transaksi_no"] = $no;
                                    }
                                    $subParams['static']["fulldate"] = date("Y-m-d");
                                    $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                    $subParams['static']["keterangan"] = "rollback of $no";
                                }


                                if (sizeof($subParams) > 0) {
                                    $tmpOutParams[$cCtr][] = $subParams;
                                }
                            }
                        }
                        else {
                            cekHitam("$comName denied");
                        }
                    }

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

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


                            cekBiru("kiriman rollback detail-postproc $comName");
                            arrPrint($tmpOutParams[$cCtr]);
                            $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        }
                        else {
                            cekHitam("$comName denied");
                        }
                    }
                }
            }
            else {
                cekbiru("TIDAK ada config post-proc detail $jenisTr :: $stepNumCurrent");
            }

            //            mati_disini();
            //==================================================================================================
            $this->load->model("Mdls/MdlTransaksiLaporan");
            $lt = New MdlTransaksiLaporan();
            $dataTransaksiLaporan = array(
                "transaksi_id" => $no,
                "master_id" => $masterID,
                "nomer" => $arrMainDataTransIDSpec['nomer'],
                "metode" => "reject",
            );
            $lt->addData($dataTransaksiLaporan);
            showLast_query("ungu");
        }


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


        //        arrPrint($mongListUpadte);
        //        arrPrint($mongoList);

//        mati_disini("DONE :: $cCode :: $jenisTr_con :: $stepNumCurrent");

        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");

        //region connect ke mongoDB
        $pakai_ini = 0;
        if ($pakai_ini == 1) {
            if (sizeof($mongListUpadte) > 0) {
                $mong = new MdlMongoMother();
                foreach ($mongListUpadte as $metode => $tmpData) {
                    if ($metode == "update") {
                        if (sizeof($tmpData) > 0) {
                            foreach ($tmpData as $gate => $fildsData) {
                                //                            arrPrint($fildsData);
                                $mong->setTableName($this->mongoTableList[$gate]);
                                foreach ($fildsData as $mongUpadte) {
                                    //                                    cekHitam("update ".$this->mongoTableList[$gate]);
                                    //                                    arrPrint( $mongUpadte['value']);
                                    //                                    arrPrintWebs($mongUpadte['where']);
                                    $mong->updateData($mongUpadte['where'], $mongUpadte['value']);
                                }
                            }
                        }
                    }

                }
            }
            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("ninsert into :".$this->mongoTableList[$gateList]);
                            //                        arrPrint($transksi_main);
                            $mong->addData($transksi_main);
                        }
                    }

                }
            }
        }

        //endregion


        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 doFollowup_old1_unused()
    {
        $ipadd = $_SERVER['REMOTE_ADDR'];
//        cekHijau($ipadd);
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

        $gmr = img_working();
        echo "\n" . 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'] : 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

            $tokoID = $_SESSION[$cCode]['main']['tokoID'];
            $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];
            $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

//        }


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

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


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

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

        // </editor-fold>
        //endregion

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


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

        //==tulis kloningan transaksi
        //region write entries
        if (sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {

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


            $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']['piutang_dagang']) && $_SESSION[$cCode]['main']['piutang_dagang'] > 0) {
                        // cekBiru($_SESSION[$cCode]['main']['piutang_dagang']);

                        $tr->writeDueDate($insertID, $dataDue);
                        // cekHitam($this->db->last_query());
                        // matiHEre($validateDue['allow_create']);
                    }
                }
                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) {
                    cekHItam($keyTarget . "[$valTarget] => " . $dueDate);
                    $_SESSION[$cCode]['main_elements'][$keyTarget][$valTarget] = $dueDate;
                    $_SESSION[$cCode]['main']['dueDate'] = $dueDate;
                }
            }
            // matiHEre(__LINE__." cek duedate writer");

            //------------
            if (isset($this->configValues[$this->jenisTr]['coreBuilder'][$jenisTrTarget]) && sizeof($this->configValues[$this->jenisTr]['coreBuilder'][$jenisTrTarget])) {
                $coreBuilder = $this->configValues[$this->jenisTr]['coreBuilder'][$jenisTrTarget];
            }
            else {
                $coreBuilder = array();
            }
            //------------

            $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(),
                "itemPrice_sum" => isset($_SESSION[$cCode]['itemPrice_sum']) ? $_SESSION[$cCode]['itemPrice_sum'] : array(),
                //-----
                "coreBuilder" => $coreBuilder,
                'diskon_event' => isset($_SESSION[$cCode]['diskon_event']) ? $_SESSION[$cCode]['diskon_event'] : array(),
                'cashback_event' => isset($_SESSION[$cCode]['cashback_event']) ? $_SESSION[$cCode]['cashback_event'] : 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) {
                        //----- kiriman gerbang
                        if (method_exists($m, "setTableInMaster")) {
                            $m->setTableInMaster($_SESSION[$cCode]["tableIn_master"]);
                        }
                        if (method_exists($m, "setDetail")) {
                            $m->setDetail($_SESSION[$cCode][$srcGateName]);
                        }
                        if (method_exists($m, "setJenisTr")) {
                            $m->setJenisTr($this->jenisTr);
                        }
                        //----- kiriman gerbang
                        $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__);
                        showLast_query("lime");
                    }
                    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);
                        //----- kiriman gerbang untuk counter mutasi rekening
                        if (method_exists($m, "setTableInMaster")) {
                            $m->setTableInMaster($_SESSION[$cCode]["tableIn_master"]);
                        }
                        if (method_exists($m, "setMain")) {
                            $m->setMain($_SESSION[$cCode]["main"]);
                        }
                        if (method_exists($m, "setJenisTr")) {
                            $m->setJenisTr($this->jenisTr);
                        }
                        //----- kiriman gerbang untuk counter mutasi rekening
                        $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'],
                            "toko_id" => $this->session->login['toko_id'],
                            "toko_nama" => $this->session->login['toko_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,
                            "seller_id" => (isset($externSrc['seller_id']) && ($_SESSION[$cCode]['main'][$externSrc['seller_id']])) ? $_SESSION[$cCode]['main'][$externSrc['seller_id']] : "",
                            "seller_nama" => (isset($externSrc['seller_nama']) && ($_SESSION[$cCode]['main'][$externSrc['seller_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['seller_nama']] : "",
                            "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']] : "",

                        );
                        $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'],
                        "toko_id" => $this->session->login['toko_id'],
                        "toko_nama" => $this->session->login['toko_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

        validateBalancesComparison("", $componentConfig);
        validateAllBalances($tokoID);
        //
        //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], $tokoID);

                }

                $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], $tokoID);

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

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


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

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

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

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

                //===cloning detail/items cabang1 ke cabang2
                //===yang direplace: sub_step_number, sub_step_current, sub_step_avail, next_substep_num, next_substep_code, next_substep_label, next_subgroup_code
                $detailReplacers = array(
                    "sub_step_avail" => sizeof($configUiMasterModulJenis['steps']),
                    "sub_step_current" => 1,
                    "sub_step_number" => 1,
                    "next_substep_num" => $_SESSION[$cCode]['tableIn_master']['next_step_num'],
                    "next_substep_code" => $_SESSION[$cCode]['tableIn_master']['next_step_code'],
                    "next_substep_label" => $_SESSION[$cCode]['tableIn_master']['next_step_label'],
                    "next_subgroup_code" => $_SESSION[$cCode]['tableIn_master']['next_group_code'],
                    //                    "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(),
                    "itemPrice_sum" => isset($_SESSION[$cCode]['itemPrice_sum']) ? $_SESSION[$cCode]['itemPrice_sum'] : array(),
                    //-----
                    "coreBuilder" => isset($coreBuilder) ? $coreBuilder : array(),
                    'diskon_event' => isset($_SESSION[$cCode]['diskon_event']) ? $_SESSION[$cCode]['diskon_event'] : array(),
                    'cashback_event' => isset($_SESSION[$cCode]['cashback_event']) ? $_SESSION[$cCode]['cashback_event'] : 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

        $pakai_ini = 0;
        if ($pakai_ini == 1) {

            //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
                                    $addData = array(
                                        "toko_id" => $tokoID,
                                        "toko_nama" => $tokoNama,
                                    );
                                    $paramKeyRaw = print_r($cParams, true);
                                    $paramValuesRaw = print_r($cValues[$i], true);
                                    $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                    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
                                        $addData = array(
                                            "toko_id" => $tokoID,
                                            "toko_nama" => $tokoNama,
                                        );
                                        $paramKeyRaw = print_r($cParams, true);
                                        $paramValuesRaw = print_r($cValues[$i], true);
                                        $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                                        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 -- $ipadd");
        if ($dieForDebug === true) {
            mati_disini(__FUNCTION__ . " *** under maintenance ***  <br> TUNGGU SEBENTAR YA... @" . __LINE__);
        }
        //region writelog
        echo "<script>top.writeProgress('sedang menulis ke log');</script>";
        $this->load->model("Mdls/" . "MdlActivityLog");
        $hTmp = new MdlActivityLog();
        $tmpHData = array(
            "title" => $_SESSION[$cCode]['main']['jenisTrName'],
            "sub_title" => "Saving followup process",
            "uid" => $this->session->login['id'],
            "uname" => $this->session->login['nama'],
            "dtime" => date("Y-m-d H:i:s"),
            "transaksi_id" => $insertID,
            "deskripsi_old" => "",
            "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
            "jenis" => $this->jenisTr,
            "ipadd" => $_SERVER['REMOTE_ADDR'],
            "devices" => $_SERVER['HTTP_USER_AGENT'],
            "category" => "transaksi",
            "controller" => $this->uri->segment(1),
            "method" => $this->uri->segment(2),
            "url" => current_url(),

        );
        $logID = $hTmp->addData($tmpHData, $hTmp->getTableName()) or die(lgShowError("Gagal menulis riwayat data", __FILE__));
        //endregion


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

//        mati_disini(__FUNCTION__ . "  TRANSAKSI BERHASIL (UNDER MAINTENANCE)  <br> silahkan tutup browser terlebih dahulu. <br>execute in " . $val . " ms");

        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");


        if (isset($_SESSION[$cCode])) {
            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 clearContent()
    {

        $jenisTr = $this->jenisTr;
        $cCode = $this->cCode;
        $modul = $this->modul;

        $_SESSION[$cCode] = null;
        unset($_SESSION[$cCode]);
        $initMasterValues = heInitMasterValues_he_cart($this->jenisTr, 1, $this->configUiJenis);
        heInitGates_he_cart($this->jenisTr, $initMasterValues);
        echo "<script>";
        echo "if(top.document.getElementById('shopping_cart')){";
        echo "top.getData('" . base_url() . "$modul/_shoppingCart/viewCart/" . $jenisTr . "?selID=0','shopping_cart');";
        echo "}";
        echo "</script>";
    }

    //reject transaksi no step
    public function viewReject()
    {
        // arrPrint($this->uri->segment_array());
        $this->load->model("MdlTransaksi");
        $id_x = $this->uri->segment(5);
        $tr = new MdlTransaksi();
        $this->registryFields = $tr->getRegistryFields();
        $tr->setFilters(array());
        $tr->addFIlter("id=$id_x");
        $tmp = $tr->lookupMainTransaksi()->result();
        showLast_query("biru");
        arrPrint($tmp);

        $jenisTr = $tmp[0]->jenis;
        $step = $tmp[0]->step_number;
        $jenis_master = $tmp[0]->jenis_master;
        $trash_4 = $tmp[0]->trash_4;
//        cekHitam(": $jenisTr : $step :");
        $configHederFields = isset($this->configUi[$jenisTr]['rejectMainField']) ? $this->configUi[$jenisTr]['rejectMainField'] : array();
        $configDetilFields = isset($this->configUi[$jenisTr]['rejectDetilField'][$step]) ? $this->configUi[$jenisTr]['rejectDetilField'][$step] : array();
        $configDetilSumFields = isset($this->configUi[$jenisTr]['shoppingCartSumFields'][$step]) ? $this->configUi[$jenisTr]['shoppingCartSumFields'][$step] : array();
        $configLayoutSumFields = isset($this->configLayout[$jenisTr]['receiptSumFields'][$step]) ? $this->configLayout[$jenisTr]['receiptSumFields'][$step] : array();

        $tr = new MdlTransaksi();
        $tr->setFilters(array());
//        $tr->addFilter("transaksi_id='$id_x'");
        $trReg = $tr->lookupBaseDataRegistries($id_x)->result();
//        arrPrint($trReg);
        if (sizeof($trReg) > 0) {
            foreach ($trReg as $regSpec) {
                foreach ($this->registryFields as $regField) {
                    $$regField = blobDecode($regSpec->$regField);
                }
            }
        }
// arrPrint($main);

        //---- VALIDASI TRANSAKSI YANG AKAN DIBATALKAN...
        $warning = array();
        $pembatalanValidateConfig = isset($this->config->item('heTransaksi_pembatalanValidate')[$jenis_master]) ? $this->config->item('heTransaksi_pembatalanValidate')[$jenis_master] : array();
        if (sizeof($pembatalanValidateConfig) > 0) {
            foreach ($pembatalanValidateConfig as $pembatalanSpec) {
                $mdlNameValidate = $pembatalanSpec['mdlName'];
                $mdlFilterValidate = isset($pembatalanSpec['mdlFilter']) ? $pembatalanSpec['mdlFilter'] : array();

                $this->load->model("Mdls/$mdlNameValidate");
                $mdl_v = New $mdlNameValidate();
                $mdl_v->setFilters(array());
                if (sizeof($mdlFilterValidate) > 0) {
                    $rslt = makeFilter($mdlFilterValidate, (array)$tmp[0], $mdl_v);
                }
                $validateTmp = $mdl_v->lookupAll()->result();
                showLast_query("biru");
                if (sizeof($validateTmp) > 0) {
                    $msg = $pembatalanSpec['label'];
                    cekHitam($msg);
                    $warning[] = $msg;
//                        die(lgShowAlert($msg));
                }
                if (isset($pembatalanSpec['detailCekQty']) && ($pembatalanSpec['detailCekQty'] == true)) {
                    $trs->setFilters(array());
                    $dTr = $trs->lookupDetailTransaksi($id)->result();
                    $totalOrdJml = 0;
                    $totalValidQty = 0;
                    foreach ($dTr as $dTrSpec) {
                        $totalOrdJml += $dTrSpec->produk_ord_jml;
                        $totalValidQty += $dTrSpec->valid_qty;
                    }
                    if ($totalOrdJml != $totalValidQty) {
                        $warning[] = $pembatalanSpec['label'];
//                            mati_disini($pembatalanSpec['label']);
                    }
                }
            }

        }

//cekPink($configDetilFields);
//cekPink($items);


        //region builder data
        $mainData = array();
        $itemData = array();
        $sumData = array();
        if (sizeof($configHederFields) > 0) {
            foreach ($configHederFields as $hKey => $hederFields) {
                $mainData[$hKey] = isset($main[$hKey]) ? $main[$hKey] : "";
            }
            if (sizeof($items) > 0) {
                foreach ($items as $PID => $pidData) {
                    foreach ($configDetilFields as $dKey => $dLabel) {
                        $itemData[$PID][$dKey] = isset($pidData[$dKey]) ? $pidData[$dKey] : "";
                    }
                }
            }
            else {
                cekMerah("tidak ada gerbang items");
            }
            $configSumFields = sizeof($configDetilSumFields) > 0 ? $configDetilSumFields : $configLayoutSumFields;
//            cekPink($configSumFields);
            foreach ($configSumFields as $sumKey => $sumLabel) {
                $sumData[$sumKey] = isset($main[$sumKey]) ? $main[$sumKey] : "";
            }
        }


        //reject link
        if ($trash_4 == 1) {
            $rejectLink = NULL;
        }
        else {
            $rejectLink = base_url() . $this->modul . "/" . get_class($this) . "/doReject/$jenisTr/$id_x";
        }

        //endregion


//cekKuning($mainData);
//cekKuning($items);
//cekKuning($itemData);
//cekKuning($sumData);


        $data = array(
            "mode" => $this->uri->segment(3),
            "title" => "",
            "headers" => array(),
            "mainHeaderField" => isset($configHederFields) ? $configHederFields : array(),
            "detailHeaderField" => isset($configDetilFields) ? $configDetilFields : array(),
            "sumLabelField" => isset($configSumFields) ? $configSumFields : array(),
            "mainData" => $mainData,
            "itemData" => $itemData,
            "sumData" => $sumData,
            "signStr" => "",
            "cabangData" => "",
            "urutCounter" => "",
            "underMaintenance" => underConstruction(),
            "rejectLink" => $rejectLink,
            "warning" => $warning,
        );
        $this->load->view("transaksi", $data);
    }

    //reject transaksi step habis
    public function doReject()
    {
        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();
        $this->load->model("MdlTransaksi");
        $this->load->model("Mdls/MdlRevertJurnal");
        $b = new MdlRevertJurnal();
        $tr = new MdlTransaksi();
        $registryFields = $tr->getRegistryFields();
//         arrPrint($this->uri->segment_array());

        $id = $transID_ref = $this->uri->segment(5);
        $jenisMaster = $this->uri->segment(4);
        $reject_target = isset($this->configUi[$jenisMaster]["rejectedTraget"]) ? $this->configUi[$jenisMaster]["rejectedTraget"] : matiHere("tidak di ijinkan melakukan pembatalan transaksi " . __LINE__);
        $rejectValidate = isset($this->configUi[$jenisMaster]["rejectValidate"]) ? $this->configUi[$jenisMaster]["rejectValidate"] : matiHere("komponen pembatalan tidak ditemukan, silahkan hubungi admin anda untuk memastikan kesalahan ini. refLine(" . __LINE__ . ") on date " . date("Y-m-d H:i"));
        $relOptionConfigs = isset($this->configUi[$jenisMaster]['relativeOptions']) ? $this->configUi[$this->jenisTr]['relativeOptions'] : array();
        $connecToRelation = isset($this->configUi[$jenisMaster]['connectTo']) ? $this->configUi[$jenisMaster]['connectTo'] : "";
        $this->jenisTr = $reject_target;
        $cCode = "_TR_" . $reject_target;

        cekMerah(":: " . $reject_target);

        //region pasang pihak extern
        $jr = new MdlRevertJurnal();
        $tmpJ = $jr->lookupByID($jenisMaster)->result();
        if (sizeof($tmpJ) > 0) {
            if (isset($this->configUi[$this->jenisTr]["pihakMainNota"]) && $this->configUi[$this->jenisTr]["pihakMainNota"] == true) {
                $selectColumn = "nomer";
            }
            else {
                $selectColumn = "nama";
            }
            $_SESSION[$cCode]['main']['pihakExternID'] = $jenisMaster;
            $_SESSION[$cCode]['main']['pihakExternMasterID'] = isset($tmpJ[0]->id_master) ? $tmpJ[0]->id_master : "";
            $_SESSION[$cCode]['main']['pihakExternName'] = isset($tmpJ[0]->$selectColumn) ? $tmpJ[0]->$selectColumn : "";
            $_SESSION[$cCode]['main']['pihakExternValueSrc'] = isset($tmpJ[0]->value_src) ? $tmpJ[0]->value_src : "";


        }
//         cekLime($this->db->last_query());
//         arrPrint($tmpJ);
        // matiHEre();
        //endregion

        $this->blackList = array(
            "jml", "qty",
        );
        $this->whitelist = array(
            "pihakExternID",
            "pihakExternMasterID",
            "pihakExternName",
            "pihakExternValueSrc",
            "pihakExternRevertStep",
            "pihakExternDetailGate",
        );
        foreach ($this->whitelist as $list) {
            $this->whitelistMain[$list] = isset($_SESSION[$cCode]['main'][$list]) ? $_SESSION[$cCode]['main'][$list] : "";
        }
//        arrPrintHijau($this->whitelist);
        // unset($_SESSION[$cCode]);
        //reset sesion dulu biar bersih
        if (isset($_SESSION[$cCode]['items']) && sizeof($_SESSION[$cCode]['items']) > 0) {
            // $detailResetList = array(
            //     "main",
            //     "items",
            //     "items2",
            //     "items2_sum",
            //     "items3",
            //     "items3_sum",
            //     "tableIn_detail",
            //     "tableIn_detail2",
            //     "tableIn_detail_values",
            //     "tableIn_detail2_sum",
            //     "tableIn_detail_values2_sum",
            //     "tableIn_detail_rsltItems",
            //     "tableIn_detail_values_rsltItems",
            //     "tableIn_detail_rsltItems2",
            //     "tableIn_detail_values_rsltItems2",
            //     "rsltItems",
            //     "rsltItems2",
            //     "items_komposisi",
            // );
            foreach ($registryFields as $sSName) {
                $_SESSION[$cCode][$sSName] = null;
                unset($_SESSION[$cCode]["$sSName"]);
            }
            if (isset($this->whitelistMain) && sizeof($this->whitelistMain) > 0) {
                foreach ($this->whitelistMain as $key => $val) {
                    if (!isset($_SESSION[$cCode]['main'][$key])) {
                        $_SESSION[$cCode]['main'][$key] = $val;
                    }
                }
            }
        }

        $referenceConfig = isset($this->configUi[$this->jenisTr]['referenceFields']) ? $this->configUi[$this->jenisTr]['referenceFields'] : null;
        //$externalConfig = isset($this->configCore[$referenceJenisTr]['externalValues']) ? $this->configCore[$referenceJenisTr]['externalValues'] : array();
        $itemsInjectorConfig = isset($this->configUi[$this->jenisTr]['itemsInjector']) ? $this->configUi[$this->jenisTr]['itemsInjector'] : array();
        $fifoValidate = $this->config->item('heTransaksi_pembatalanFifoValidate') != NULL ? $this->config->item('heTransaksi_pembatalanFifoValidate') : array();

        //------------------
        $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();
//        $runCoreAkunting = isset($this->configUi[$this->jenisTr]["steps"][$stepNum]["runCoreAkunting"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNum]["runCoreAkunting"] : false;
        //------------------


        // baca ulang transaksi sebelum di eksekusi
        $tr = new MdlTransaksi();
        $tr->setFilters(array());
        if (sizeof($rejectValidate) > 0) {
            foreach ($rejectValidate as $f) {
                $f_ex = explode("=", $f);
                if (!isset($f_ex[1])) {
                    $f_ey = explode(">", $f_ex[0]);
                    if (substr($f_ey[1], 0, 1) == ".") {
                        // $o->addFilter($f_ey[0] . ">'" . ltrim($f_ey[1], ".") . "'");
                        $tr->addFilter($f_ey[0] . ">'" . ltrim($f_ey[1], ".") . "'");
                    }
                    else {
                        if (isset($_SESSION[$cCode]['main'][$f_ey[1]])) {
                            // $o->addFilter($f_ey[0] . ">'" . $_SESSION[$cCode]['main'][$f_ey[1]] . "'");
                            $tr->addFilter($f_ey[0] . ">'" . $_SESSION[$cCode]['main'][$f_ey[1]] . "'");
                        }
                        else {
                            // $o->addFilter($f_ey[0] . ">0");
                            $tr->addFilter($f_ey[0] . ">0");
                        }
                    }
                }
                else {
                    if (substr($f_ex[1], 0, 1) == ".") {
                        $tr->addFilter($f_ex[0] . "='" . ltrim($f_ex[1], ".") . "'");
                    }
                    else {
                        if (isset($_SESSION[$cCode]['main'][$f_ex[1]])) {
                            // $o->addFilter($f_ex[0] . "='" . $_SESSION[$cCode]['main'][$f_ex[1]] . "'");
                            $tr->addFilter($f_ex[0] . "='" . $_SESSION[$cCode]['main'][$f_ex[1]] . "'");
                        }
                        else {
                            // $o->addFilter($f_ex[0] . "=''");
                            $tr->addFilter($f_ex[0] . "=''");
                        }

                    }
                }
            }
        }
        $tr->addFilter("id=$id");
        $tmp = $tr->lookupMainTransaksi()->result();
        cekHere($this->db->last_query());
//        arrPrint($tmp);
        // unset($_SESSION[$cCode]);
//         matiHEre();
        if (sizeof($tmp) > 0) {
            $tr = new MdlTransaksi();
            $tr->setFilters(array());
            $trReg = $tr->lookupBaseDataRegistries($id)->result();

            $itemPrice_sum = array();
            $masterAddFields = array();
            $itemsFields = array();
            $items2Fields = array();
            $rsltItems = array();
            $rsltItems2 = array();
            $masterAddValues = array();
            $tmpMasterInValues = array();
            $tmpDetailValues = array();
            $tmpDetail = array();
            $postProcessor = array();
            $preProcessor = array();
            $revert = array();
            $component = array();
            $coreBuilder = array();
            $masterMainFields = array();
            foreach ($tr->getRegistryFields() as $rKey) {
                switch ($rKey) {
                    case "main":
                        $masterMainFields = unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "master_add_fields":
                        $masterAddFields = unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "master_add_values":
                        $masterAddValues = unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "tableIn_detail":
//                        $tmpDetail = unserialize(base64_decode($trReg[0]->$rKey));
                        $_SESSION[$cCode][$rKey] = unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "tableIn_detail_values":
                        $tmpDetailValues = unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "tableIn_master_values":
                        $tmpMasterInValues = unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "items":
                        $itemsFields = unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "items2":
                        $items2Fields = $trReg[0]->$rKey == '' ? array() : unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "items2_sum":
                        $items2_sum = $trReg[0]->$rKey == '' ? array() : unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "rsltItems":
                        $rsltItems = $trReg[0]->$rKey == '' ? array() : unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "rsltItems2":
                        $rsltItems2 = $trReg[0]->$rKey == '' ? array() : unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "preProcessor":
                        $preProcessor = $trReg[0]->$rKey == '' ? array() : unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "postProcessor":
                        $postProcessor = $trReg[0]->$rKey == '' ? array() : unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "jurnal_index":
                        $component = $trReg[0]->$rKey == '' ? array() : unserialize(base64_decode($trReg[0]->$rKey));
                        break;
                    case "main_elements":
                        $_SESSION[$cCode][$rKey] = blobDecode($trReg[0]->$rKey);
                        // matihere("mainelemet");

                        break;
                    case "tableIn_master":
                        $_SESSION[$cCode][$rKey] = blobDecode($trReg[0]->$rKey);
                        break;
                    case "itemPrice_sum":
                        $_SESSION[$cCode][$rKey] = blobDecode($trReg[0]->$rKey);
                        break;
                    case "coreBuilder":
                        $coreBuilder = blobDecode($trReg[0]->$rKey);
                        break;
                }
            }
        }
//arrPrintWebs($_SESSION[$cCode]["coreBuilder"]);
        arrPrintWebs($tmp);
//mati_disini();
        $jenis_master = $tmp[0]->jenis_master;
        $tokoID = $masterMainFields['tokoID'];
        $tokoNama = $masterMainFields['tokoNama'];


        $pembatalanValidateConfig = isset($this->config->item('heTransaksi_pembatalanValidate')[$jenis_master]) ? $this->config->item('heTransaksi_pembatalanValidate')[$jenis_master] : array();
        if (sizeof($pembatalanValidateConfig) > 0) {
            foreach ($pembatalanValidateConfig as $pembatalanSpec) {
                $mdlNameValidate = $pembatalanSpec['mdlName'];
                $mdlFilterValidate = isset($pembatalanSpec['mdlFilter']) ? $pembatalanSpec['mdlFilter'] : array();
//cekHere(":: $mdlNameValidate ::");
                $this->load->model("Mdls/$mdlNameValidate");
                $mdl_v = New $mdlNameValidate();
                $mdl_v->setFilters(array());
                if (sizeof($mdlFilterValidate) > 0) {
                    // $tmpB dimana dibuatnya kok dipakai disini???
                    $rslt = makeFilter($mdlFilterValidate, (array)$tmpB[0], $mdl_v);
                }
                $validateTmp = $mdl_v->lookupAll()->result();

                if (sizeof($validateTmp) > 0) {
                    $msg = $pembatalanSpec['label'];
                    //                        cekHitam($msg);
                    die(lgShowAlert($msg));
                }
                if (isset($pembatalanSpec['detailCekQty']) && ($pembatalanSpec['detailCekQty'] == true)) {
                    $trs->setFilters(array());
                    $dTr = $trs->lookupDetailTransaksi($id)->result();
                    $totalOrdJml = 0;
                    $totalValidQty = 0;
                    foreach ($dTr as $dTrSpec) {
                        $totalOrdJml += $dTrSpec->produk_ord_jml;
                        $totalValidQty += $dTrSpec->valid_qty;
                    }
                    if ($totalOrdJml != $totalValidQty) {
                        mati_disini($pembatalanSpec['label']);
                    }
                }
            }

        }

        $_SESSION[$cCode]['main']['seluruhnya'] = true;
        $_SESSION[$cCode]['main']['referenceID'] = $id;
        $_SESSION[$cCode]['main']['referenceNomer'] = $masterMainFields['nomer'];
        $_SESSION[$cCode]['main']['referenceNomer_top'] = $tmp[0]->nomer_top;
        $_SESSION[$cCode]['main']['jenisTr_reference'] = $tmp[0]->jenis;
        $_SESSION[$cCode]['main']['referenceStepNumber'] = $tmp[0]->step_number;
        $_SESSION[$cCode]['main']['referenceID_top'] = $tmp[0]->id_top;
        $_SESSION[$cCode]['items'] = $itemsFields;


        // matiHEre(sizeof($items2Fields));
        if (sizeof($itemsFields) > 0) {
            foreach ($itemsFields as $key => $val) {
                $setVal = $_SESSION[$cCode]["items"][$key];
                foreach ($val as $keys => $val0) {
                    if (!isset($setVal[$keys])) {
                        $_SESSION[$cCode]["items"][$key][$keys] = $val0;
                    }
                }
            }
        }
        if (sizeof($masterAddFields) > 0) {
            foreach ($masterAddFields as $key => $value) {
                $_SESSION[$cCode]['main_add_fields'][$key] = $value;
                $_SESSION[$cCode]['main'][$key] = $value;

            }
        }
        if (sizeof($masterAddValues) > 0) {
            foreach ($masterAddValues as $key => $value) {
                $_SESSION[$cCode]['main_add_values'][$key] = $value;
                $_SESSION[$cCode]['main'][$key] = $value;

            }
        }
        if (sizeof($tmpMasterInValues) > 0) {
            $tmpInjectTablein_masterValues = array(
                "trash" => "0",
                "jenis_master" => $this->jenisTr,
                "jenis_top" => $this->jenisTr,
                "jenis" => $this->jenisTr,
                "jenis_label" => "settlement",
                "div_id" => $masterMainFields["divID"],
                "div_nama" => "default",
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow(),
                "olehID" => $this->session->login['id'],
                "olehName" => $this->session->login['nama'],
                "cabang_id" => $masterMainFields["placeID"],
                "cabang_nama" => $masterMainFields['placeName'],
                "transaksi_nilai" => $masterMainFields["nilai_cash"],
                "transaksi_jenis" => $this->jenisTr,
                "gudang_id" => $masterMainFields["gudangID"],
                "gudang_nama" => $masterMainFields['gudangName'],
                "gudang2_id" => $masterMainFields["gudangID"],
                "gudang2_nama" => $masterMainFields['gudangName'],
                "keterangan" => "",
                "cabang2_id" => $masterMainFields["placeID"],
                "cabang2_nama" => $masterMainFields["placeName"],
                "status_4" => "11",
                "trash_4" => "0",

            );
            $tmpInjectTablein_master = array(
                "gudang" => $masterMainFields["gudangID"],
                "harga" => $masterMainFields["nilai_cash"],
                "divID" => $masterMainFields["divID"],
                "subtotal" => $masterMainFields["nilai_cash"],
                "reference" => "0",
                "nilai_bayar" => "0",
                "note" => "0",
            );
            foreach ($tmpMasterInValues as $key => $value) {
                $_SESSION[$cCode]['main'][$key] = $value;

            }
            foreach ($tmpInjectTablein_master as $mvKey => $mvValues) {
                $_SESSION[$cCode]['main'][$mvKey] = $mvValues;
                $_SESSION[$cCode]['tableIn_master'][$mvKey] = $mvValues;
            }
            foreach ($tmpInjectTablein_masterValues as $tiKey => $tiValues) {
                $_SESSION[$cCode]["tableIn_master_values"][$tiKey] = $tiValues;
            }
        }
        if (sizeof($masterMainFields) > 0) {
            foreach ($masterMainFields as $key => $value) {
                if (!isset($_SESSION[$cCode]['main'][$key])) {
                    $_SESSION[$cCode]['main'][$key] = $value;
                }
            }
            //injec new ssion untuk replace jenis TR target
            unset($_SESSION[$cCode]["main"]["nomer"]);
            unset($_SESSION[$cCode]["main"]["transaksi_id"]);
            $mainInjector = array(
                "olehID" => $this->session->login['id'],
                "olehName" => $this->session->login['nama'],
//                "pihakID" => $this->session->login['id'],
//                "pihakName" => $this->session->login['nama'],
                "jenis" => $this->jenisTr,
                "transaksi_jenis" => $this->jenisTr,
                "next_step_code" => $this->jenisTr,
                "next_group_code" => "",
                "step_number" => "1",
                "step_current" => "1",
                "jenisTr" => $this->jenisTr,
                "jenisTrMaster" => $this->jenisTr,
                "jenisTrTop" => $this->jenisTr,
                "jenisTrName" => "settlement",
                "stepNumber" => "1",
                "stepCode" => $this->jenisTr,
                "dtime" => dtimeNow(),
                "fulldate" => dtimeNow(),
            );
            foreach ($mainInjector as $miKey => $miValue) {
                $_SESSION[$cCode]['main'][$miKey] = $miValue;
            }
        }
        if (sizeof($_SESSION[$cCode]['items']) > 0) {
            $_SESSION[$cCode]['main']['harga'] = 0;
            foreach ($_SESSION[$cCode]['items'] as $id => $iSpec) {
                $_SESSION[$cCode]['main']['harga'] += ($iSpec['jml'] * $iSpec['harga']);

            }
        }
        if (sizeof($items2Fields) > 0) {
            foreach ($items2Fields as $key => $value) {
                $_SESSION[$cCode]['items2'][$key] = $value;
            }
        }
        if (sizeof($items2_sum) > 0) {
            foreach ($items2_sum as $key => $value) {
                $_SESSION[$cCode]['items2_sum'][$key] = $value;
            }
        }
        if (sizeof($rsltItems) > 0) {
            foreach ($rsltItems as $key => $value) {
                $_SESSION[$cCode]['rsltItems'][$key] = $value;
            }
        }
        if (sizeof($rsltItems2) > 0) {
            foreach ($rsltItems2 as $key => $value) {
                $_SESSION[$cCode]['rsltItems2'][$key] = $value;
            }
        }
//        arrPrint($component);


        $currentStepNum = 1;
        $stepNumber = 1;


        //region fetch jurnalconfig
        $revertedCoreBuilder = fetchRevertCoreBuilder($masterMainFields["jenisTrMaster"], $coreBuilder);
//        $revertedJurnal = fetchRevertJurnal($masterMainFields["jenisTrMaster"], $masterMainFields["step_number"], $component);
        $revertPostProc = fetchRevertPostProc($masterMainFields["jenisTrMaster"], $masterMainFields["step_number"], $postProcessor);
        $revertPaymentSrc = fetchRevertPaymentSrc($masterMainFields["jenis"], $masterMainFields["step_number"], $masterMainFields["transaksi_id"]);
        $swapcomFifo = fetchSwapComFifo($masterMainFields["jenisTrMaster"], $masterMainFields["step_number"]);
        $swapPreFifo = fetchSwapPreFifo($masterMainFields["jenisTrMaster"], $masterMainFields["step_number"]);
        // $swapPreFifoMain = fetchSwapPreFifoMain($masterMainFields["jenisTrMaster"], $masterMainFields["step_number"], $preProcessor['master']);

//arrPrintWebs($revertPostProc);
//matiHEre();

        $preProcc = array(
            "master" => array(
                // rekening koran
                array(
                    "comName" => "RekeningKoranPembatalan",
                    "loop" => array(),
                    "static" => array(
                        "cabang_id" => "placeID",
                        "state" => ".active",
                        "extern_id" => "cash_account",
                        "extern_nama" => "cash_account__label",
                        "nilai" => "nilai_entry",
                        "method" => "cashMethode", // cash method yang dipilih
                        "jenis" => ".hutang bank",

                        "jenisTr" => "jenisTr",
                    ),
                    "resultParams" => array(
                        "main" => array(
                            "nilai_cash" => "nilai_cash",
                            "nilai_koran" => "nilai_koran",
                            "nilai_cash_full" => "nilai_cash_full",
                            "nilai_koran_full" => "nilai_koran_full",
                        ),
                    ),
                    "srcGateName" => "main",
                    "srcRawGateName" => "main",
                ),
            ),
        );


        if (sizeof($swapcomFifo) > 0) {

            $jenisTr_reference = $_SESSION[$cCode]['main']['jenisTr_reference'];
            $jenisException = $this->config->item('heTransaksi_revertJenisException') != null ? $this->config->item('heTransaksi_revertJenisException') : array();
//arrPrintWebs($jenisException);
//cekBiru($jenisTr_reference);
            if (!in_array($jenisTr_reference, $jenisException)) {

                if (isset($swapcomFifo['detail']) && sizeof($swapcomFifo['detail']) > 0) {
                    foreach ($revertedJurnal as $main => $mainVal) {
                        $loop = array();
                        foreach ($mainVal as $key => $ValDetails) {
                            if (isset($ValDetails["comName"]) && $ValDetails["comName"] == "Jurnal") {
                                if (isset($ValDetails["loop"]) && !array_key_exists("hutang lain ppv", $ValDetails["loop"])) {

//                                    $revertedJurnal[$main][$key]['loop']['selisih persediaan karena fifo'] = "selisih";//"(hpp+ppn)-nett"
                                }
                            }
                            if (isset($ValDetails["comName"]) && $ValDetails["comName"] == "Rekening") {
                                if (isset($ValDetails["loop"]) && !array_key_exists("hutang lain ppv", $ValDetails["loop"])) {

//                                    $revertedJurnal[$main][$key]['loop']['selisih persediaan karena fifo'] = "selisih";//"(hpp+ppn)-nett"
                                }
                            }
                        }
                    }
                }
            }

            //arrPrintWebs($revertedJurnal);
            //            arrPrintWebs($swapcomFifo);
            foreach ($swapcomFifo as $gate => $spec) {
                foreach ($spec as $ii => $subSpec) {
                    $preProcc[$gate][$ii] = $subSpec;
                }
            }
        }

        if (sizeof($swapPreFifo) > 0) {

            foreach ($swapPreFifo as $gate => $swapPreFifoSpec) {

                foreach ($swapPreFifoSpec as $spec) {
                    $revertedJurnal[$gate][] = $spec;
                }
            }
        }

        if (sizeof($revertedCoreBuilder) > 0) {
            $_SESSION[$cCode]['coreBuilder'] = $revertedCoreBuilder;
        }
        else {
            $_SESSION[$cCode]['coreBuilder'] = array();
        }

        //        mati_disini("MAINTENANCE");
//        if (sizeof($revertedJurnal) > 0) {
//            if (isset($revertedJurnal['master'])) {
//                krsort($revertedJurnal['master']);
//            }
//            if (isset($revertedJurnal['detail'])) {
//                krsort($revertedJurnal['detail']);
//            }
//        }

        //        arrPrintWebs($revertPostProc);
        //        mati_disini();
        //        cekPink2("preprocc");
        //        arrPrintWebs($preProcc);
        //        cekPink("postprocc");
        //        arrPrintWebs($swapPreFifoMain);
        //        cekPink2("cetak reverted");
        //        arrPrint($preProcc);
        //        cekPink2("cetak reverted post procc");
        //        arrPrintWebs($revertPostProc);
//        arrPrintWebs($component);
//        arrPrintWebs($coreBuilder);
//        arrPrintKuning($revertedCoreBuilder);
//                mati_disini();

        $revertedJurnal = $component;
        $_SESSION[$cCode]["revert"]["jurnal"] = $revertedJurnal;
        $_SESSION[$cCode]["revert"]["postProc"] = $revertPostProc;
        $_SESSION[$cCode]["revert"]["connectedPaymentsource"] = $revertPaymentSrc;
        $_SESSION[$cCode]["revert"]["preProc"] = $preProcc;


        if (isset($this->whitelistMain) && sizeof($this->whitelistMain) > 0) {
            foreach ($this->whitelistMain as $key => $val) {
                if (isset($_SESSION[$cCode]['main'][$val])) {
                    $_SESSION[$cCode]['main']['nilai_cancel'] = $_SESSION[$cCode]['main'][$val];
                }
            }
        }
        $nextProp = array();
        if (isset($_SESSION[$cCode]['main']['pihakExternRevertStep']) && ($_SESSION[$cCode]['main']['pihakExternRevertStep'] == true)) {
            $pihakExternMasterID = isset($_SESSION[$cCode]['main']['pihakExternMasterID']) ? $_SESSION[$cCode]['main']['pihakExternMasterID'] : 0;
            $stepsConfig = isset($this->configUi[$pihakExternMasterID]['steps']) ? $this->configUi[$pihakExternMasterID]['steps'] : array();
            $maxStep = sizeof($stepsConfig);
            if ($maxStep > 0) {
                $stepNum = $_SESSION[$cCode]['main']['referenceStepNumber'] - 1;
                $nextStepNum = $_SESSION[$cCode]['main']['referenceStepNumber'];
                $nextProp = array(
                    "step_num" => $stepNum,
                    "num" => $nextStepNum,
                    "code" => $this->configUi[$pihakExternMasterID]['steps'][$nextStepNum]['target'],
                    "label" => $this->configUi[$pihakExternMasterID]['steps'][$nextStepNum]['label'],
                    "groupID" => $this->configUi[$pihakExternMasterID]['steps'][$nextStepNum]['userGroup'],
                    "trID" => isset($_SESSION[$cCode]['main']['referenceID_top']) ? $_SESSION[$cCode]['main']['referenceID_top'] : 0,
                    "detailGate" => isset($_SESSION[$cCode]['main']['pihakExternDetailGate']) ? $_SESSION[$cCode]['main']['pihakExternDetailGate'] : "",
                );

            }
        }
        $_SESSION[$cCode]['main']['referenceNextProp'] = $nextProp;
        //endregion


//arrPrintKuning($this->configCore[$this->jenisTr]);
//mati_disini($this->jenisTr);

        $this->load->helper("he_value_builder");
        fillValues_he_value_builder($this->jenisTr, $currentStepNum, $stepNumber, $this->configCore[$this->jenisTr], $this->configUi[$this->jenisTr], $this->configValues[$this->jenisTr]);


//arrprint($_SESSION[$cCode]['main']);
//arrprint($_SESSION[$cCode]['items']);
//mati_disini();

        if (sizeof($_SESSION[$cCode]) > 0) {
            if (!isset($_SESSION[$cCode]['items'])) {
                die("belum ada item yang dipilih");
            }
            else {
                if (sizeof($_SESSION[$cCode]['items']) < 1) {
                    die("belum ada item yang dipilih");
                }
            }
            echo("now processing your transaction..<br>");


            //region build table rekening
            //            $buildTablesMaster = isset($this->configCore[$this->jenisTr]['components'][1]['master']) ? $this->configCore[$this->jenisTr]['components'][1]['master'] : array();
            if (isset($_SESSION[$cCode]['componentsBuilder'][1]['master'])) {
                // $buildTablesMaster = $_SESSION[$cCode]['componentsBuilder'][1]['master'];
                //upate builder main
                if (isset($this->configCore[$this->jenisTr]['componentsFixed'][1]['main'])) {
                    $masterInjector = $this->configCore[$this->jenisTr]['componentsFixed'][1]['main'];
                    // arrPrint($_SESSION[$cCode]['componentsBuilder'][1]['master']);
                    // arrPrint($masterInjector);
                    foreach ($_SESSION[$cCode]['componentsBuilder'][1]['master'] as $ix => $ixDatas) {
                        // arrPrint($ixDatas);
                        $keyCom = $ixDatas['comName'];
                        if (isset($masterInjector[$keyCom])) {
                            $valLoop = $masterInjector[$keyCom]['loop'];
                            foreach ($valLoop as $mKey => $mValues) {
                                if (!isset($_SESSION[$cCode]['componentsBuilder'][1]['master'][$ix]['loop'][$mKey])) {
                                    $_SESSION[$cCode]['componentsBuilder'][1]['master'][$ix]['loop'][$mKey] = $mValues;
                                }
                            }
                            // arrPrint($valLoop);

                            // cekMerah($keyCom);
                        }
                    }
                }
                $buildTablesMaster = $_SESSION[$cCode]['componentsBuilder'][1]['master'];

            }
            elseif (isset($this->configCore[$this->jenisTr]['components'][1]['master'])) {
                $buildTablesMaster = $this->configCore[$this->jenisTr]['components'][1]['master'];
            }
            else {
                $buildTablesMaster = array();
            }
            // matiHEre("LINE ".__LINE__);
            //---------------------------------------
            //            $buildTablesDetail = isset($this->configCore[$this->jenisTr]['components'][1]['detail']) ? $this->configCore[$this->jenisTr]['components'][1]['detail'] : array();
            if (isset($_SESSION[$cCode]['componentsBuilder'][1]['detail'])) {

                //tambahain param forcer untuk inject dari config core
                if (isset($this->configCore[$this->jenisTr]['componentsFixed'][1]['detail'])) {
                    $itemsInjector = $this->configCore[$this->jenisTr]['componentsFixed'][1];
                    $gateValues = $_SESSION[$cCode]['main'];
                    if (!isset($this->configCore[$this->jenisTr]['componentsFixed'][1]['paramKey'])) {
                        matiHEre("paramkey not found!! on line" . __LINE__);
                    }
                    //inject ke componentbuilder detail
                    $paramKey = $itemsInjector['paramKey'];
                    $_SESSION[$cCode]['main']['paramKey'] = $paramKey;//tulis param dulu suapya bisa dibaca items
                    $dataInt = array();
                    unset($_SESSION[$cCode]['componentsBuilder'][1]['detail'][$paramKey]);
                    if (!isset($_SESSION[$cCode]['componentsBuilder'][1]['detail'][$paramKey])) {
                        $_SESSION[$cCode]['componentsBuilder'][1]['detail'][$paramKey] = $itemsInjector['detail'][$paramKey];
                    }
                    //lanjut inject builder items
                    // arrPrint($gateValues);
                    $itemsToInject = array();
                    unset($_SESSION[$cCode]['items'][$paramKey]);
                    // matiHEre();
                    foreach ($itemsInjector['items'][$paramKey] as $iKeyParam => $iValueParam) {
                        // ceklIme($iValueParam);
                        $itemsToInject[$iKeyParam] = isset($gateValues[$iValueParam]) ? $gateValues[$iValueParam] : $iValueParam;
                    }
                    // arrPrint($itemsToInject);
                    if (!isset($_SESSION[$cCode]['items'][$paramKey])) {
                        $_SESSION[$cCode]['items'][$paramKey] = $itemsToInject;
                    }

                    // matiHEre('ayo di inject ke details');
                }
                $buildTablesDetail = $_SESSION[$cCode]['componentsBuilder'][1]['detail'];
            }
            elseif (isset($this->configCore[$this->jenisTr]['components'][1]['detail'])) {
                $buildTablesDetail = $this->configCore[$this->jenisTr]['components'][1]['detail'];
            }
            else {
                $buildTablesDetail = array();
            }

            // matiHEre();
            $addMasterTables = array(
                "rugilaba",
                "laba ditahan",
                "rugilaba lain lain",
            );
            foreach ($addMasterTables as $trek) {
                $buildTablesMaster[] = array(
                    "comName" => "RugiLaba",
                    "loop" => array(
                        "$trek" => .0,
                    ),
                );
            }
            if (sizeof($buildTablesMaster) > 0) {
                //                arrprint($buildTablesMaster);
                $bCtr = 0;
                foreach ($buildTablesMaster as $buildTablesMaster_specs) {

                    $bCtr++;
                    $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;

                    $this->load->model("Coms/" . $mdlName);
                    $m = new $mdlName();


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


                    if (method_exists($m, "getTableNameMaster")) {
                        if (sizeof($m->getTableNameMaster())) {
                            $m->buildTables($buildTablesMaster_specs);
                        }
                    }
                }
            }
            // arrprint($buildTablesDetail);
            if (sizeof($buildTablesDetail) > 0) {
                foreach ($buildTablesDetail as $buildTablesDetail_specs) {
                    foreach ($_SESSION[$cCode]['items'] as $itemSpec) {
                        //arrPrint($itemSpec);
                        $mdlName = $buildTablesDetail_specs['comName'];
                        cekLime($mdlName);
                        if (substr($mdlName, 0, 1) == "{") {
                            $mdlName = trim($mdlName, "{");
                            $mdlName = trim($mdlName, "}");
                            $mdlName = str_replace($mdlName, $itemSpec[$mdlName], $mdlName);
                            //                        $mdlName = str_replace($mdlName, $_SESSION[$cCode]['main'][$mdlName], $mdlName);
                        }
                        $mdlName = "Com" . $mdlName;
                        cekbiru("model: $mdlName");
                        $this->load->model("Coms/" . $mdlName);
                        $m = new $mdlName();

                        if (isset($buildTablesDetail_specs['loop']) && sizeof($buildTablesDetail_specs['loop']) > 0) {
                            foreach ($buildTablesDetail_specs['loop'] as $key => $val) {
                                if (substr($key, 0, 1) == "{") {
                                    $oldParam = $buildTablesDetail_specs['loop'][$key];
                                    unset($buildTablesDetail_specs['loop'][$key]);
                                    $key = trim($key, "{");
                                    $key = trim($key, "}");
                                    $key = str_replace($key, $itemSpec[$key], $key);
                                    //                                    $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
                                    $buildTablesDetail_specs['loop'][$key] = $oldParam;
                                }
                            }
                        }
                        if (method_exists($m, "getTableNameMaster")) {
                            if (sizeof($m->getTableNameMaster())) {
                                $m->buildTables($buildTablesDetail_specs);
                            }
                        }
                    }
                }
            }
            //endregion

            $this->db->trans_start();


            //region pre-processors (master)
            if (isset($this->configValues[$this->jenisTr]['relativeComponets']) && $this->configValues[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['preProc']['master']) ? $_SESSION[$cCode]['revert']['preProc']['master'] : array();
            }
            else {
                $iterator = isset($this->configValues[$this->jenisTr]['preProcessor'][1]['master']) ? $this->configValues[$this->jenisTr]['preProcessor'][1]['master'] : array();
            }
            //            if (isset($this->configCore[$this->jenisTr]['preProcessor'][1]['master'])) {
            if (sizeof($iterator) > 0) {
                //                $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][1]['master']) ? $this->configCore[$this->jenisTr]['preProcessor'][1]['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();
                        $subParams = array();

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

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

                            }

                            if (!isset($subParams['static']["transaksi_id"])) {
                                //									$subParams['static']["transaksi_id"] = $masterID;
                            }

                            $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'][1]['label'] . " oleh " . $this->session->login['nama'];
                        }
                        $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(0, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $gotParams = $m->exec();

                            cekbiru("gotparams dari pre-proc $comName");
                            arrprint($gotParams);

                            if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                                foreach ($gotParams as $gateName => $gSpec) {
                                    //										$id=$gSpec['id'];
                                    if (isset($_SESSION[$cCode]['main'])) {
                                        if (is_array($gSpec) && sizeof($gSpec) > 0) {
                                            foreach ($gSpec as $key => $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;
                                            }
                                        }
                                    }
                                    //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]['main'][$key])) {
                                                $_SESSION[$cCode]['main']['sub_' . $key] = ($_SESSION[$cCode]['main']['jml'] * $_SESSION[$cCode]['main'][$key]);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        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, 1, 1, $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);
            }
            else {
                echo("no processor defined. skipping preprocessor..<br>");
            }
            //endregion


            //region pre-processors (item)
            if (isset($this->configValues[$this->jenisTr]['relativeComponets']) && $this->configValues[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['preProc']['detail']) ? $_SESSION[$cCode]['revert']['preProc']['detail'] : array();
            }
            else {
                $iterator = isset($this->configValues[$this->jenisTr]['preProcessor'][1]['detail']) ? $this->configValues[$this->jenisTr]['preProcessor'][1]['detail'] : array();
            }
            //            if (isset($this->configCore[$this->jenisTr]['preProcessor'][1]['detail'])) {
            if (sizeof($iterator) > 0) {
                //                $procList = $this->configCore[$this->jenisTr]['preProcessor'][1];

                //                $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][1]['detail']) ? $this->configCore[$this->jenisTr]['preProcessor'][1]['detail'] : array();
                $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields']) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'] : array();
                echo "ITEM NUM LABELS";

                if (sizeof($iterator) > 0) {
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];

                        echo "sub-preproc: $comName, initializing values <br>";
                        // arrprint($_SESSION[$cCode][$srcGateName]);
                        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($subParams['static']["transaksi_id"])) {
                                    //									$subParams['static']["transaksi_id"] = $masterID;
                                }


                                $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'][1]['label'] . " oleh " . $this->session->login['nama'];
                            }
                            cekLime(":: cetak preprocc... $comName :: $srcGateName ::");
                            // arrPrint($subParams);
                            // mati_disini();
                            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 #: $comName, sending values <br>";

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


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

                                    cekmerah("gotparams dari pre-proc $comName");


                                    if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor

                                        foreach ($gotParams as $gateName => $paramSpec) {
                                            cekBiru(":: getParams inject ke $gateName ::");
                                            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) {
                                                            cekHere(":: injecte ke $gateName, ::: $key diisi dengan $val");
                                                            $_SESSION[$cCode][$gateName][$id][$key] = $val;
                                                        }

                                                    }
                                                }
                                                //==inject gotParams to child gate
                                                cekHitam("srcGateName = $srcGateName :: " . __LINE__);
                                                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");
                                                        if (isset($_SESSION[$cCode][$gateName][$id][$key])) {
                                                            $_SESSION[$cCode][$gateName][$id]['sub_' . $key] = ($_SESSION[$cCode][$gateName][$id]['jml'] * $_SESSION[$cCode][$gateName][$id][$key]);
                                                        }
                                                        //                                        die();
                                                    }
                                                }
                                            }
                                            //                                    arrPrint($items);die();
                                        }


                                    }

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


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

                // mati_disini();
                $this->load->helper("he_value_builder");
                fillValues_he_value_builder($this->jenisTr, 1, 1, $this->configCoreJenis, $this->configUiJenis, $this->configValuesJenis);
                //region injector gerbang value untuk pembatalan ppv dan selisih
                if (isset($_SESSION[$cCode]["revert"]["preProc"]["replacer"])) {
                    $replace = $_SESSION[$cCode]["revert"]["preProc"]["replacer"];
                    //                    $mainVAl = $_SESSION[$cCode]["main"]["hpp"];
                    //                    $indexVal =$_SESSION[$cCode]["main"]["ppv_index__nilai"];
                    //                    $valRiil = $mainVAl/$indexVal;
                    //                    $ppv_nilai = $mainVAl-$valRiil;
                    $tempCalculate = array(
                        "selisih" => ($_SESSION[$cCode]["main"]["hpp"] + $_SESSION[$cCode]["main"]["ppn"]) - ($_SESSION[$cCode]["main"]["nett"] + $_SESSION[$cCode]["main"]["ppv"]),
                        "hpp_nppv" => $_SESSION[$cCode]["main"]["hpp"],
                        "hpp_nppn" => $_SESSION[$cCode]["main"]["hpp"] + $_SESSION[$cCode]["main"]["ppn"],
                    );

                    foreach ($replace['recalculate'] as $iKey => $gate) {
                        $_SESSION[$cCode]["main"][$gate] = $tempCalculate[$gate];
                    }

                    CekLime($_SESSION[$cCode]["main"]["hpp"] . "+" . $_SESSION[$cCode]["main"]["ppn"] . "-" . $_SESSION[$cCode]["main"]["nett"]);
                    //                    CekLime($mainVAl."-".$ppv_nilai."=".$ppv_nilai);

                }

                //endregion

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


            // $this->unionValidate();
            //===finalisasi sebelum masuk tabel beneran
            //===isinya ada pembentukan nomor nota dll
            cekHitam("cek line:: " . __LINE__);

            //
            //region penomoran receipt
            //<editor-fold desc="==========penomoran">
            $this->load->model("CustomCounter");
            $cn = new CustomCounter("transaksi");
            $cn->setType("transaksi");
            cekHitam("::: " . $this->jenisTr);
//arrPrintKuning($this->configCore);
            $counterForNumber = array($this->configCore[$this->jenisTr]['formatNota']);
            if (!in_array($counterForNumber[0], $this->configCore[$this->jenisTr]['counters'])) {
                die(__LINE__ . " Used number should be registered in 'counters' config as well");
            }
            echo "<div style='background:#ff7766;'>";
            foreach ($counterForNumber as $i => $cRawParams) {
                $cParams = explode("|", $cRawParams);
                $cValues = array();
                foreach ($cParams as $param) {
                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                }
                $cRawValues = implode("|", $cValues[$i]);
                $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);

            }
            echo "</div style='background:#ff7766;'>";

            $stepNumber = 1;
            $tmpNomorNota = $paramSpec['paramString'];
            $tmpNomorNota_alias = formatField("nomer_nolink", $paramSpec['paramString']);


            if (isset($this->configUi[$this->jenisTr]['steps'][2])) {
                $nextProp = array(
                    "num" => 2,
                    "code" => $this->configUi[$this->jenisTr]['steps'][2]['target'],
                    "label" => $this->configUi[$this->jenisTr]['steps'][2]['label'],
                    "groupID" => $this->configUi[$this->jenisTr]['steps'][2]['userGroup'],
                );
            }
            else {
                $nextProp = array(
                    "num" => 0,
                    "code" => "",
                    "label" => "",
                    "groupID" => "",
                );
            }

            //</editor-fold>
            //endregion
            //
            //region dynamic counters
            // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
            $cn = new CustomCounter("transaksi");
            $cn->setType("transaksi");
            $configCustomParams = $this->configCore[$this->jenisTr]['counters'];
            $configCustomParams[] = "stepCode";
//            arrPrint($configCustomParams);
            if (sizeof($configCustomParams) > 0) {
                $cContent = array();
                foreach ($configCustomParams as $i => $cRawParams) {
                    $cParams = explode("|", $cRawParams);
                    $cValues = array();
                    foreach ($cParams as $param) {
                        $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                    }
                    $cRawValues = implode("|", $cValues[$i]);
                    $paramSpec = $cn->getNewCount($cParams, $cValues[$i], $tokoID);
                    showLast_query("pink");
//                    arrPrintPink($paramSpec);
//                    cekBiru("nomer nota: $tmpNomorNota");
                    $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                    switch ($paramSpec['id']) {
                        case 0: //===counter type is new
                            $addData = array(
                                "toko_id" => $tokoID,
                                "toko_nama" => $tokoNama,
                            );
                            $paramKeyRaw = print_r($cParams, true);
                            $paramValuesRaw = print_r($cValues[$i], true);
                            $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw, $addData);
                            break;
                        default: //===counter to be updated
                            $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                            break;
                    }
                    //echo "<hr>";
                }
            }
            $appliedCounters = base64_encode(serialize($cContent));
            $appliedCounters_inText = print_r($cContent, true);
            //mati_disini();

            //
            //region addition on master

            $addValues = array(
                'counters' => $appliedCounters,
                'counters_intext' => $appliedCounters_inText,
                'nomer' => $tmpNomorNota,
                'dtime' => date("Y-m-d H:i:s"),
                'fulldate' => date("Y-m-d"),
                "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                "step_number" => 1,
                "step_current" => 1,
                "next_step_num" => $nextProp['num'],
                "next_step_code" => $nextProp['code'],
                "next_step_label" => $nextProp['label'],
                "next_group_code" => $nextProp['groupID'],
                "tail_number" => 1,
                "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


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

            //
            //region addition on detail
            $addSubValues = array(
                "sub_step_number" => 1,
                "sub_step_current" => 1,
                "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                "next_substep_num" => $nextProp['num'],
                "next_substep_code" => $nextProp['code'],
                "next_substep_label" => $nextProp['label'],
                "next_subgroup_code" => $nextProp['groupID'],
                "sub_tail_number" => 1,
                "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


            );
            foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                foreach ($addSubValues as $key => $val) {
                    $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                }
            }
            //endregion

            //endregion

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


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

            //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
            if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {

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


                $tr = new MdlTransaksi();
                $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                showLast_query("lime");
                $epID = $tr->writeMainEntries_entryPoint($insertID, $insertID, $_SESSION[$cCode]['tableIn_master']);
                $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                // matiHere($insertNum);
                $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                if ($insertID < 1) {
                    die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                }
                //==transaksi_id dan nomor nota diinject kan ke gate utama
                $injectors = array(
                    "transaksi_id" => $insertID,
                    "nomer" => $tmpNomorNota,
                    "nomer_alias" => $tmpNomorNota_alias,
                );
                $arrInjectorsTarget = array(
                    "items",
                    "items2_sum",
                    "rsltItems",
                );
                foreach ($injectors as $key => $val) {
                    $_SESSION[$cCode]['main'][$key] = $val;
                    foreach ($arrInjectorsTarget as $target) {
                        if (isset($_SESSION[$cCode][$target])) {
                            foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                if (isset($_SESSION[$cCode][$target][$id])) {
                                    $_SESSION[$cCode][$target][$id][$key] = $val;
                                }
                            }
                        }
                    }
                }

                //===signature
                $dwsign = $tr->writeSignature($insertID, array(
                    "nomer" => $_SESSION[$cCode]['main']['nomer'],
                    "step_number" => 1,
                    "step_code" => $this->jenisTr,
                    "step_name" => $this->configUi[$this->jenisTr]['steps'][1]['label'],
                    "group_code" => $this->configUi[$this->jenisTr]['steps'][1]['userGroup'],
                    "oleh_id" => $this->session->login['id'],
                    "oleh_nama" => $this->session->login['nama'],
                    "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                    "transaksi_id" => $insertID,
                )) or die("Failed to write signature");
                // cekMerah($this->db->last_query());
                // matiHEre();
                $idHis = array(
                    $stepNumber => array(
                        "olehID" => $_SESSION[$cCode]['main']['olehID'],
                        "olehName" => $_SESSION[$cCode]['main']['olehName'],
                        "step" => $stepNumber,
                        "trID" => $insertID,
                        "nomer" => $tmpNomorNota,
                        "nomer_alias" => $tmpNomorNota_alias,
                        "counters" => $appliedCounters,
                        "counters_intext" => $appliedCounters_inText,
                    ),
                );
                $idHis_blob = blobEncode($idHis);
                $idHis_intext = print_r($idHis, true);
                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array("id" => $insertID), array(
                    "next_step_num" => $nextProp['num'],
                    "next_step_code" => $nextProp['code'],
                    "next_step_label" => $nextProp['label'],
                    "next_group_code" => $nextProp['groupID'],

                    //===references
                    "id_master" => $insertID,
                    "id_top" => $insertID,
                    "ids_prev" => "",
                    "ids_prev_intext" => "",
                    "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                    "nomers_prev" => "",
                    "nomers_prev_intext" => "",
                    "jenises_prev" => "",
                    "jenises_prev_intext" => "",
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

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

                $addValues = array(
                    //===references
                    "id_master" => $insertID,
                    "id_top" => $insertID,
                    "ids_prev" => "",
                    "ids_prev_intext" => "",
                    "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                    "nomers_prev" => "",
                    "nomers_prev_intext" => "",
                    "jenises_prev" => "",
                    "jenises_prev_intext" => "",
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,
                );
                foreach ($addValues as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }

            }
            // arrPrint($_SESSION[$cCode]['tableIn_master']);
            // matiHEre("hoop");
            if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                $inserMainValues = array();
                if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                    foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                        if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                            $inserMainValues[] = $tr->writeMainValues($insertID, array(
                                "key" => $key,
                                "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                            ));
                        }
                    }
                }

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

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

                if (sizeof($inserMainValues) > 0) {
                    $arrBlob = blobEncode($inserMainValues);
                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                    $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    //                    cekkuning("making a clone for input key $key / $val");
                    //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                    //                    $replacers=array(
                    //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                    //                    );
                    //                    foreach($replacers as $key=>$val){
                    //                        $tmpTableIn[$key]=$val;
                    //                    }
                    //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                }
            }
            if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                    $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                }
            }
            if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                    $tr->writeMainApplets($insertID, array(
                        "mdl_name" => $amdl,
                        "key" => $aSpec['key'],
                        "label" => $aSpec['labelValue'],
                        "description" => $aSpec['description'],
                    ));
                }
            }
            if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                    $tr->writeMainElements($insertID, array(
                        "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                        "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                        "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                        "name" => $aSpec['name'],
                        "label" => $aSpec['label'],
                        "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                        "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                    ));


                    //==nebeng bikin inputLabels
                    $currentValue = "";
                    switch ($aSpec['elementType']) {
                        case "dataModel":
                            $currentValue = $aSpec['key'];
                            break;
                        case "dataField":
                            $currentValue = $aSpec['value'];
                            break;
                    }
                    if (array_key_exists($elName, $relOptionConfigs)) {
                        //					cekhijau("$eName terdaftar pada relInputs");


                        if (isset($relOptionConfigs[$elName][$currentValue])) {
                            if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
                                foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
                                    $inputLabels[$oValueName] = $oValSpec['label'];
                                    if (isset($oValSpec['auth'])) {
                                        if (isset($oValSpec['auth']['groupID'])) {
                                            $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
                        }

                    }

                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

                $insertIDs = array();
                $insertDeIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail'] as $dSpec) {
                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                    if ($insertDetailID < 1) {
                        die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                    }
                    else {
                        $insertIDs[] = $insertDetailID;
                        $insertDeIDs[$insertID][] = $insertDetailID;
                    }
                    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;
                        }
                    }
                    cekUngu($this->db->last_query());
                }


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

                    foreach ($indexing_details as $k => $arrID) {
                        $arrBlob = blobEncode($arrID);
                        $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                        cekOrange($this->db->last_query());
                    }
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                    $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                    if ($epID != 999) {
                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                    }
                    cekUngu($this->db->last_query());
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                    $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                    if ($epID != 999) {
                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                    }
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                    $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                    if ($epID != 999) {
                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                    }
                    cekUngu($this->db->last_query());
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

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

                            }
                        }
                    }
                }

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

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

            // cekHitam("cek line:: " . __LINE__);
            // matiHere();
            //===components akan langsung dieksekusi jika steps-nya tidak pakai approval
            $steps = $this->configUi[$this->jenisTr]['steps'];

            //region processing sub-components, if in single step
            //<editor-fold desc="----------subcomponents">
            $componentConfig['detail'] = array();
            //==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();
            $filterNeeded = false;
            $comsLocation = isset($this->configValues[$this->jenisTr]['componentsLocation']['detail']) ? $this->configValues[$this->jenisTr]['componentsLocation']['detail'] : "Coms";
            $comsPrefix = isset($this->configValues[$this->jenisTr]['componentsPrefix']['detail']) ? $this->configValues[$this->jenisTr]['componentsPrefix']['detail'] : "Com";
            $componentsDetailLoop = isset($this->configValues[$this->jenisTr]['componentsDetailLoop']) ? $this->configValues[$this->jenisTr]['componentsDetailLoop'] : true;

            //region processing sub-components
            if (isset($this->configValues[$this->jenisTr]['relativeComponets']) && $this->configValues[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['jurnal']['detail']) ? $_SESSION[$cCode]['revert']['jurnal']['detail'] : array();
                $revertedTarget = $_SESSION[$cCode]['main']['pihakExternID'];
            }
            else {
                if (isset($_SESSION[$cCode]['componentsBuilder'][1]['detail'])) {
                    $iterator = $_SESSION[$cCode]['componentsBuilder'][1]['detail'];
                }
                elseif (isset($this->configValues[$this->jenisTr]['components'][$jenisTrTarget]['detail'])) {
                    $iterator = $this->configValues[$this->jenisTr]['components'][$jenisTrTarget]['detail'];
                }
                else {
                    $iterator = array();
                }
                $revertedTarget = "";
            }


            if (sizeof($iterator) > 0) {
                foreach ($iterator as $cCtr => $tComSpec) {
                    $tmpOutParams[$cCtr] = array();
                    $gg = 0;
                    $srcGateName = $tComSpec['srcGateName'];

                    // SATU ITERATOR AKAN MENJALANKAN SESSION ITEMS
                    if ($componentsDetailLoop == true) {
                        foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
                            $srcRawGateName = $tComSpec['srcRawGateName'];
                            $comName = $tComSpec['comName'];
                            if (substr($comName, 0, 1) == "{") {
                                $comName = trim($comName, "{");
                                $comName = trim($comName, "}");

                                $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
                            }


                            $mdlName = "$comsPrefix" . ucfirst($comName);
                            if (in_array($mdlName, $compValidators)) {//perlu validasi filter
                                //cekLime($mdlName. "line");
                                $filterNeeded = true;
                            }
                            else {
                                //                            cekLime($mdlName . "like");
                                $filterNeeded = false;
                            }
                            echo "sub-component: [$comsLocation] $comName, initializing values <br>";

                            $subParams = array();

                            if (isset($tComSpec['loop'])) {
                                foreach ($tComSpec['loop'] as $key => $value) {
                                    cekMerah(":: $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][$id][$key], $key);
                                    }

                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                    $subParams['loop'][$key] = $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;

                                }
                                if (!isset($subParams['static']["transaksi_id"])) {
                                    $subParams['static']["transaksi_id"] = $insertID;
                                }
                                if (!isset($subParams['static']["transaksi_no"])) {
                                    $subParams['static']["transaksi_no"] = $insertNum;
                                }

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

                            if (sizeof($subParams) > 0) {
                                //                            arrprint($subParams);
                                cekhitam("subparam ada isinya");
                                if ($filterNeeded) {
                                    if (isset($subParams['loop']) && sizeof($subParams['loop']) > 0) {
                                        $tmpOutParams[$cCtr][] = $subParams;
                                    }
                                }
                                else {
                                    $tmpOutParams[$cCtr][] = $subParams;
                                    //                                CekHijiau("asem" .$gg++);
                                }
                            }
                            else {
                                cekhitam("subparam TIDAK ada isinya");
                            }

                        }
                    }
                    else {
                        // SATU ITERATOR AKAN MENJALANKAN SESSION ITEMS
                        foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
                            if ($cCtr == $id) {

                                $srcRawGateName = $tComSpec['srcRawGateName'];
                                $comName = $tComSpec['comName'];
                                if (substr($comName, 0, 1) == "{") {
                                    $comName = trim($comName, "{");
                                    $comName = trim($comName, "}");

                                    $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
                                }


                                $mdlName = "$comsPrefix" . ucfirst($comName);
                                if (in_array($mdlName, $compValidators)) {//perlu validasi filter
                                    //cekLime($mdlName. "line");
                                    $filterNeeded = true;
                                }
                                else {
                                    //                            cekLime($mdlName . "like");
                                    $filterNeeded = false;
                                }
                                echo "sub-component: [$comsLocation] $comName, initializing values <br>";

                                $subParams = array();

                                if (isset($tComSpec['loop'])) {
                                    foreach ($tComSpec['loop'] as $key => $value) {
                                        cekMerah(":: $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][$id][$key], $key);
                                        }

                                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                        $subParams['loop'][$key] = $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;

                                    }
                                    if (!isset($subParams['static']["transaksi_id"])) {
                                        $subParams['static']["transaksi_id"] = $insertID;
                                    }
                                    if (!isset($subParams['static']["transaksi_no"])) {
                                        $subParams['static']["transaksi_no"] = $insertNum;
                                    }

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

                                if (sizeof($subParams) > 0) {
                                    //                            arrprint($subParams);
                                    cekhitam("subparam ada isinya");
                                    if ($filterNeeded) {
                                        if (isset($subParams['loop']) && sizeof($subParams['loop']) > 0) {
                                            $tmpOutParams[$cCtr][] = $subParams;
                                        }
                                    }
                                    else {
                                        $tmpOutParams[$cCtr][] = $subParams;
                                        //                                CekHijiau("asem" .$gg++);
                                    }
                                }
                                else {
                                    cekhitam("subparam TIDAK ada isinya");
                                }

                            }
                        }
                    }

                    $componentConfig['detail'][$cCtr] = $subParams;
                }

                foreach ($iterator as $cCtr => $tComSpec) {
                    $srcGateName = $tComSpec['srcGateName'];
                    foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {

                        $srcRawGateName = $tComSpec['srcRawGateName'];
                        $comName = $tComSpec['comName'];
                        if (substr($comName, 0, 1) == "{") {
                            $comName = trim($comName, "{");
                            $comName = trim($comName, "}");
                            $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
                        }

                    }
                    echo "sub component: [$comsLocation] $comName, sending values ***<br>";

                    $mdlName = "$comsPrefix" . ucfirst($comName);
                    $this->load->model("$comsLocation/" . $mdlName);
                    $m = new $mdlName();
                    //===filter value nol, jika harus difilter

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

                    if ($tobeExecuted) {
                        cekMerah("$comName dieksekusiii");
                        arrPrint($tmpOutParams[$cCtr]);
                        //----- kiriman gerbang
                        if (method_exists($m, "setTableInMaster")) {
                            $m->setTableInMaster($_SESSION[$cCode]["tableIn_master"]);
                        }
                        if (method_exists($m, "setDetail")) {
                            $m->setDetail($_SESSION[$cCode][$srcGateName]);
                        }
                        if (method_exists($m, "setJenisTr")) {
                            $m->setJenisTr($this->jenisTr);
                        }
                        //----- kiriman gerbang
                        $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__);
                        cekBiru($this->db->last_query());
                    }
                    else {
                        cekMerah("$comName tidak eksekusi");
                    }

                }
            }
            else {
                //cekKuning("subcomponents is not set");
            }
            //endregion

            //endregion

//arrPrint($_SESSION[$cCode]['main']);
            //region processing main components, if in single step
            $componentConfig['master'] = array();
            //==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();
            if (isset($this->configValues[$this->jenisTr]['relativeComponets']) && $this->configValues[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['jurnal']['master']) ? $_SESSION[$cCode]['revert']['jurnal']['master'] : array();
                cekKuning(":: ATAS ::");
            }
            else {
                if (isset($_SESSION[$cCode]['componentsBuilder'][1]['master'])) {
                    $iterator = $_SESSION[$cCode]['componentsBuilder'][1]['master'];
                }
                elseif (isset($this->configValues[$this->jenisTr]['components'][$jenisTrTarget]['master'])) {
                    $iterator = $this->configValues[$this->jenisTr]['components'][$jenisTrTarget]['master'];
                }
                else {
                    $iterator = array();
                }
            }
//arrprintPink($iterator);
//mati_disini();
            if (sizeof($iterator) > 0) {
                $componentConfig['master'] = $iterator;
                $cCtr = 0;
                foreach ($iterator as $cCtr => $tComSpec) {
                    $cCtr++;
                    $comName = $tComSpec['comName'];
                    if (substr($comName, 0, 1) == "{") {
                        $comName = trim($comName, "{");
                        $comName = trim($comName, "}");
                        $comName = str_replace($comName, $_SESSION[$cCode]['main'][$comName], $comName);
                    }
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo "component # $cCtr: $comName<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);
                            }

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                            $tmpOutParams['loop'][$key] = $realValue;
                            //                            cekKuning("LOOP $key diisi dengan $realValue");
                        }
                    }
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

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

                        }
                        if (!isset($tmpOutParams['static']["transaksi_id"])) {
                            $tmpOutParams['static']["transaksi_id"] = $insertID;
                        }
                        if (!isset($tmpOutParams['static']["transaksi_no"])) {
                            $tmpOutParams['static']["transaksi_no"] = $insertNum;
                        }
                        $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'][1]['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($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'];


                    }

                    //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) {
                        //----- kiriman gerbang untuk counter mutasi rekening
                        if (method_exists($m, "setTableInMaster")) {
                            $m->setTableInMaster($_SESSION[$cCode]["tableIn_master"]);
                        }
                        if (method_exists($m, "setMain")) {
                            $m->setMain($_SESSION[$cCode]["main"]);
                        }
                        if (method_exists($m, "setJenisTr")) {
                            $m->setJenisTr($this->jenisTr);
                        }
                        //----- kiriman gerbang untuk counter mutasi rekening
                        $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__);
                    }

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


            //endregion

//mati_disini(__LINE__);

            //region processing sub-post-processors, always
            if (isset($this->configValues[$this->jenisTr]['relativeComponets']) && $this->configValues[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['postProc']['detail']) ? $_SESSION[$cCode]['revert']['postProc']['detail'] : array();
            }
            else {
                $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>";
                    $tmpOutParams[$cCtr] = array();
                    foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                        $id = $dSpec['id'];
                        $subParams = array();
                        if (isset($tComSpec['loop'])) {
                            foreach ($tComSpec['loop'] as $key => $value) {

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

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

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

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

                arrPrint($iterator);
                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");
                }
            }
            //endregion

            //region relesaese connected payment source dan marking trash transaksi
            //            arrPrint($_SESSION[$cCode]["revert"]);
            if (isset($_SESSION[$cCode]["revert"]["connectedPaymentsource"]) && $_SESSION[$cCode]["revert"]["connectedPaymentsource"] == true) {
                $keyRel = $_SESSION[$cCode]["main"]["referenceID"];
                $keyRelRef = $_SESSION[$cCode]["main"]["pihakExternID"];
                $relPaymentSrc = isset($this->config->item("payment_source")[$keyRelRef]) ? $this->config->item("payment_source")[$keyRelRef] : array();
                if (sizeof($relPaymentSrc) > 0) {
                    $this->load->model("Mdls/MdlPaymentSource");
                    $m = new MdlPaymentSource();
                    $m->addFilter("transaksi_id='$keyRel'");
                    $tmpRelPay = $m->lookupAll()->result();
                    $paymentRelUsed = array(
                        "cabang_id" => "placeID",
                        "extern_id" => "id",
                        "extern_nama" => "name",
                        "label" => ".hutang biaya",
                        "target_jenis" => "jenisTr",
                        "transaksi_id" => "refID",
                        "terbayar" => "nilai_bayar",
                        "sisa" => "new_sisa",
                        "ppn" => "valid_ppn",
                        "extern_nilai2" => "valid_dpp",
                        "toko_id" => "tokoID",
                        "toko_nama" => "tokoName",
                    );
                    if (sizeof($tmpRelPay) > 0) {
                        $tmpOutParams = array();
                        $iterator = array();
                        foreach ($tmpRelPay as $indexKey => $relData) {
                            $tmp = array();
                            foreach ($paymentRelUsed as $key => $keyGate) {
                                if ($key == "terbayar") {
                                    $val = $relData->sisa;
                                }
                                else {
                                    if ($key == "sisa") {
                                        $val = "-" . $relData->sisa;
                                    }
                                    else {
                                        $val = $relData->$key;
                                    }
                                }
                                $tmp["static"][$key] = $val;
                                $tmp["static"]["keterangan"] = $this->configUi[$this->jenisTr]['steps'][1]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];

                            }
                            $iterator[$indexKey]["loop"] = array();
                            $iterator[$indexKey]["comName"] = "PaymentSrcItem";
                            if (sizeof($tmp) > 0) {
                                $tmpOutParams[$indexKey][] = $tmp;
                            }
                        }
                        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__);
                            //                            cekHitam($this->db->last_query());
                        }
                    }
                    //                    foreach()
                    cekLime("yuk direset paymentsource**");
                }


            }
            //endregion

            //region processing main-post-processors, always
            if (isset($this->configValues[$this->jenisTr]['relativeComponets']) && $this->configValues[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['postProc']['detail']) ? $_SESSION[$cCode]['revert']['postProc']['master'] : array();
            }
            else {
                $iterator = isset($this->configValues[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master']) ? $this->configValues[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master'] : array();
            }
            //            $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][1]['master']) ? $this->configCore[$this->jenisTr]['postProcessor'][1]['master'] : array();
            if (sizeof($iterator) > 0) {
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo "post-processor: $comName<br>LINE: " . __LINE__;

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

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

                        }
                    }
                    if (isset($tComSpec['static'])) {
                        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[$this->jenisTr]['steps'][1]['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($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'];


                    }

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

                    cekBiru("kiriman komponem $comName");
                    arrPrintWebs($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 {

            }
            //endregion

//            cekHere("cekline:: " . __LINE__);

            //  region //cek lajur dan neraca
            //            if (sizeof($steps) == 1) {//==nggak pakai step2 lanjutan
            //
            //                $mdlName = "ComLedger";
            //                $this->load->model("Mdls / ".$mdlName);
            //                $l = new ComLedger();
            //                $l->addFilter("periode = 'forever'");
            ////        $date = date("Y - m - d");
            //                $tmp = $l->getLastEntries();
            ////                arrPrint($tmp);
            //                $arrHasilLajur = $l->getLajurBalance($tmp);
            //                $arrHasilNeraca = $l->getNeracaBalance($tmp);
            //
            ////                if (is_null($arrHasilLajur)) {
            ////                    mati_disini("UN - BALANCE... LAJUR");
            ////                } else {
            ////                    //cekBiru("BALANCE LAJUR...");
            ////                }
            ////
            ////                if (is_null($arrHasilNeraca)) {
            ////                    mati_disini("UN - BALANCE... NERACA");
            ////                } else {
            ////                    arrPrint($arrHasilNeraca);
            ////                    //cekBiru("BALANCE NERACA...");
            ////                }
            //
            //            }
            //  endregion //cek lajur dan neraca

            //region updater main transaksi rejection jurnal next step exist
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                // arrPrint($_SESSION[$cCode]["main"]["referenceID"]);
                // matiHere($_SESSION[$cCode]["main"]["referenceID"]);
                $refNumID = $_SESSION[$cCode]["main"]["referenceID"];
                $tr->setFilters(array());
                $tr->addFilter("id =$refNumID");
                $tempData = $tr->lookupAll()->result();
                cekBiru($this->db->last_query());
                // arrPrint($tempData);
                // matiHEre();
                $refMasterID = $tempData[0]->id_master;
                $refMasterJenis = $tempData[0]->jenis_master;
                $nextStepCode = $tempData[0]->next_step_code;
                $mainStepCode = $tempData[0]->jenis;
                $stepnum = $tempData[0]->step_number;
                $stepnumAvail = $tempData[0]->step_avail;
                if (($stepnumAvail - $stepnum) > 0) {
                    //                    matiHere("masukk".$nextStepCode);
                    $this->load->model("Coms / ComTransaksi_jurnal_revert");
                    $r = new ComTransaksi_jurnal_revert();
                    $outParams = array(
                        "refID" => $refMasterID,
                        "main_code" => $mainStepCode,
                        "next_code" => $nextStepCode,
                        "step_num" => $stepnum,
                    );
                    $r->pair($outParams) or die("Tidak berhasil memasang  values pada komponen: $comName / " . $this->jenisTr . " / " . __FUNCTION__ . " / " . __LINE__);
                    $r->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName / " . $this->jenisTr . " / " . __FUNCTION__ . " / " . __LINE__);

                    //marking main transaksi trash4
                    $udpate = array(
                        "trash_4" => "1",
                    );
                    $tr->setFilters(array());
                    //$tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array(
                        //                "id" => $no,
                        "id" => $_SESSION[$cCode]["main"]["referenceID"],
                    ), $udpate) or die("Failed to update tr next - state!");
                    cekHijau("UPDATE transaksi step sebelumnya...");
                    cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    //update validqty 0 supaya gak bisa difollowup
                    //                    $arrData_detail["valid_qty"] = 0;
                    $td = new MdlTransaksi();
                    $td->setFilters(array());
                    $rslt = $td->lookupJoinedByID($_SESSION[$cCode]["main"]["referenceID"])->result();
                    if (sizeof($rslt) > 0) {
                        foreach ($rslt as $rsltSpec) {
                            if (array_key_exists($rsltSpec->produk_id, $_SESSION[$cCode]["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'];
                                //                                }
                                $arrData_detail["valid_qty"] = 0;
                                $tr = new MdlTransaksi();
                                $tr->setFilters(array());
                                $tr->setTableName($tr->getTableNames()['detail']);
                                $dupState = $tr->updateData(array(
                                    "transaksi_id" => $_SESSION[$cCode]["main"]["referenceID"],
                                    "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() . "]");
                            }
                        }
                    }

                    $dwsign = $tr->writeSignature($refMasterID, array(
                        "prev_id" => "",
                        "nomer" => "pembatalan",
                        "step_number" => " - " . $stepnum, // ini minus step number
                        "step_code" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['target'],
                        "step_name" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'],
                        "group_code" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['userGroup'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "keterangan" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'] . " oleh " . $this->session->login['nama'],
                        //            "transaksi_id" => $no,
                    )) or die("Failed to write signature");
                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                    matiHere("ada revertan");
                }
                else {

                    //marking main transaksi trash4
                    $udpate = array(
                        "trash_4" => "1",
                        "cancel_dtime" => date("Y-m-d H:i"),
                        "cancel_id" => $this->session->login['id'],
                        "cancel_name" => $this->session->login['nama'],

                    );
                    $tr->setFilters(array());
                    //                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array(
                        //                "id" => $no,
                        "id" => $_SESSION[$cCode]["main"]["referenceID"],
                    ), $udpate) or die("Failed to update tr next - state!");
                    cekHijau("UPDATE transaksi step sebelumnya...");
                    cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    //update validqty 0 supaya gak bisa difollowup
                    $arrData_detail["valid_qty"] = $new_valid_qty;
                    $td = new MdlTransaksi();
                    $td->setFilters(array());
                    $rslt = $td->lookupJoinedByID($_SESSION[$cCode]["main"]["referenceID"])->result();
                    if (sizeof($rslt) > 0) {
                        foreach ($rslt as $rsltSpec) {
                            if (array_key_exists($rsltSpec->produk_id, $_SESSION[$cCode]["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'];
                                //                                }
                                $arrData_detail["valid_qty"] = 0;
                                $tr = new MdlTransaksi();
                                $tr->setFilters(array());
                                $tr->setTableName($tr->getTableNames()['detail']);
                                $dupState = $tr->updateData(array(
                                    "transaksi_id" => $_SESSION[$cCode]["main"]["referenceID"],
                                    "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() . "]");
                            }
                        }
                    }

                    $dwsign = $tr->writeSignature($refMasterID, array(
                        "prev_id" => "",
                        "nomer" => "pembatalan",
                        "step_number" => " - " . $stepnum, // ini minus step number
                        "step_code" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['target'],
                        "step_name" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'],
                        "group_code" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['userGroup'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "keterangan" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'] . " oleh " . $this->session->login['nama'],
                        //            "transaksi_id" => $no,
                    )) or die("Failed to write signature");
                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    // matiHEre("uhuu");
                }
            }

            //endregion

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

                $payConfigs = $paymentSources[$stepCode];
                if (sizeof($payConfigs) > 0) {
                    foreach ($payConfigs[1] as $paymentSrcConfig) {
                        //					$paymentSrcConfig = $paymentSources[$stepCode];
                        $valueSrc = $paymentSrcConfig['valueSrc'];
                        $externSrc = $paymentSrcConfig['externSrc'];
                        // arrPrint($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" => $_SESSION[$cCode]['main']['nomer'],
                            "label" => $paymentSrcConfig['label'],
                            "tagihan" => isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0,
                            "terbayar" => 0,
                            "sisa" => isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0,
                            "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']] : 0,
                            "tagihan_valas" => (isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']])) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : 0,
                            "terbayar_valas" => (isset($externSrc['valasTerbayar']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTerbayar']])) ? $_SESSION[$cCode]['main'][$externSrc['valasTerbayar']] : 0,
                            "sisa_valas" => (isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']])) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : 0,
                            "extern_label2" => (isset($externSrc['extern_label2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_label2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_label2']] : "",
                            "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']] : 0,
                        ));
                        cekMerah($this->db->last_query());
                    }
                }


            }
            else {
                cekMerah("TIDAK nulis paymentSrc");
            }
            //endregion
            // matiHere(__LINE__ . __METHOD__);

            //
            //region nulis paymentAntiSource
            $stepCode = $this->configUi[$this->jenisTr]['steps'][1]['target'];
            $paymentSources = $this->config->item("payment_antiSource") != null ? $this->config->item("payment_antiSource") : array();
            if (array_key_exists($stepCode, $paymentSources)) {
                cekHitam(":: 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" => $_SESSION[$cCode]['main']['nomer'],
                            "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" => isset($_SESSION[$cCode]['main'][$externSrc['valasTerbayar']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTerbayar']] : '',
                            "sisa_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',

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


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


            //====registri value-gate
            if (isset($this->configCore[$this->jenisTr]['components'][1]) && sizeof($this->configCore[$this->jenisTr]['components'][1])) {
                $jurnalIndex = $this->configCore[$this->jenisTr]['components'][1];
            }
            else {
                if (isset($_SESSION[$cCode]["revert"]["jurnal"]) && sizeof($_SESSION[$cCode]["revert"]["jurnal"]) > 0) {
                    $jurnalIndex = $_SESSION[$cCode]["revert"]["jurnal"];
                }
                else {
                    $jurnalIndex = array();
                }
            }

            if (isset($this->configCore[$this->jenisTr]['postProcessor'][1]) && sizeof($this->configCore[$this->jenisTr]['postProcessor'][1])) {
                $jurnalPostProc = $this->configCore[$this->jenisTr]['postProcessor'][1];
            }
            else {
                if (isset($_SESSION[$cCode]["revert"]["postProc"]) && sizeof($_SESSION[$cCode]["revert"]["postProc"]) > 0) {
                    $jurnalPostProc = $_SESSION[$cCode]["revert"]["postProc"];
                }
                else {
                    $jurnalPostProc = array();
                }
            }
            //------------
            if (isset($this->configValues[$this->jenisTr]['coreBuilder'][$jenisTrTarget]) && sizeof($this->configValues[$this->jenisTr]['coreBuilder'][$jenisTrTarget])) {
                $coreBuilder = $this->configValues[$this->jenisTr]['coreBuilder'][$jenisTrTarget];
            }
            else {
                $coreBuilder = array();
            }
            //------------
            $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(),
                'itemSrc' => isset($_SESSION[$cCode]['itemSrc']) ? $_SESSION[$cCode]['itemSrc'] : array(),
                'itemSrc_sum' => isset($_SESSION[$cCode]['itemSrc_sum']) ? $_SESSION[$cCode]['itemSrc_sum'] : 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(),
                'items5_sum' => isset($_SESSION[$cCode]['items5_sum']) ? $_SESSION[$cCode]['items5_sum'] : array(),
                'items6_sum' => isset($_SESSION[$cCode]['items6_sum']) ? $_SESSION[$cCode]['items6_sum'] : array(),
                'items7_sum' => isset($_SESSION[$cCode]['items7_sum']) ? $_SESSION[$cCode]['items7_sum'] : array(),
                'items8_sum' => isset($_SESSION[$cCode]['items8_sum']) ? $_SESSION[$cCode]['items8_sum'] : array(),
                'items9_sum' => isset($_SESSION[$cCode]['items9_sum']) ? $_SESSION[$cCode]['items9_sum'] : array(),
                'items10_sum' => isset($_SESSION[$cCode]['items10_sum']) ? $_SESSION[$cCode]['items10_sum'] : array(),

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

                '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(),
                'items_elements' => isset($_SESSION[$cCode]['items_elements']) ? $_SESSION[$cCode]['items_elements'] : array(),
                'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                //                "jurnal_index" =>isset($this->configCore[$this->jenisTr]['components'][1]) ? $this->configCore[$this->jenisTr]['components'][1] : array(),
                "jurnal_index" => $jurnalIndex,
                //                "postProcessor" =>isset($this->configCore[$this->jenisTr]['postProcessor'][1]) ? $this->configCore[$this->jenisTr]['postProcessor'][1] : array(),
                "postProcessor" => $jurnalPostProc,
                "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(),
                //-----
                "coreBuilder" => $coreBuilder,
                //-----
            );
            // arrPrint($baseRegistries);
            $doWriteReg = $tr->writeRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
            cekKuning(":: mulai cek rek besar dan rek pembantu");

            //region cek transaksi punya connecting atau tidak
            if (strlen($connecToRelation) > 1) {
                $cc = new MdlTransaksi();
                $cc->setFilters(array());
                $cc->addFilter("id_master=$transID_ref");
                $cc->addFilter("link_id=0");
                $cc->addFilter("jenis_master=$connecToRelation");
                $tmpConnected = $cc->lookUpMainTransaksi()->result();
                cekBiru($this->db->last_query());
                if (sizeof($tmpConnected) > 0) {

//                 arrPrint($tmpConnected);
// matiHere();
                    //cek sudah difoolw up
                    // $next_step = $tmpConnected[0]->next_step_num;
                    // $curent_step = $tmpConnected[0]->step_current;

                    $relID = $tmpConnected[0]->id;
                    $refMasterIDRel = $tmpConnected[0]->id_master;
                    $refMasterJenisRel = $tmpConnected[0]->jenis_master;
                    $nextStepCodeRel = $tmpConnected[0]->next_step_code;
                    $mainStepCodeRel = $tmpConnected[0]->jenis;
                    $stepnumRel = $tmpConnected[0]->step_number;
                    $stepnumAvailRel = $tmpConnected[0]->step_avail;
                    $nextStepNum = $tmpConnected[0]->next_step_num;
                    // matiHere("8");
                    if ($nextStepNum > 0) {
                        //jika belum di followup langsung di matikan
                        $udpate = array(
                            "trash_4" => "1",
                            "cancel_dtime" => date("Y-m-d H:i"),
                            "cancel_id" => $this->session->login['id'],
                            "cancel_name" => $this->session->login['nama'],

                        );
                        $tr->setFilters(array());
                        //                    $tr = new MdlTransaksi();
                        $dupState = $tr->updateData(array(
                            //                "id" => $no,
                            "id" => $relID,
                        ), $udpate) or die("Failed to update tr next - state!");
                        cekHijau("UPDATE transaksi step sebelumnya...");
                        cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                        //update validqty 0 supaya gak bisa difollowup
                        $arrData_detail["valid_qty"] = 0;
                        $td = new MdlTransaksi();
                        $td->setFilters(array());
                        $rslt = $td->lookupJoinedByID($relID)->result();
                        if (sizeof($rslt) > 0) {
                            foreach ($rslt as $rsltSpec) {
                                // if (array_key_exists($rsltSpec->produk_id, $_SESSION[$cCode]["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'];
                                //                                }
                                $arrData_detail["valid_qty"] = 0;
                                $tr = new MdlTransaksi();
                                $tr->setFilters(array());
                                $tr->setTableName($tr->getTableNames()['detail']);
                                $dupState = $tr->updateData(array(
                                    "transaksi_id" => $relID,
                                    "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() . "]");
                                // }
                            }
                        }

                        $dwsign = $tr->writeSignature($relID, array(
                            "prev_id" => "",
                            "nomer" => "pembatalan**",
                            "step_number" => " - " . $stepnum, // ini minus step number
                            "step_code" => $this->configUi[$refMasterJenisRel]['steps'][abs($stepnumRel)]['target'],
                            "step_name" => $this->configUi[$refMasterJenisRel]['steps'][abs($stepnumRel)]['label'],
                            "group_code" => $this->configUi[$refMasterJenisRel]['steps'][abs($stepnumRel)]['userGroup'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "keterangan" => $this->configUi[$refMasterJenis]['steps'][abs($stepnumRel)]['label'] . " oleh " . $this->session->login['nama'],
                            //            "transaksi_id" => $no,
                        )) or die("Failed to write signature");

                    }
                    else {
                        cekHitam("sudah difollow up, tidak bisa otomatis di cabut");
                        matiHEre();
                    }
                    cekHitam("next " . $next_step . " <br> " . " current step " . $curent_step);
                    // arrPrint($tmpConnected);

                    // matiHEre("ada connectingnya nya broo");
                }
            }


            //endregion

            validateBalancesComparison("", $componentConfig);
            validateAllBalances();


            mati_disini("LINE: " . __LINE__ . " under maintenance, tunggu beberapa saat lagi yaa ..");

            $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");

        }
        else {
            matiHere("Gagal melakukan pembatalan. Data tidak ditemukan!");
        }


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

        //region feedback msg
        $this->session->errMsg = "transaction entry has been saved < br>";
        $nextNum = $nextProp["num"];
        if (isset($this->configUi[$this->jenisTr]['steps'][$nextNum])) {
            $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white' > " . $this->configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . " </strong ><br > ";
            $this->session->errMsg .= "This entry needs to be authorized by < strong class='text-blue' > " . $this->configUi[$this->jenisTr]['steps'][$nextNum]['userGroup'] . " </strong ><br > ";
            $trBackLink = base_url() . get_class($this) . " / viewIncomplete / " . $this->jenisTr;

        }
        else {
            $this->session->errMsg .= "transaction state: <strong class='badge bg-grey text-white' > " . $this->configUi[$this->jenisTr]['steps'][$nextNum]['stateLabel'] . " </strong ><br > ";
            $trBackLink = base_url() . get_class($this) . " / viewHistory / " . $this->jenisTr;

        }
        $trBackClick = "location . href = '$trBackLink'";
        //            $this->session->errMsg .= " < a href = 'JavaScript:void(0)' onclick = \"$trBackClick\">view entry</a><br>";
        //endregion

        $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 topReload();
        unset($this->session->errMsg);


        // matiHEre($cCode);

    }

    //---------------------------
    public function doPreEdit_old_unused()
    {
        $this->load->model("MdlTransaksi");

        $no = rtrim($this->uri->segment(5), "-");

        //$targetStepNum = $this->uri->segment(4);
        $stepNumber = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);

        $rawBuilderURL = blobEncode(current_url());
        $editMode = array(
            "edit" => "$no",
        );


        $tr = new MdlTransaksi();
        $tr->addFilter("transaksi.id in (" . implode(",", explode("-", $no)) . ")");
        $tmpTr = $tr->lookupJoined()->result();
//arrprintPink($tmpTr);
//mati_disini(__LINE__);

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

        $rawItems = array();

        //region detail elements of preview
        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;
            $cCode = "_TR_" . $this->jenisTr;
            if (isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = null;
                unset($_SESSION[$cCode]);
            }

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

            $trID = $tmpTr[0]->transaksi_id;
            $itemLabels = isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNumber]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][$stepNumber] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNumber] : array();
            $subAmountConfig = isset($this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$stepNumber]) ? $this->configUi[$this->jenisTr]['shoppingCartAmountValue'][$stepNumber] : null;
            $measurementDetails = isset($this->configUi[$this->jenisTr]["receiptMesurementRows"]) ? $this->configUi[$this->jenisTr]["receiptMesurementRows"] : array();
            $masterID = $tmpTr[0]->id_master;
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;
            $currentStepNum = $tmpTr[0]->step_number;
            $afterTargetStepNum = ($currentStepNum + 1);


            //==periksa apakah ada ganjalan
            $trA = new MdlTransaksi();

            $extSteps = $trA->lookupExtSteps($trID);
            if (sizeof($extSteps) > 0) {
                cekmerah("ada ganjalan step sebanyak " . sizeof($extSteps));
            }
            else {
                cekhijau("TAK ada ganjalan step");
            }

            $paySrcs = $trA->lookupPaymentSrcs($trID, $this->jenisTr . "_");
            if (sizeof($paySrcs) > 0) {
                cekmerah("ada ganjalan paymentSrc sebanyak " . sizeof($paySrcs));
            }
            else {
                cekhijau("TAK ada ganjalan paymentSrc");
            }


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


            //region valid items
            $this->load->model("MdlTransaksi");
            $tr = new MdlTransaksi();
            $tr->addFilter("transaksi.id in (" . implode(",", explode("-", $no)) . ")");
            $tr->addFilterJoin("valid_qty>0");
            $tmpTr = $tr->lookupJoined()->result();
            //            cekhitam($this->db->last_query());


            $extractedItems = array();//==untuk urusan update transaksi referer
            $validItems = array();
            $validItemSends = array();
            if (sizeof($tmpTr) > 0) {
                cekmerah("ada yang mau diekstrak");
                foreach ($tmpTr as $row) {
                    if (!isset($validItems[$row->produk_id])) {
                        $validItems[$row->produk_id] = 0;
                    }
                    if (!isset($validItemSends[$row->produk_id])) {
                        $validItemSends[$row->produk_id] = 0;
                    }
                    $validItems[$row->produk_id] += $row->valid_qty;
                    $validItemSends[$row->produk_id] += $row->produk_ord_jml - $row->valid_qty;

                    if (!isset($extractedItems[$row->produk_id])) {
                        $extractedItems[$row->produk_id] = array();
                    }
                    $extractedItems[$row->produk_id][$row->id_detail] = array(
                        "id" => $row->id_detail,
                        "produk_id" => $row->produk_id,
                        "qty" => $row->produk_ord_jml,
                        "valid_qty" => $row->valid_qty,
                        "transaksi_id" => $row->transaksi_id,
                        "sent_qty" => $row->produk_ord_jml - $row->valid_qty,
                    );


                }
            }
            else {
                cekmerah("TIDAK ada yang mau diekstrak");
            }
            //            arrprint($validItems);
            //die();
            //            die();
            //endregion


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


            //region take from registries
            //==ambil value-gate
            $trr = new MdlTransaksi();
            $trr->setFilters(array());
            $trr->addFilter("transaksi_id='$no'");
            $tmpReg = $trr->lookupDataRegistries()->result();
            cekKuning($this->db->last_query());

            $mainOriginal = array();
            $itemsOriginal = array();
            $main = array();
            $items = array();
            $items2 = array();
            $items2_sum = array();
            $items3 = array();
            $items3_sum = array();
            $items4 = array();
            $items4_sum = array();
            $itemsSrc = array();
            $itemsSrc_sum = array();
            $rsltItems = array();
            $rsltItems2 = array();
            $masterGates = array();
            $childGates = array();
            $childGates2 = array();
            $childGates2_sum = array();
            $childGatesRsltItems = array();
            $childGatesRsltItems2 = array();
            $masterTableInParams = array();
            $childTableInParams = array();
            $childTableInParamsRsltItems = array();
            $childTableInParamsRsltItems2 = array();
            $masterTableInValueParams = array();
            $childTableInValueParams = array();
            $childTableInValueParamsRsltItems = array();
            $childTableInValueParamsRsltItems2 = array();
            $masterAddValues = array();
            $masterAddFields = array();
            $mainElements = array();
            $mainInputs = array();
            if (sizeof($tmpReg) > 0) {
                foreach ($tmpReg as $row) {
                    foreach ($row as $key_reg => $val_reg) {
                        if ($key_reg != "transaksi_id") {
                            switch ($key_reg) {
                                case "main"://
                                    $main = $main + unserialize(base64_decode($val_reg));
                                    $mainOriginal = $main;
                                    break;
                                case "items"://
                                    $items = $items + unserialize(base64_decode($val_reg));
                                    $itemsOriginal = $items;
                                    break;
                                case "items2"://
                                    $items2 = $items2 + unserialize(base64_decode($val_reg));
                                    break;
                                case "items3"://
                                    $items3 = $items3 + unserialize(base64_decode($val_reg));
                                    break;
                                case "items3_sum"://
                                    $items3_sum = $items3_sum + unserialize(base64_decode($val_reg));
                                    break;
                                case "items4"://
                                    $items4 = $items4 + unserialize(base64_decode($val_reg));
                                    break;
                                case "items4_sum"://
                                    $items4_sum = $items4_sum + unserialize(base64_decode($val_reg));
                                    break;
                                case "itemsSrc"://
                                    $itemsSrc = $itemsSrc + unserialize(base64_decode($val_reg));
                                    break;
                                case "itemsSrc_sum"://
                                    $itemsSrc_sum = $itemsSrc_sum + unserialize(base64_decode($val_reg));
                                    break;
                                case "rsltItems"://
                                    $rsltItems = $rsltItems + unserialize(base64_decode($val_reg));
                                    break;
                                case "rsltItems2"://
                                    $rsltItems2 = $rsltItems2 + unserialize(base64_decode($val_reg));
                                    break;
                                case "items2_sum"://
                                    $items2_sum = $items2_sum + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_master"://
                                    $masterTableInParams = $masterTableInParams + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail"://
                                    $childTableInParams = $childTableInParams + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail_rsltItems"://
                                    $childTableInParamsRsltItems = $childTableInParamsRsltItems + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail_rsltItems2"://
                                    $childTableInParamsRsltItems2 = $childTableInParamsRsltItems2 + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_master_values"://
                                    $masterTableInValueParams = $masterTableInValueParams + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail_values"://
                                    $childTableInValueParams = $childTableInValueParams + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail_values_rsltItems"://
                                    $childTableInValueParamsRsltItems = $childTableInValueParamsRsltItems + unserialize(base64_decode($val_reg));
                                    break;
                                case "tableIn_detail_values_rsltItems2"://
                                    $childTableInValueParamsRsltItems2 = $childTableInValueParamsRsltItems2 + unserialize(base64_decode($val_reg));
                                    break;
                                case "main_add_values"://
                                    $masterAddValues = $masterAddValues + unserialize(base64_decode($val_reg));
                                    break;
                                case "main_add_fields"://
                                    $masterAddFields = $masterAddFields + unserialize(base64_decode($val_reg));
                                    break;
                                case "main_elements"://
                                    $mainElements = unserialize(base64_decode($val_reg));
                                    break;
                                case "main_inputs"://
                                    $mainInputs = unserialize(base64_decode($val_reg));
                                    break;

                                case "item_price"://
                                    $item_price = unserialize(base64_decode($val_reg));
                                    break;
                                case "itemPrice"://
                                    $itemPrice = unserialize(base64_decode($val_reg));
                                    break;
                                case "coreBuilder"://
                                    $coreBuilder = unserialize(base64_decode($val_reg));
                                    break;
                                case "diskon_event"://
                                    $diskon_event = unserialize(base64_decode($val_reg));
                                    break;
                                case "cashback_event"://
                                    $cashback_event = unserialize(base64_decode($val_reg));
                                    break;
                            }
                        }
                    }

                }

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


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


            //==revalidate items
            $this->load->library("FieldCalculator");
            $this->load->helper("he_angka");
            $cal = new FieldCalculator();


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

                    if (array_key_exists($id, $validItems)) {
                        $items[$id]['jml'] = $validItems[$id];
                        $items[$id]['max_jml'] = $validItems[$id];
                        $items[$id]['sent_jml'] = $validItemSends[$id];
                        if (sizeof($editableFields) > 0) {
                            foreach ($editableFields as $fName) {
                                $items[$id]["max_$fName"] = isset($iSpec[$fName]) ? $iSpec[$fName] : 0;
                            }
                        }

                        if (sizeof($measurementDetails)) {
                            if (in_array($stepNumber, $measurementDetails["allowView"]) && isset($measurementDetails[$tipeSize])) {
                                $selectedColl = $measurementDetails[$tipeSize];
                                foreach ($selectedColl as $colSelected => $tempHelper) {
                                    //                                    cekHitam("$heAngka");

                                    foreach ($tempHelper as $newKey => $heAngka) {
                                        cekHitam($newKey);
                                        $items[$id][$newKey] = $heAngka($iSpec[$colSelected]);
                                    }
                                    //
                                }
                            }

                        }


                        //                        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;
                        //
                        //                        }
                        //                        //                    echo lgShowAlert("isi subtotal: $subtotal");
                        //                        $items[$id]['subtotal'] = $subtotal;
                    }
                    else {
                        unset($items[$id]);
                        unset($childGates[$id]);
                        unset($childTableInParams[$id]);
                        unset($childTableInValueParams[$id]);

                    }


                }
            }


            //region session-swapper
            $swappers = array(
                "main" => $main,
                "items" => $items,
                "items2" => $items2,
                "items2_sum" => $items2_sum,
                "items3" => $items3,
                "items3_sum" => $items3_sum,
                "items4" => $items4,
                "items4_sum" => $items4_sum,
                "itemsSrc" => $itemsSrc,
                "itemsSrc_sum" => $itemsSrc_sum,
                "rsltItems" => $rsltItems,
                "rsltItems2" => $rsltItems2,
                "extractedItems" => $extractedItems,
                "tableIn_master" => $masterTableInParams,
                "tableIn_detail" => $childTableInParams,
                "tableIn_detail_rsltItems" => $childTableInParamsRsltItems,
                "tableIn_detail_rsltItems2" => $childTableInParamsRsltItems2,
                "tableIn_master_values" => $masterTableInValueParams,
                "tableIn_detail_values" => $childTableInValueParams,
                "tableIn_detail_values_rsltItems" => $childTableInValueParamsRsltItems,
                "tableIn_detail_values_rsltItems2" => $childTableInValueParamsRsltItems2,
                "main_add_values" => $masterAddValues,
                "main_add_fields" => $masterAddFields,
                "main_elements" => $mainElements,
                "main_inputs" => $mainInputs,
                "extSteps" => $extSteps,
                "paySrcs" => $paySrcs,
                "mode" => $editMode,
                "mainOriginal" => $mainOriginal,
                "itemsOriginal" => $itemsOriginal,
                //-----
                "item_price" => $item_price,
                "itemPrice" => $itemPrice,
                "coreBuilder" => $coreBuilder,
                "diskon_event" => $diskon_event,
                "cashback_event" => $cashback_event,
            );
            foreach ($swappers as $targetVar => $src) {
                $_SESSION[$cCode][$targetVar] = $src;
            }
            //endregion


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

            if (sizeof($_SESSION[$cCode]['items']) > 0) {
                foreach ($_SESSION[$cCode]['items'] as $xid => $iSpec) {
                    $id = $iSpec['id'];
                    $_SESSION[$cCode]['main']['harga'] += ($iSpec['jml'] * $iSpec['harga']);
                    //                    $_SESSION[$cCode]['main']['harga'] += ($iSpec['jml'] * $iSpec['harga']);
                }
            }

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


        $link = MODUL_PATH . "Create/index/" . $this->jenisTr;

        topRedirect($link);

        die();


    }
    public function editForm()
    {

        if (!isset($this->session->login['id'])) {
            redirect(base_url() . "Login");
        }
//        arrPrint($this->uri->segment_array());
        //cekHitam("putihhh");
        //===pageView options
        if (!isset($_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'])) {
            $viewModeConfig = isset($this->configUi[$this->jenisTr]['defaultViewMode']) ? $this->configUi[$this->jenisTr]['defaultViewMode'] : "list";
            $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] = isset($_GET['viewMode']) ? $_GET['viewMode'] : $viewModeConfig;
        }
        //        die();
        $viewModeSpec = array(
            "icon" => "",
            "url" => "",
        );
        $thisPage = base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3);
        switch ($_SESSION["opt_" . $this->jenisTr]['opt']['viewMode']) {
            case "list":
                $viewModeSpec = array(
                    "icon" => "	glyphicon glyphicon-th-large",
                    "url" => $thisPage . "?viewMode=thumbnail",
                );
                break;
            case "thumbnail":
                $viewModeSpec = array(
                    "icon" => "glyphicon glyphicon-align-justify",
                    "url" => $thisPage . "?viewMode=list",
                );
                break;
        }
        $viewModeSwitch = "<a href='javascript:void(0)' onclick=\"location.href='" . $viewModeSpec['url'] . "';\"><span class='" . $viewModeSpec['icon'] . "'></span></a>";


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

        $jenisTr = $this->uri->segment(4);
        $this->jenisTr = $this->uri->segment(4);
        $cCode = "_TR_" . $this->jenisTr;
        //        arrPrint($_SESSION[$cCode]);
        //        matiHere();
        //        heInitCart($jenisTr);
        //        arrPrint($jenisTr);
        heInitGates($this->jenisTr);

        $pairRegistries = isset($this->configUi[$jenisTr]['pairRegistries']) ? $this->configUi[$jenisTr]['pairRegistries'] : array();
        $historyFields = $this->configUi[$jenisTr]['shortHistoryFields'];
        $glanceHistoryFields = isset($this->configUi[$jenisTr]['glanceHistoryFields']) ? $this->configUi[$jenisTr]['glanceHistoryFields'] : array("nomer" => "receipt no");
        $glanceHistoryFields2 = array("nomer" => "receipt no"); //init;
        $selectorProcessor = base_url() . $this->configUi[$jenisTr]['selectorProcessor'] . "/$jenisTr";
        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        if ($isMob) {
            $historyFields = isset($this->configUi[$jenisTr]['compactHistoryFields']) ? $this->configUi[$jenisTr]['compactHistoryFields'] : array();
        }
        //
        //region lookup on-going transactions

        $arrayOnprogress = array();
        $progressFields = $historyFields;
        $progressFields['state'] = "status";
        $progressFields['action'] = "action";
        $steps = $this->configUi[$jenisTr]['steps'];
        //        if (sizeof($steps) > 1) {
        //            $stepCodes = array();
        //            $jmlStep = count($steps);
        //            foreach ($steps as $stepNumber => $stepSpec) {
        //                if ($stepNumber < $jmlStep) {
        //                    $stepCodes[] = $stepSpec['target'];
        //                }
        //
        //            }
        //
        //
        //            $this->load->model("MdlTransaksi");
        //            $tr = new MdlTransaksi();
        //            $tr->addFilter("jenis_top='" . $steps[1]['target'] . "'");
        //            $tr->addFilter("next_substep_code<>''");
        //            $tmpHist = $tr->lookupRecentUndoneEntries_joined($this->session->login['cabang_id'], $this->session->login['gudang_id'])->result();
        //
        //            $arrayOnprogress = array();
        //            if (sizeof($tmpHist) > 0) {
        //                foreach ($tmpHist as $row) {
        //                    $tmp = array();
        //                    foreach ($historyFields as $fName => $fLabel) {
        //                        //$tmp[$fName] = $row->$fName;
        //                        $tmp[$fName] = formatField($fName, $row->$fName);
        //                    }
        ////                    $tmp['state'] = $this->configUi[$jenisTr]['steps'][$row->step_current]['stateLabel'];
        //                    if ($row->sub_step_number > 0) {
        //                        $tmp['state'] = "<span style='color:" . $this->configUi[$jenisTr]['steps'][$row->sub_step_number]['stateColor'] . "'>" . $this->configUi[$jenisTr]['steps'][$row->sub_step_number]['stateLabel'] . "</span>";
        //                        $tmp['state'] .= "<br>" . createStateSign($row->sub_step_number, $row->step_avail);
        //                    } else {
        //                        $tmp['state'] = "<span style='color:#777777'>canceled</span>";
        //                    }
        //
        //                    $tmp['action'] = "";
        //                    $nextStepNum = ($row->next_substep_num);
        //                    $currentStepNum = ($row->sub_step_number);
        ////                    echo $currentStepNum." vs ".$nextStepNum."<br>";
        //                    $allowJoin = isset($this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin']) && $this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin'] == true ? $this->configUi[$jenisTr]["steps"][$nextStepNum]['allowJoin'] : false;
        //
        //
        //                    $allowFollowup = false;
        //                    if ($row->sub_step_number > 0) {
        //                        if (in_array($this->configUi[$jenisTr]['steps'][$currentStepNum]['userGroup'], $this->session->login['membership'])) {
        //                            $allowFollowup = true;
        //                            $actionLabel = "review " . $this->configUi[$jenisTr]['steps'][$currentStepNum]['label'];
        //                        }
        //                    }
        //
        //                    if (isset($this->configUi[$jenisTr]['steps'][$nextStepNum])) {
        //                        if (in_array($this->configUi[$jenisTr]['steps'][$nextStepNum]['userGroup'], $this->session->login['membership'])) {
        //                            $allowFollowup = true;
        //                            $actionLabel = $this->configUi[$jenisTr]['steps'][$nextStepNum]['actionLabel'];
        //
        //                        }
        //                    }
        //
        //                    if ($allowFollowup) {
        //                        $stepLabel = $this->configUi[$jenisTr]['steps'][$nextStepNum]['label'];
        //
        //                        $followupLink = "document.getElementById('result').src=('" . base_url() . "Transaksi/followupPrePreview/" . $row->transaksi_id . "/$nextStepNum/" . $row->sub_step_number . "');";
        ////                        $tmp['action'] = "<a class='btn btn-primary btn-block' title='turn this entry into $stepLabel' href='javascript:void(0)' onClick =\"$followupLink\">" . $actionLabel . "</a>";
        //                        $tmp['action'] = "<div class='input-group'>";
        //                        $tmp['action'] .= "<a class='btn btn-primary btn-block' title='turn this entry into $stepLabel' href='javascript:void(0)' onClick =\"$followupLink\">" . $actionLabel . "</a>";
        //                        if ($allowJoin) {
        //                            $tmp['action'] .= "<span class='input-group-addon'>";
        //                            $tmp['action'] .= "<a title='process many items at once' href='" . base_url() . "Transaksi/viewIncomplete/" . $this->jenisTr . "/$currentStepNum'><span class='fa fa-dedent'></span></a>";
        //                            $tmp['action'] .= "</span class='input-group-addon'>";
        //                        }
        //                    }
        //                    $arrayOnprogress[] = $tmp;
        //                }
        //            }
        //        } else {
        //            $arrayOnprogress = array();
        //        }
        //endregion

        //

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

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


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

        //
        //region lookup histories
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
        $tr->addFilter("transaksi.gudang_id='" . $this->session->login['gudang_id'] . "'");
        $tr->addFilter("transaksi.jenis_master='" . $this->jenisTr . "'");

        //        $tr->addFilter("transaksi.next_step_code=''");
        $tmpHist = $tr->lookupRecentHistories()->result();

        // print_r($tmpHist);die();
        $arrayHistory = array();
        if (sizeof($tmpHist) > 0) {
            if (sizeof($pairRegistries) > 0) {
                $arrTransID = array();
                $arrIndexID = array();
                foreach ($tmpHist as $row) {
                    $req_index = isset($row->indexing_registry) ? blobDecode($row->indexing_registry) : array();
                    foreach ($pairRegistries as $reg) {
                        if (isset($req_index[$reg])) {
                            $arrIndexID[] = $req_index[$reg];
                        }
                    }
                    $arrTransID[] = $row->id;
                }
                $tmpReg_result = array();
                if (sizeof($arrIndexID) > 0) {
                    $trReg = new MdlTransaksi();
                    $trReg->setFilters(array());
                    $trReg->addFilter("trash='0'");
                    $trReg->addFilter("id in ('" . implode("','", $arrIndexID) . "')");
                    $tmpReg = $trReg->lookupRegistries()->result();

                    if (sizeof($tmpReg) > 0) {
                        foreach ($tmpReg as $regRow) {
                            $tmpReg_result[$regRow->transaksi_id] = blobDecode($regRow->values);
                        }
                    }
                }
            }
            foreach ($tmpHist as $row) {

                if (isset($tmpReg_result[$row->id]) && sizeof($tmpReg_result[$row->id]) > 0) {
                    foreach ($tmpReg_result[$row->id] as $k => $v) {
                        if (!isset($row->$k)) {
                            $row->$k = $v;
                        }
                    }
                }


                $tmp = array();
                foreach ($historyFields as $fName => $fLabel) {
                    $tmp[$fName] = isset($row->$fName) ? formatField($fName, $row->$fName) : formatField($fName, 0);
                }
                $arrayHistory[] = $tmp;
            }
        }

        //endregion
        //


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

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


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

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

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

        $allowTmpSave = isset($this->configUi[$jenisTr]['allowTmpSave']) ? $this->configUi[$jenisTr]['allowTmpSave'] : false;
        //region prepare params to viewer

        $data = array(
            "mode" => $this->uri->segment(2),
            "isMobile" => $isMob,
            "errMsg" => $this->session->errMsg,
            //            "template" => $this->configUi[$jenisTr]["template"],
            "template" => "application/template/transaksi_edit.html",
            "title" => " ",
            "subTitle" => "Edit " . $this->configUi[$jenisTr]["steps"][1]['label'],
            "jenisTr" => $jenisTr,
            "jenisTransaksi" => $jenisTr,
            "selectedID" => $this->uri->segment(3),
            "trName" => $this->configUi[$jenisTr]["label"],
            //            "selectorCaller" => base_url() . "_selectorItem/" . $this->configUi[$jenisTr]["selectorCaller"] . "/$jenisTr/" . $this->configUi[$jenisTr]["selectorModel"],
            "selectorCaller" => base_url() . $this->configUi[$jenisTr]["selectorCaller"] . "/$jenisTr/" . $this->configUi[$jenisTr]["selectorModel"],

            "selectorLabel" => $this->configUi[$jenisTr]["selectorLabel"],
            "selectorCaller2" => isset($this->configUi[$jenisTr]["selectorCaller2"]) ? base_url() . $this->configUi[$jenisTr]["selectorCaller2"] . "/$jenisTr/" . $this->configUi[$jenisTr]["selectorModel2"] : "",
            //            "pihakCaller" => base_url() . "_selectorPihak/" . $this->configUi[$jenisTr]["pihakCaller"] . "/$jenisTr/" . $this->configUi[$jenisTr]["pihakModel"],
            "selectorLabel2" => isset($this->configUi[$jenisTr]["selectorLabel2"]) ? $this->configUi[$jenisTr]["selectorLabel2"] : "",
            "pihakCaller" => base_url() . $this->configUi[$jenisTr]["pihakCaller"] . "/$jenisTr/" . $this->configUi[$jenisTr]["pihakModel"],
            "pihakCallerDelete" => base_url() . "Selectors/_processPihak/remove/$jenisTr",
            // "pihakLabel"=>$this->configUi[$jenisTr]["pihakLabel"],
            "pihakLabel" => isset($_SESSION[$cCode]['main']['pihakName']) ? $_SESSION[$cCode]['main']['pihakName'] . "(" . $this->configUi[$jenisTr]["pihakLabel"] . ")" : $this->configUi[$jenisTr]["pihakLabel"],
            "arrayHistoryLabels" => $historyFields,
            "arrayHistory" => $arrayHistory,
            "arrayProgressLabels" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] == "list" ? $progressFields : $glanceHistoryFields,
            "arrayProgress2Labels" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'] == "list" ? $progress2Fields : $glanceHistoryFields2,
            "arrayOnProgress" => $arrayOnprogress,
            "arrayOnProgress2" => $arrayOnprogress2,
            "reqFormTarget" => isset($reqFormTarget) ? $reqFormTarget : "",

            //            "strPaymentMethod" => $strPaymentMethod,
            "extTool" => $extTool,
            "columnRecorderTarget" => base_url() . "ValueGate/recordColumn/" . $this->jenisTr . "/",
            "defaultDescription" => isset($_SESSION[$cCode]['main']['description']) ? $_SESSION[$cCode]['main']['description'] : "",
            "allowJoin" => isset($this->configUi[$jenisTr]["steps"][1]['allowJoin']) && $this->configUi[$jenisTr]["steps"][1]['allowJoin'] == true ? $this->configUi[$jenisTr]["steps"][1]['allowJoin'] : false,
            "allowTmpSave" => $allowTmpSave,
            "needToClear" => $needToClear,
            "addPihakStr" => $addPihakStr,
            "addItemStr" => $addItemStr,
            "mobScanStr" => $mobScanStr,
            "thisPage" => base_url() . get_class($this) . "/" . $this->uri->segment(2) . "/" . $this->uri->segment(3),
            "viewMode" => $_SESSION["opt_" . $this->jenisTr]['opt']['viewMode'],
            "viewModeSwitch" => $viewModeSwitch,
            "barcodeSettings" => $barcodeSettings,
            "selectorProcessor" => $selectorProcessor,

        );
        //endregion
        //        arrPrint($data);
        $this->load->view("transaksi", $data);
        //        $this->session->errMsg = "";
    }

    // ini eksekutor yang baru, mengarah ke library transaksional---------------------------
    public function followupPrePreview()
    {
        $srcIdTr = $no = rtrim($this->uri->segment(5), "-");
        $stepNum = $stepNumber = $this->uri->segment(6);
        $currentStepNum = $this->uri->segment(7);
        $rawBuilderURL = url_cleanup(blobEncode(current_url()));
        $cCode = $this->cCode;

        // arrPrint($this->uri->segment_array());
        // matiHere();
        //-------
        $this->load->library("Transaksional");
        $lt = New Transaksional();
        //-------
        $sessionData[$this->cCode] = $_SESSION[$this->cCode];
        //-------
        $lt->setCCode($this->cCode);
        $lt->setModul($this->modul);
        $lt->setJenisTr($this->jenisTr);
        $lt->setCCodeData($sessionData);
        $lt->setStepNum($stepNum);
        $lt->setStepNumCurrent($currentStepNum);
        $lt->setTransaksiNumber($no);
        $lt->setConfigUiModul($this->configUi);
        $lt->setConfigLayoutModul($this->configLayout);
        $lt->setConfigCoreModul($this->configCore);
        $lt->setConfigValuesModul($this->configValues);
        $lt->setConfigCoreMaster($this->config->item('heTransaksi_core'));
        //-------
        $libResult = $lt->followupPrePreview();
        // arrPrint($libResult);
        // matiHere();
        $_SESSION[$cCode] = $libResult["sessionData"];
        //-------


        $mb = New MobileDetect();
        $isMob = $mb->isMobile();
        $mobileSupport = isset($this->configUi[$this->jenisTr]["mobileSupport"]) ? $this->configUi[$this->jenisTr]["mobileSupport"] : false;
        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>";
    }
    public function doFollowup_yang_lama_sebelum_auto_transaksi_unused()
    {
        $ipadd = $_SERVER['REMOTE_ADDR'];
        $starttime = microtime(true);
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

        $gmr = img_working();
        echo "\n" . 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'>");

        $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'] : 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

            $tokoID = $_SESSION[$cCode]['main']['tokoID'];
            $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];
            $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!"));
        }

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

        $this->load->library("Transaksional");
        $lt = New Transaksional();
        //-------
        $sessionData[$this->cCode] = $_SESSION[$this->cCode];
        //-------
        $lt->setCCode($this->cCode);
        $lt->setModul($this->modul);
        $lt->setJenisTr($this->jenisTr);
        $lt->setCCodeData($sessionData);
        $lt->setStepNum($stepNum);
        $lt->setStepNumCurrent($stepNumCurrent);
        $lt->setTransaksiNumber($no);
        $lt->setConfigUiModul($this->configUi);
        $lt->setConfigLayoutModul($this->configLayout);
        $lt->setConfigCoreModul($this->configCore);
        $lt->setConfigValuesModul($this->configValues);
        $lt->setConfigCoreMaster($this->config->item('heTransaksi_core'));
        //-------

        //region build table rekening
        if ($runCoreAkunting == true) {
            $lt->buildTableRekening();
        }
        //endregion

        /* ------------------------------
         * TRANSAKSIONAL TERJADI DI DALAM SINI
         * $dieForDebug = false; --------> kondisi normal transaksi bisa lanjot
         * untuk mematikan transksi di jadikan true
         * ------------------------*/
        $dieForDebug = false;
//        $dieForDebug = true;

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

        $libResult = $lt->doFollowup();

        $tmpNomorNota2 = isset($libResult["tmpNomerNota"]) ? $libResult["tmpNomerNota"] : "";
        $tmpTransaksiID = isset($libResult["transaksiId"]) ? $libResult["transaksiId"] : "";
        $tmpTransaksConectingiID = isset($libResult["transaksiIdConnecting"]) ? $libResult["transaksiIdConnecting"] : "";

        //==tampilkan receipt
        cekOrange("-- DONE -- $ipadd");
        if ($dieForDebug === true) {
            cekMerah( json_encode($libResult) );
            mati_disini(__FUNCTION__ . " *** under maintenance ***  <br> TUNGGU SEBENTAR YA... @" . __LINE__);
        }

        //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" => $tmpTransaksConectingiID,
            "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;

//        cekHere("this->jenisTr : " . $this->jenisTr);
//        cekHere("stepNum : " . $stepNum);
//      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!");

        $connectToApk = isset($this->configUi[$this->jenisTr]["steps"][$stepNum]["connectToApk"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNum]["connectToApk"] : array();

        if(!empty($connectToApk)){
            switch($stepNum){
                case "2":
//                    $response = array(
//                        "status" => 999,
//                        "toko_id" => $this->session->login['toko_id'],
//                        "nomor_referensi" => $_SESSION[$cCode]['tableIn_master']['nomer'],
//                        "nomer" => $libResult["sessionData"]['main']['nomer'],
//                        "oleh_id" => $this->session->login['id'],
//                        "oleh_nama" => $this->session->login['nama'],
//                        "seller_id" => $_SESSION[$cCode]['main']['logistikInternal'],
//                        "datetime" => date("Y-m-d H:i:s"),
//                        "seller_nama" => $_SESSION[$cCode]['main']['logistikInternal__nama'],
//                        "customer_id" => $_SESSION[$cCode]['main']['customerDetails'],
//                        "customer_nama" => $_SESSION[$cCode]['main']['customerDetails__nama'],
//                        "customer_alamat" => $_SESSION[$cCode]['main']['customerDetails__alamat_1'],
//                        "customer_telp" => $_SESSION[$cCode]['main']['customerDetails__tlp_1'],
//                        "produk_blob" => base64_encode(json_encode($_SESSION[$cCode]['items'])), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agakr bisa di urai di javascript
//                    );
//                    $sendToApk = $curl->_simple_call("post", ADM_DOMAIN . "/eusvc/Entries/writeDataLogistik", $response);
                    break;
                case "3":
//                    $response = array(
//                        "nomor_referensi" => $_SESSION[$cCode]['tableIn_master']['nomer'],
//                        "logistik_approve_nomer" => $libResult["sessionData"]['main']['nomer'],
//                        "logistik_approve_by_id" => $this->session->login['id'],
//                        "logistik_approve_by_nama" => $this->session->login['nama'],
//                    );
//                    $sendToApk = $curl->_simple_call("post", ADM_DOMAIN . "/eusvc/Entries/updateDataLogistik", $response);
//                    cekMerah("sendToApk");
//                    arrPrint($sendToApk);
                    break;
                case "4":

//                    $this->load->library("Curl");
//                    $curl = New Curl();
//                    $arrProduk = $libResult['sessionData']['items'];
//                    $response = array(
//                        "status" => 999,
//                        "toko_id" => $this->session->login['toko_id'],
//                        "nomor_referensi" => $_SESSION[$cCode]['tableIn_master']['nomer'],
//                        "nomer" => $libResult["sessionData"]['main']['nomer'],
//                        "oleh_id" => $this->session->login['id'],
//                        "oleh_nama" => $this->session->login['nama'],
//                        "seller_id" => $_SESSION[$cCode]['main']['logistikInternal'],
//                        "datetime" => date("Y-m-d H:i:s"),
//                        "seller_nama" => $_SESSION[$cCode]['main']['logistikInternal__nama'],
//                        "customer_id" => $_SESSION[$cCode]['main']['customerDetails'],
//                        "customer_nama" => $_SESSION[$cCode]['main']['customerDetails__nama'],
//                        "customer_alamat" => $_SESSION[$cCode]['main']['customerDetails__alamat_1'],
//                        "customer_telp" => $_SESSION[$cCode]['main']['customerDetails__tlp_1'],
//                        "produk_blob" => base64_encode(json_encode($arrProduk)), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agakr bisa di urai di javascript
//                    );
//                    $writeDataLogistik = $curl->_simple_call("post", ADM_DOMAIN."/run_sakura_apk/eusvc/Entries/writeDataLogistik", $response);
//
//                    $this->load->library("Curl");
//                    $curl = New Curl();
//                    $response = array(
//                        "status"            => 999,
//                        "toko_id"           => $libResult['sessionData']['main']['tokoID'],
//                        "validGrandTotal"   => $libResult['sessionData']['main']['piutang_dagang'],
//                        "nomor_referensi"   => $libResult['sessionData']['main']['nomer'],
//                        "referensi_id"      => $tmpTransaksiID,
//                        "oleh_id"           => $libResult['sessionData']['main']['olehID'],
//                        "oleh_nama"         => $libResult['sessionData']['main']['olehName'],
////                        "collector_id"      => $libResult['sessionData']['main']['penagihID'],
//                        "datetime"          => date("Y-m-d H:i:s"),
////                        "collector_nama"    => $libResult['sessionData']['main']['penagihName'],
//                        "customer_id"       => $libResult['sessionData']['main']['customerDetails'],
//                        "customer_nama"     => $libResult['sessionData']['main']['customerDetails__nama'],
//                        "customer_alamat"   => $libResult['sessionData']['main']['customerDetails__alamat_1'],
//                        "customer_telp"     => $libResult['sessionData']['main']['customerDetails__tlp_1'],
//                        "produk_blob"       => base64_encode(json_encode($arrProduk)), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agakr bisa di urai di javascript
//                    );
//                    $writeDataCollector = $curl->_simple_call("post", ADM_DOMAIN."/run_sakura_apk/eusvc/Entries/writeDataCollector", $response);

                    //cek konsumen VA
                    $this->load->model("MdlCustomer");
                    $cus = new MdlCustomer();
                    $cus->addFilter("id=".$libResult['sessionData']['main']['customerDetails']);
                    $tmpCus = $cus->lookupAll()->result();

                    arrPrint($tmpCus[0]);
                    matiHere("STOP DULU");

                    break;
            }
        }

        // matiHere("stok dulu cek apk ");
        // cekMerah("response yang di kirim");
        // arrPrintWebs($response);
        // cekMerah("stepNum: $stepNum");
        // cekMerah("connectToApk");
        // arrPrint($connectToApk);
        // matiHere("mati dulu cek API");

        if (isset($_SESSION[$cCode])) {
            if (isset($_SESSION[$cCode]["main"]["print_barcode"]) && $_SESSION[$cCode]["main"]["print_barcode"] == "1") {
                echo "<script>";
                echo "window.open('" . base_url() . "Addons/BarcodePrinter/doPrint/?FromTransaksi=" . $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);
        }


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

        $rejectException = $this->config->item('heTransaksi_rejectException') != NULL ? $this->config->item('heTransaksi_rejectException') : array();
        $referenceRevertConfigs = isset($this->configUi[$jenisTr]['referenceRevert']) ? $this->configUi[$jenisTr]['referenceRevert'] : array();
        $prepConfigs = null != $this->config->item('hePreProcessors') ? $this->config->item('hePreProcessors') : array();
        $postConfigs = null != $this->config->item('hePostProcessors') ? $this->config->item('hePostProcessors') : array();


        //-------
        $this->load->library("Transaksional");
        $lt = New Transaksional();
        //-------
        $sessionData[$this->cCode] = $_SESSION[$this->cCode];
        //-------
        $lt->setCCode($this->cCode);
        $lt->setModul($this->modul);
        $lt->setJenisTr($this->jenisTr);
        $lt->setCCodeData($sessionData);
        $lt->setStepNum($masterTargetStepNum_con);
        $lt->setStepNumCurrent($stepNumCurrent);
        $lt->setMasterTargetStepNum($masterTargetStepNum);
        $lt->setChildTargetStepNum($childTargetStepNum);
        $lt->setTransaksiNumber($no);
        $lt->setConfigUiModul($this->configUi);
        $lt->setConfigLayoutModul($this->configLayout);
        $lt->setConfigCoreModul($this->configCore);
        $lt->setConfigValuesModul($this->configValues);
        $lt->setConfigCoreMaster($this->config->item('heTransaksi_core'));
        //-------


        $this->db->trans_start();


        $libResult = $lt->doRevert();
        $tmpNomorNota2 = $libResult["tmpNomerNota"];
        $tmpTransaksiID = $libResult["transaksiId"];


        //==tampilkan receipt
        cekMerah("-- DONE --");


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


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

        unset($this->session->errMsg);
    }
    public function doRevertAll()
    {
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }


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


        $this->db->trans_start();

        //-------
        $this->load->library("Transaksional");
        $lt = New Transaksional();
        //-------
        $sessionData[$this->cCode] = $_SESSION[$this->cCode];
        //-------
        $lt->setCCode($this->cCode);
        $lt->setModul($this->modul);
        $lt->setJenisTr($this->jenisTr);
        $lt->setCCodeData($sessionData);
        $lt->setStepNum($stepNum);
        $lt->setStepNumCurrent($stepNumCurrent);
        $lt->setMasterTargetStepNum($masterTargetStepNum);
        $lt->setChildTargetStepNum($childTargetStepNum);
        $lt->setTransaksiNumber($no);
        $lt->setConfigUiModul($this->configUi);
        $lt->setConfigLayoutModul($this->configLayout);
        $lt->setConfigCoreModul($this->configCore);
        $lt->setConfigValuesModul($this->configValues);
        $lt->setConfigCoreMaster($this->config->item('heTransaksi_core'));
        //-------
        $libResult = $lt->doRevertAll();
        $tmpNomorNota = $libResult["tmpNomerNota"];
        $tmpTransaksiID = $libResult["transaksiId"];
        //-------


//        mati_disini("DONE :: $cCode :: $jenisTr_con :: $stepNumCurrent");

        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");


        if (isset($_SESSION[$cCode])) {
            unset($_SESSION[$cCode]);
        }
        if (isset($oldCode)) {
            if (isset($_SESSION[$oldCode])) {
                unset($_SESSION[$oldCode]);
            }
        }
        $arrAlert = array(
            "type" => "success",
            "title" => "Transaction updated",
            //                        "html" => "your order has been saved and ready to process",
            "html" => $this->session->errMsg,
            "timer" => "1500",
            "showConfirmButton" => false,
            "allowOutsideClick" => false,
        );

        echo swalAlert($arrAlert);
        echo topReload();
        unset($this->session->errMsg);

    }
    public function doPreEdit()
    {
        $this->load->model("MdlTransaksi");

        $no = rtrim($this->uri->segment(5), "-");
        $stepNum = $stepNumber = $this->uri->segment(6);
        $stepNumCurrent = $currentStepNum = $this->uri->segment(7);
        $rawBuilderURL = blobEncode(current_url());
        $editMode = array(
            "edit" => "$no",
        );
        //-------
        $cCode = $this->cCode;
        //-------
        $this->load->library("Transaksional");
        $lt = New Transaksional();
        //-------
        $sessionData[$this->cCode] = $_SESSION[$this->cCode];
        //-------
        $lt->setCCode($this->cCode);
        $lt->setModul($this->modul);
        $lt->setJenisTr($this->jenisTr);
        $lt->setCCodeData($sessionData);
        $lt->setStepNum($stepNum);
        $lt->setStepNumCurrent($stepNumCurrent);
        $lt->setTransaksiNumber($no);
        $lt->setConfigUiModul($this->configUi);
        $lt->setConfigLayoutModul($this->configLayout);
        $lt->setConfigCoreModul($this->configCore);
        $lt->setConfigValuesModul($this->configValues);
        $lt->setConfigCoreMaster($this->config->item('heTransaksi_core'));
        //-------
        $libResult = $lt->doPreEdit();
        $_SESSION[$cCode] = $libResult["sessionData"];

        $link = MODUL_PATH . "Create/index/" . $this->jenisTr;

//mati_disini("HAHAH");
        topRedirect($link);
        die();


    }

    //---------------
    public function followupPrePreviewAuto_ORI_unused($trID, $nextStepNumber, $fromStepNumber)
    {
        $no = $trID;
        $stepNumber = $nextStepNumber;
        $currentStepNum = $fromStepNumber;
        $rawBuilderURL = blobEncode(current_url());


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

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

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


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

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

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

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

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

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

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

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


            //            arrPrint($tempLocker);
            //endregion

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

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

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

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


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


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


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

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

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


            $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");
                foreach ($tmpTr as $row) {
                    if (!isset($validItems[$row->produk_id])) {
                        $validItems[$row->produk_id] = 0;
                    }
                    if (!isset($validItemSends[$row->produk_id])) {
                        $validItemSends[$row->produk_id] = 0;
                    }
                    if (!isset($validItemCancels[$row->produk_id])) {
                        $validItemCancels[$row->produk_id] = 0;
                    }
                    if (!isset($validItemReqCancels[$row->produk_id])) {
                        $validItemReqCancels[$row->produk_id] = 0;
                    }
                    if (!isset($validItemPackeds[$row->produk_id])) {
                        $validItemPackeds[$row->produk_id] = 0;
                    }
                    if (!isset($validItemPreCancels[$row->produk_id])) {
                        $validItemPreCancels[$row->produk_id] = 0;
                    }

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

            //==revalidate items
            $this->load->library("FieldCalculator");
            $this->load->helper("he_angka");
            $cal = new FieldCalculator();

            $itemChildData = array();
            if (sizeof($items) > 0) {

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

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

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


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

                                    }
                                    else {
                                        if (isset($tmp[$val2])) {
                                            $newSrc = str_replace($val2, $items[$val2], $newSrc);

                                        }
                                        else {
                                            $newSrc = str_replace($val2, "0", $newSrc);

                                        }
                                    }


                                }
                                $subtotal = $cal->calculate($newSrc);


                            }
                            else {
                                //                            echo lgShowAlert("memasang subtotal dari $subAmountConfig");
                                $subtotal = $items[$id][$subAmountConfig];

                            }
                        }
                        else {
                            //                        echo lgShowAlert("tidak mengapa-apakan subtotal");
                            $subtotal = 0;

                        }

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

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

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

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


                    }
                    else {
                        unset($items[$id]);
                        unset($items2[$id]);
                        unset($childGates[$id]);
                        unset($childTableInParams[$id]);
                        unset($childTableInValueParams[$id]);

                    }
                }

//cekKuning($items2_sum);
                cekPink($items2);
                if (sizeof($itemsKomposisi) > 0) {
                    $items2_sum = array();// supplies-nya...
                    $items3_sum = array();// biaya-nya...
                    foreach ($items2 as $pID => $pSpec) {
                        foreach ($pSpec as $jenis => $jSpec) {
                            foreach ($jSpec as $eSpec) {
                                if ($jenis == "produk") {
                                    if (!isset($items2_sum[$eSpec['id']])) {
                                        $items2_sum[$eSpec['id']] = $eSpec;
                                        $items2_sum[$eSpec['id']]['jml'] = 0;
                                        $items2_sum[$eSpec['id']]['produk_ids'] = array();
                                    }
                                    $items2_sum[$eSpec['id']]['jml'] += $eSpec['jml'];
                                    $items2_sum[$eSpec['id']]['produk_ids'][$pID] = $pID;

                                    cekBiru("pID: " . $eSpec['id'] . " jml: " . $eSpec['jml']);
                                }
                                if ($jenis == "biaya") {
                                    if (!isset($items3_sum[$eSpec['id']])) {
                                        $items3_sum[$eSpec['id']] = $eSpec;
                                        $items3_sum[$eSpec['id']]['jml'] = 0;
                                        $items3_sum[$eSpec['id']]['sub_nilai'] = 0;
                                        $items3_sum[$eSpec['id']]['produk_ids'] = array();
                                    }
                                    $items3_sum[$eSpec['id']]['jml'] += $eSpec['jml'];
                                    $items3_sum[$eSpec['id']]['sub_nilai'] += $eSpec['sub_nilai'];
                                    $items3_sum[$eSpec['id']]['produk_ids'][$pID] = $pID;
                                }
                            }
                        }
                    }
                }

            }

            if (sizeof($itemsChild) > 0 && ($itemsChildGate == 'main')) {

                $fieldAlias = isset($this->configUi[$this->jenisTr]["shopingCartDetailFields"][$stepNumber]['fieldAlias']) ? $this->configUi[$this->jenisTr]["shopingCartDetailFields"][$stepNumber]['fieldAlias'] : $itemsChild;//dipake detil pembelian aset
                foreach ($fieldAlias as $col => $col_label) {
                    $itemChildData[$main['pihakMainRulesID']][1][$col] = isset($main[$col_label]) ? $main[$col_label] : "";
                }
                $itemChildData[$main['pihakMainRulesID']][1]["jml"] = 1;
                $itemChildData[$main['pihakMainRulesID']][1]["qty"] = 1;
                $itemChildData[$main['pihakMainRulesID']][1]["folders"] = $main['pihakID'];
//                cekBiru("main");
            }

            //region session-swapper
            unset($main["nilai_pembulatan"]);
            $swappers = array(
                "main" => $main,
                "items" => $items,
                "items2" => $items2,
                "items2_sum" => $items2_sum,
                "items3" => $items3,
                "items3_sum" => $items3_sum,
                "items4_sum" => $items4_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,
                "main_add_fields" => $masterAddFields,
                "main_elements" => $mainElements,
                "main_inputs" => $mainInputs,
                "extSteps" => $extSteps,
                "paySrcs" => $paySrcs,
                "lockerPayment" => $tempBtnUndo,
                "items_komposisi" => $itemsKomposisi,
            );
            foreach ($swappers as $targetVar => $src) {
                $_SESSION[$cCode][$targetVar] = $src;
            }
            //endregion

            $this->load->helper("he_value_builder");

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

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

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

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

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

            cekMerah("LINE: " . __LINE__);
        }
        else {
            die(lgShowAlert("No such transaction. You may want to refresh the browser to re-fetch actual content."));
        }
    }
    public function doFollowup_2_unused($trID, $nextStepNumber, $fromStepNumber)
    {
        echo "<script>top.writeProgress('MEMULAI PROSES FOLLOWUP....');</script>";
        $starttime = microtime(true);
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

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


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

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

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

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

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

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

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

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

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

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


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


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


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


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


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

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

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

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


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

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


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


        //region build table rekening
//        $buildTablesMaster = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'] : array();
//        $buildTablesDetail = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
//
//        //arrPrint($buildTablesMaster);
//
//        $addMasterTables = array(
//            "rugilaba",
//            "laba ditahan",
//            "rugilaba lain lain",
//        );
//        foreach ($addMasterTables as $trek) {
//            $buildTablesMaster[] = array(
//                "comName" => "RugiLaba",
//                "loop" => array(
//                    "$trek" => .0,
//                ),
//            );
//        }
//
//        if (sizeof($buildTablesMaster) > 0) {
//            foreach ($buildTablesMaster as $buildTablesMaster_specs) {
//                $mdlName = $buildTablesMaster_specs['comName'];
//                if (substr($mdlName, 0, 1) == "{") {
//                    //                        cekkuning("mengandung kurawal");
//                    $mdlName = trim($mdlName, "{");
//                    $mdlName = trim($mdlName, "}");
//                    $mdlName = str_replace($mdlName, $_SESSION[$cCode]['main'][$mdlName], $mdlName);
//                }
//                else {
//                    //                        cekkuning("TIDAK mengandung kurawal");
//                }
//                $mdlName = "Com" . $mdlName;
//                cekHitam("model: $mdlName");
//
//
//                if (isset($buildTablesMaster_specs['loop'])) {
//                    foreach ($buildTablesMaster_specs['loop'] as $key => $val) {
//                        unset($buildTablesMaster_specs['loop'][$key]);
//                        //                        if (isset($_SESSION[$cCode]['main'][$key])) {
//                        if (substr($key, 0, 1) == "{") {
//                            $key = trim($key, "{");
//                            $key = trim($key, "}");
//                            $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
//                        }
//                        $buildTablesMaster_specs['loop'][$key] = $val;
//                        //                        }
//                    }
//                }
//
//                $this->load->model("Coms/" . $mdlName);
//                $m = new $mdlName();
//                if (method_exists($m, "getTableNameMaster")) {
//                    if (sizeof($m->getTableNameMaster())) {
//                        $m->buildTables($buildTablesMaster_specs);
//                    }
//                }
//            }
//        }
//
//        if (sizeof($buildTablesDetail) > 0) {
//            foreach ($buildTablesDetail as $buildTablesDetail_specs) {
//                foreach ($_SESSION[$cCode]['items'] as $itemSpec) {
//
//                    $mdlName = $buildTablesDetail_specs['comName'];
//                    if (substr($mdlName, 0, 1) == "{") {
//                        $mdlName = trim($mdlName, "{");
//                        $mdlName = trim($mdlName, "}");
//                        $mdlName = str_replace($mdlName, $itemSpec[$mdlName], $mdlName);
//                    }
//
//                    if (isset($buildTablesDetail_specs['loop'])) {
//                        foreach ($buildTablesDetail_specs['loop'] as $key => $val) {
//                            unset($buildTablesDetail_specs['loop'][$key]);
//
//                            if (substr($key, 0, 1) == "{") {
//                                $key = trim($key, "{");
//                                $key = trim($key, "}");
//                                $key = str_replace($key, $itemSpec[$key], $key);
//                            }
//                            $buildTablesDetail_specs['loop'][$key] = $val;
//                            cekHitam("LINE: " . __LINE__ . " ::sini bukan??  akan build tabel detail $key");
//
//                        }
//                    }
//
//
//                    $mdlName = "Com" . $mdlName;
//                    $this->load->model("Coms/" . $mdlName);
//                    $m = new $mdlName();
//                    if (method_exists($m, "getTableNameMaster")) {
//                        if (sizeof($m->getTableNameMaster())) {
//                            $m->buildTables($buildTablesDetail_specs);
//                            arrPrint($buildTablesDetail_specs);
//                            cekHitam(":: build tabel detail");
//                        }
//                    }
//                }
//            }
//        }
        //endregion


//        $this->db->trans_start();

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

        }
        //endregion


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


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

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

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

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

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

                            }

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

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

                        if (sizeof($subParams) > 0) {

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


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

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

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

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

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

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

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

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

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

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

        //endregion


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

            echo "ITEM NUM LABELS";

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

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


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

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

                        }

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

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


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


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

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

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

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

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

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

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

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


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


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

        //endregion

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


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

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

                        }

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

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


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


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

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

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

                                }

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

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

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

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

        }
        //endregion


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


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

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


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


        //==tulis signature

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

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

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

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

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


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


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

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

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


        $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->configCore[$origJenis]['formatNota']);
        if (!in_array($counterForNumber[0], $this->configCore[$origJenis]['counters'])) {
            die(__LINE__ . " Used number should be registered in 'counters' config as well");
        }

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

        //endregion

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

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


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

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

        // </editor-fold>
        //endregion


        //==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']);
            showLast_query("ungu");
            $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
            $mongoList['main'] = array($insertID, $epID);
            $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
            $_SESSION[$cCode]['main']['nomer'] = $insertNum;
            if ($insertID < 1) {
                die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
            }


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

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


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

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


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


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

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

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

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


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


                }
            }


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

                    }

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

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


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

                                $mongUpdateList['update']['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


            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($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget] : array(),
                "preProcessor" => isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget] : array(),
                "postProcessor" => isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget] : array(),
                "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),

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


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

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

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

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

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

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

                        }

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

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

                    if (sizeof($subParams) > 0) {
                        $tmpOutParams[$cCtr][] = $subParams;
                    }
                    echo "<script>top.writeProgress('" . isset($subParams['static']['name']) ? $subParams['static']['name'] : "" . " " . isset($subParams['static']['extern_nama']) ? $subParams['static']['extern_nama'] : "" . " " . isset($subParams['static']['nama']) ? $subParams['static']['nama'] : "" . "');</script>";
                }
            }

            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, sending values <br>";
                echo "<script>top.writeProgress('SENDING SUB-PROCESSORS ($comName)...', 'head');</script>";
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                cekBiru($this->db->last_query());
            }
        }

        //endregion

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

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

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

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

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

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

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


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

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

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


                }

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

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


            }
        }


        //</editor-fold>
        //endregion


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

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

        //endregion


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

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


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

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

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

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

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

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


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

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

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


                }

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

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

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

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

                }


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

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


        //endregion


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

                    if (isset($_SESSION[$cCode]['main'][$valueSrc]) && $_SESSION[$cCode]['main'][$valueSrc] > 0) {
                        if (isset($externSrc['extern_label2'])) {
                            //cek ada isinya atau kosong
                            $cek = strlen($_SESSION[$cCode]['main'][$externSrc['extern_label2']]) > 4 ? "" : matiHere("jenis biaya tidak dikenali " . __LINE__);//
                        }
                        $arrPymSrc = array(
                            "jenis" => $stepCode,
                            "target_jenis" => $paymentSrcConfig['jenisTarget'],
                            "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                            "extern_id" => isset($_SESSION[$cCode]['main'][$externSrc['id']]) ? $_SESSION[$cCode]['main'][$externSrc['id']] : "",
                            "extern_nama" => isset($_SESSION[$cCode]['main'][$externSrc['nama']]) ? $_SESSION[$cCode]['main'][$externSrc['nama']] : "",
                            "nomer" => $tmpNomorNota2,
                            "label" => $paymentSrcConfig['label'],

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

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

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

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

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

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

                    }


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

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

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


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

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

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

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

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

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

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


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


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


        //==================================================================================================
        $this->load->model("Mdls/MdlTransaksiLaporan");
        $lt = New MdlTransaksiLaporan();
        $dataTransaksiLaporan = array(
            "transaksi_id" => $insertID,
            "master_id" => $masterID,
            "nomer" => $tmpNomorNota2,
            "metode" => "reguler",
        );
        $lt->addData($dataTransaksiLaporan);
        showLast_query("ungu");
        //==================================================================================================
        //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
        $this->load->model("Mdls/MdlLockerTransaksi");
        $lt = New MdlLockerTransaksi();
        $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], $transaksiID_reference, $insertID);
        //==================================================================================================



        //==tampilkan receipt
        cekOrange("-- DONE --");

        //region writelog
        echo "<script>top.writeProgress('sedang menulis ke log');</script>";
        $this->load->model("Mdls/" . "MdlActivityLog");
        $hTmp = new MdlActivityLog();
        $tmpHData = array(
            "title" => $_SESSION[$cCode]['main']['jenisTrName'],
            "sub_title" => "Saving followup process",
            "uid" => $this->session->login['id'],
            "uname" => $this->session->login['nama'],
            "dtime" => date("Y-m-d H:i:s"),
            "transaksi_id" => $insertID,
            "deskripsi_old" => "",
            "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
            "jenis" => $this->jenisTr,
            "ipadd" => $_SERVER['REMOTE_ADDR'],
            "devices" => $_SERVER['HTTP_USER_AGENT'],
            "category" => "transaksi",
            "controller" => $this->uri->segment(1),
            "method" => $this->uri->segment(2),
            "url" => current_url(),

        );
        $logID = $hTmp->addData($tmpHData, $hTmp->getTableName()) or die(lgShowError("Gagal menulis riwayat data", __FILE__));
        //endregion


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

//        mati_disini(__FUNCTION__ . "  TRANSAKSI BERHASIL (UNDER MAINTENANCE)  <br> silahkan tutup browser terlebih dahulu. <br>execute in " . $val . " ms");

//        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");

        $pakai_ini = 0;
        if($pakai_ini == 1){
            if (isset($_SESSION[$cCode])) {
                unset($_SESSION[$cCode]);
            }

            if (isset($_SESSION["_TR_" . $origJenis])) {
                unset($_SESSION["_TR_" . $origJenis]);
            }

            if (isset($oldCode)) {
                if (isset($_SESSION[$oldCode])) {
                    unset($_SESSION[$oldCode]);
                }
            }
        }

        return $insertID;
    }
    public function doFollowup_3_ori_unused($trID, $nextStepNumber, $fromStepNumber)
    {
        echo "<script>top.writeProgress('MEMULAI PROSES FOLLOWUP....');</script>";

        $starttime = microtime(true);

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

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

        $transaksiID_reference = $no = $trID;
        $stepNum = $nextStepNumber;
        $stepNumCurrent = $fromStepNumber;

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

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

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

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

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

        //==ambil datanya
        $stepNowParameter = array();
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("transaksi.id in (" . implode(",", explode("-", $no)) . ")");
        $tr->addFilter("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();

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

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

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

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

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

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

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

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

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


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

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

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

        //region build table rekening
//        $buildTablesMaster = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'] : array();
//        $buildTablesDetail = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
//
//        //arrPrint($buildTablesMaster);
//
//        $addMasterTables = array(
//            "rugilaba",
//            "laba ditahan",
//            "rugilaba lain lain",
//        );
//        foreach ($addMasterTables as $trek) {
//            $buildTablesMaster[] = array(
//                "comName" => "RugiLaba",
//                "loop" => array(
//                    "$trek" => .0,
//                ),
//            );
//        }
//
//        if (sizeof($buildTablesMaster) > 0) {
//            foreach ($buildTablesMaster as $buildTablesMaster_specs) {
//                $mdlName = $buildTablesMaster_specs['comName'];
//                if (substr($mdlName, 0, 1) == "{") {
//                    //                        cekkuning("mengandung kurawal");
//                    $mdlName = trim($mdlName, "{");
//                    $mdlName = trim($mdlName, "}");
//                    $mdlName = str_replace($mdlName, $_SESSION[$cCode]['main'][$mdlName], $mdlName);
//                }
//                else {
//                    //                        cekkuning("TIDAK mengandung kurawal");
//                }
//                $mdlName = "Com" . $mdlName;
//                cekHitam("model: $mdlName");
//
//
//                if (isset($buildTablesMaster_specs['loop'])) {
//                    foreach ($buildTablesMaster_specs['loop'] as $key => $val) {
//                        unset($buildTablesMaster_specs['loop'][$key]);
//                        //                        if (isset($_SESSION[$cCode]['main'][$key])) {
//                        if (substr($key, 0, 1) == "{") {
//                            $key = trim($key, "{");
//                            $key = trim($key, "}");
//                            $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
//                        }
//                        $buildTablesMaster_specs['loop'][$key] = $val;
//                        //                        }
//                    }
//                }
//
//                $this->load->model("Coms/" . $mdlName);
//                $m = new $mdlName();
//                if (method_exists($m, "getTableNameMaster")) {
//                    if (sizeof($m->getTableNameMaster())) {
//                        $m->buildTables($buildTablesMaster_specs);
//                    }
//                }
//            }
//        }
//
//        if (sizeof($buildTablesDetail) > 0) {
//            foreach ($buildTablesDetail as $buildTablesDetail_specs) {
//                foreach ($_SESSION[$cCode]['items'] as $itemSpec) {
//
//                    $mdlName = $buildTablesDetail_specs['comName'];
//                    if (substr($mdlName, 0, 1) == "{") {
//                        $mdlName = trim($mdlName, "{");
//                        $mdlName = trim($mdlName, "}");
//                        $mdlName = str_replace($mdlName, $itemSpec[$mdlName], $mdlName);
//                    }
//
//                    if (isset($buildTablesDetail_specs['loop'])) {
//                        foreach ($buildTablesDetail_specs['loop'] as $key => $val) {
//                            unset($buildTablesDetail_specs['loop'][$key]);
//
//                            if (substr($key, 0, 1) == "{") {
//                                $key = trim($key, "{");
//                                $key = trim($key, "}");
//                                $key = str_replace($key, $itemSpec[$key], $key);
//                            }
//                            $buildTablesDetail_specs['loop'][$key] = $val;
//                            cekHitam("LINE: " . __LINE__ . " ::sini bukan??  akan build tabel detail $key");
//
//                        }
//                    }
//
//
//                    $mdlName = "Com" . $mdlName;
//                    $this->load->model("Coms/" . $mdlName);
//                    $m = new $mdlName();
//                    if (method_exists($m, "getTableNameMaster")) {
//                        if (sizeof($m->getTableNameMaster())) {
//                            $m->buildTables($buildTablesDetail_specs);
//                            arrPrint($buildTablesDetail_specs);
//                            cekHitam(":: build tabel detail");
//                        }
//                    }
//                }
//            }
//        }
        //endregion

//        $this->db->trans_start();

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

        }
        //endregion

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

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

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

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

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

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

                            }

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

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

                        if (sizeof($subParams) > 0) {

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


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

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

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

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

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

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

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

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

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

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

        //endregion

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

            echo "ITEM NUM LABELS";

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

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


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

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

                        }

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

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


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


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

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

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

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

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

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

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

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


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


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

        //endregion

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


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

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

                        }

                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                            foreach ($paramPatchers[$comName] as $k => $v) {
                                if (!isset($subParams['static'][$k])) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                }
                            }
                        }
                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                            $jenis = $_SESSION[$cCode]['main']['jenis'];
                            foreach ($paramForceFillers[$comName] as $k => $v) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }

                        $subParams['static']["fulldate"] = date("Y-m-d");
                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                    }
                    if (sizeof($subParams) > 0) {
                        $tmpOutParams[$cCtr] = $subParams;
                    }


                    $mdlName = "Pre" . ucfirst($comName);
                    $this->load->model("Preprocs/" . $mdlName);
                    $m = new $mdlName($resultParams);


                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
                        $tobeExecuted = true;
                    }
                    else {
                        $tobeExecuted = false;
                    }

                    if ($tobeExecuted) {
                        $m->pair($masterID, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        $gotParams = $m->exec();
                        if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                            //                            cekhijau("ada gotparam, sekarang mau replace");
                            foreach ($gotParams as $gateName => $gSpec) {
                                if ($gateName == "main") {
                                    foreach ($gSpec as $key => $val) {
                                        $_SESSION[$cCode]['main'][$key] = $val;
                                    }
                                }
                                if ($gateName == "items2") {
                                    foreach ($_SESSION[$cCode]['items2'] as $k => $tmpSes) {
                                        foreach ($gSpec as $key => $val) {
                                            foreach ($tmpSes as $y => $sesData) {
                                                if (array_key_exists($key, $sesData)) {
                                                    $_SESSION[$cCode]['items2'][$k][$y][$key] = $val;
                                                }
                                            }
                                        }
                                    }

                                }
                                if ($gateName == "items2_sum") {
                                    foreach ($_SESSION[$cCode]['items2_sum'] as $k => $tmpSes) {
                                        foreach ($gSpec as $key => $val) {
                                            $_SESSION[$cCode]['items2_sum'][$k][$key] = $val;
                                        }
                                    }

                                }

                            }
                        }
                        else {
                            cekmerah("TIDAK ada gotparam, tidak perlu replace");
                        }

                    }
                    else {
                        cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                    }

                }
            }
            else {
                //cekKuning("sub-preproc is not set");
            }

            $this->load->helper("he_value_builder");
            fillValues_he_value_builder($this->jenisTr, $stepNumCurrent, $stepNum, $this->configCoreJenis, $this->configUiJenis);

        }
        //endregion


//        $step = $_SESSION[$cCode]['main']['step_number'];
        $this->load->library("Validator");
        $va = new Validator();
        $va->setConfigUiJenis($this->configUi[$this->jenisTr]);
        $va->setCCode($this->cCode);
        $va->midValidate($stepNum);
        $va->unionValidate();
        //==tulis komponen, if any



        //region update step2an
        if (isset($this->configUi[$this->jenisTr]['steps'][$nextStepNum])) {//===masih ada langkah selanjutnya
            echo "authorizing to next step..<br>";
            $nextProp = array(
                "num" => $nextStepNum,
                "code" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['target'],
                "label" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['label'],
                "groupID" => $this->configUi[$this->jenisTr]['steps'][$nextStepNum]['userGroup'],
            );
        }
        else {//==ini step terakhir, tulis komponen jika ada

            $nextProp = array(
                "num" => 0,
                "code" => "",
                "label" => "",
                "groupID" => "",
            );
        }
        //endregion


        echo "checking components..<br>";
        echo "<script>top.writeProgress('CHECKING KOMPONEN');</script>";
        //referensi_id pada steps (dimatikan)
        //        $masterReplacers = array(
        //            "referensi_id" => $masterID,
        //        );
        //        $childReplacers = array(
        //            "referensi_id" => $masterID,
        //        );
        //        foreach ($masterReplacers as $key => $val) {
        //            $_SESSION[$cCode]['main'][$key] = $val;
        //        }
        //        foreach ($childReplacers as $key => $val) {
        //            foreach ($_SESSION[$cCode]['out_detail'] as $xid => $cSpec) {
        //                $id = $cSpec['id'];
        //                $_SESSION[$cCode]['out_detail'][$id][$key] = $val;
        //            }
        //
        //        }


        //==tulis signature

        $dwsign = $tr->writeSignature($masterID, array(
            "nomer" => $tmpNomorNota,
            "step_number" => $stepNum,
            "step_code" => $this->configUi[$origJenis]['steps'][$stepNum]['target'],
            "step_name" => $this->configUi[$origJenis]['steps'][$stepNum]['label'],
            "group_code" => $this->configUi[$origJenis]['steps'][$stepNum]['userGroup'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "keterangan" => $this->configUi[$origJenis]['steps'][$stepNum]['label'] . " oleh " . $this->session->login['nama'],
            "transaksi_id" => $masterID,
        )) or die("Failed to write signature");
        $mongoList['sign'][] = $dwsign;
        //cekKuning($this->db->last_query());

        //region update step terdahulu
        $tr = new MdlTransaksi();
        $dupState = $tr->updateData(array("id" => $topID), array(
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            "next_step_num" => $nextProp['num'],
            "step_current" => $stepNum,

            "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,

        )) or die("Failed to update tr next-state!");
        $mongUpdateList['update']['main'][] = array(
            "where" => array("id" => "$topID"),
            "value" => array(
                "next_step_code" => $nextProp['code'],
                "next_step_label" => $nextProp['label'],
                "next_group_code" => $nextProp['groupID'],
                "next_step_num" => $nextProp['num'],
                "step_current" => $stepNum,
            ),
        );
        cekHijau($this->db->last_query());

        //-------------------------------------------------
        $tr = new MdlTransaksi();
        $dupState = $tr->updateData(array("id" => $trID), array(
            "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,
        )) or die("Failed to update tr next-state!");
        $mongUpdateList['update']['main'][] = array(
            "where" => array("id" => "$trID"),
            "value" => array(
                "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,
            ),
        );


        //mati_disini("==== ==== ====");
        //endregion



        //==prepare kloningan
        $tCode = $this->configUi[$origJenis]['steps'][$stepNum]['target'];
        $tCodeName = $this->configUi[$origJenis]['steps'][$stepNum]['label'];
        $masterReplacers = array(
            //            "referensi_id" => $masterID, (dimatikan)
            //            "id_master"       => $masterID,
            //            "id_top"          => $topID,
            "inv" => $tmpNomorNota,
            //            "jenis_top"           => $tCode,
            "jenis" => $tCode,
            "jenis_label" => $tCodeName,
            "transaksi_jenis" => $tCode,
            "cabang_id" => selectedTransactionSession() ? $_SESSION[$cCode]['main']['cabangID'] : $this->session->login['cabang_id'],
            "cabang_nama" => selectedTransactionSession() ? $_SESSION[$cCode]['main']['cabangName'] : $this->session->login['cabang_nama'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "step_current" => "0",
            "step_number" => $stepNum,
            //            "next_step_code"      => "",
            //            "next_step_label"     => "",
            //            "next_group_code"     => "",
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            //===references
            "id_master" => $masterID,
            "id_top" => $topID,
            "ids_prev" => base64_encode(serialize($prevIDs)),
            "ids_prev_intext" => print_r($prevIDs, true),
            "nomer_top2" => isset($_SESSION[$cCode]['main']['nomer_top2']) ? $_SESSION[$cCode]['main']['nomer_top2'] : "",
            "nomer_top" => $_SESSION[$cCode]['tableIn_master']['nomer_top'],
            "nomers_prev" => base64_encode(serialize($prevNos)),
            "nomers_prev_intext" => print_r($prevNos, true),
            //            "jenis_top"           => $this->jenisTr,
            "jenises_prev" => base64_encode(serialize(array($prevProp['jenis']))),
            "jenises_prev_intext" => print_r(array($prevProp['jenis']), true),
            "tail_number" => $stepNum,
            "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
        );

        foreach ($masterReplacers as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        $childTableRepaclers = array(
            "sub_step_number" => $stepNum,
            "sub_step_current" => $stepNum,
            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
            "next_substep_num" => $nextProp['num'],
            "next_substep_code" => $nextProp['code'],
            "next_substep_label" => $nextProp['label'],
            "next_subgroup_code" => $nextProp['groupID'],
        );
        foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
            //			$id = $dSpec['id'];
            foreach ($childTableRepaclers as $key => $val) {
                $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
            }
        }


        $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->configCore[$origJenis]['formatNota']);
        if (!in_array($counterForNumber[0], $this->configCore[$origJenis]['counters'])) {
            die(__LINE__ . " Used number should be registered in 'counters' config as well");
        }

        foreach ($counterForNumber as $i => $cRawParams) {
            $cParams = explode("|", $cRawParams);
            $cValues = array();
            foreach ($cParams as $param) {
                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
            }
            $cRawValues = implode("|", $cValues[$i]);
            $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
        }
        $tmpNomorNota2 = $paramSpec['paramString'];
        $tmpNomorNota2Alias = formatNota("nomer_nolink", $tmpNomorNota2);

        //endregion

        //region dynamic counters #1
        echo "<script>top.writeProgress('sedang membuat penomoran');</script>";
        // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
        $cn = new CustomCounter("transaksi");
        $cn->setType("transaksi");
        $configCustomParams = $this->configCore[$origJenis]['counters'];
        $configCustomParams[] = "stepCode";
        if (sizeof($configCustomParams) > 0) {
            $cContent = array();
            foreach ($configCustomParams as $i => $cRawParams) {
                $cParams = explode("|", $cRawParams);
                $cValues = array();
                foreach ($cParams as $param) {
                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                }
                $cRawValues = implode("|", $cValues[$i]);
                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                switch ($paramSpec['id']) {
                    case 0: //===counter type is new
                        $paramKeyRaw = print_r($cParams, true);
                        $paramValuesRaw = print_r($cValues[$i], true);
                        $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                        break;
                    default: //===counter to be updated
                        $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                        break;
                }
                //echo "<hr>";
            }
        }
        $appliedCounters2 = base64_encode(serialize($cContent));
        $appliedCounters_inText2 = print_r($cContent, true);


        $masterReplacers = array(
            "nomer" => $tmpNomorNota2,
            "nomer2" => $tmpNomorNota2Alias,
            "counters" => $appliedCounters2,
            "counters_intext" => $appliedCounters_inText2,
        );
        foreach ($masterReplacers as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        $addValues = array(
            'counters' => $appliedCounters2,
            'counters_intext' => $appliedCounters_inText2,
            'nomer' => $tmpNomorNota2,
            'nomer2' => $tmpNomorNota2Alias,
            'dtime' => date("Y-m-d H:i:s"),
            'fulldate' => date("Y-m-d"),
        );
        foreach ($addValues as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        // </editor-fold>
        //endregion


        //==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']);


            showLast_query("ungu");

            $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
            $mongoList['main'] = array($insertID, $epID);
            $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
            $_SESSION[$cCode]['main']['nomer'] = $insertNum;
            if ($insertID < 1) {
                die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
            }


            if (isset($_SESSION[$cCode]['tableIn_master']['ids_his'])) {
                $idHis_decode = blobDecode($_SESSION[$cCode]['tableIn_master']['ids_his']);
                $idHis_decode[$stepNum] = array(
                    "olehID" => $_SESSION[$cCode]['main']['olehID'],
                    "olehName" => $_SESSION[$cCode]['main']['olehName'],
                    "step" => $stepNum,
                    "trID" => $insertID,
                    "nomer" => $tmpNomorNota2,
                    "nomer2" => $tmpNomorNota2Alias,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                $idHis_blob = blobEncode($idHis_decode);
                $idHis_intext = print_r($idHis_decode, true);

                $_SESSION[$cCode]['tableIn_master']['ids_his'] = $idHis_blob;
                $_SESSION[$cCode]['tableIn_master']['ids_his_intext'] = $idHis_intext;


                $tr = new MdlTransaksi();
                $dup = $tr->updateData(array("id" => $insertID), array(
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

                )) or die("Failed to update tr next-state!");
                cekUngu($this->db->last_query());
            }


            cekUngu(":: insertID => $insertID ::");



            if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                $inserMainValues = array();
                $mongoList['mainValues'] = array();
                foreach ($_SESSION[$cCode]['tableIn_master_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $inserMainValues[] = $dd;
                    $mongoList['mainValues'][] = $dd;
                }
                if (sizeof($inserMainValues) > 0) {
                    $arrBlob = blobEncode($inserMainValues);
                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $mongoList['mainValues'][] = $dd;
                }
            }
            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $mongoList['mainValues'][] = $dd;
                }
            }
            if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                    $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                }
            }
            if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                //                cekMerah("ada mainElements $cCode");
                //                arrprint($_SESSION[$cCode]['main_elements']);die();
                foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                    $tr->writeMainElements($insertID, array(
                        "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                        "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                        "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                        "name" => $aSpec['name'],
                        "label" => $aSpec['label'],
                        "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                        "contents_intext" => isset($aSpec['contents_intext']) ? print_r($aSpec['contents_intext'], true) : "",

                    ));
                }
            }
            else {
                //                cekMerah("TAK ada mainElements");
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => isset($dSpec[$src]) ? $dSpec[$src] : 0,
                            ));
                            $insertIDs[$pID][] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }

                    }
                }
                if (sizeof($insertIDs) > 0) {
                    $arrBlob = blobEncode($insertIDs);
                    $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                            $insertIDs[] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }


                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail_rsltItems'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                            $insertIDs[$pID][] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }


                }
            }

            //region update validQty pada step sebelumnya yang di-refer
            echo "<script>top.writeProgress('EXTRACT ITEMS...','head');</script>";
            $seluruhnya = true;
            $prevTrID = 0;
            $arrvalidQtySisa = array();

            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                $closedRequest = isset($this->configCore[$origJenis]['closedRequest'][$stepNum]['enabled']) ? $this->configCore[$origJenis]['closedRequest'][$stepNum]['enabled'] : false;
                $insertIDs = array();
                $insertDeIDs = array();
                matiHere("MATI-HERE: insertID:$insertID | " . __METHOD__ . " | __LINE__: " . __LINE__ );

                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;
                                $updateContents = array(
                                    "valid_qty" => $newValidQty,
                                    "valid_qty_no_approve" => $newValidQtyNotApprove,
                                );
                                if ($newValidQty < 1) {
                                    $childPrevRepaclers = array(
                                        "next_substep_code" => "",
                                        "next_substep_label" => "",
                                        "next_subgroup_code" => "",
                                        "sub_tail_number" => $stepNum,
                                        "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                    );
                                    foreach ($childPrevRepaclers as $key => $val) {
                                        $updateContents[$key] = $val;
                                    }
                                }
                                else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                    $seluruhnya = false;
                                    $arrvalidQtySisa[$iID] = $newValidQty;
                                }
                                $dupState = $tru->updateData(array(
                                    "produk_id" => $iID,
                                    "id" => $triID,
                                    "transaksi_id" => $triSpec['transaksi_id'],
                                ), $updateContents) or die("Failed to update previous detail entries!");
                                cekHijau($this->db->last_query());

                                $mongUpdateList['update']['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


            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($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget] : array(),
                "preProcessor" => isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget] : array(),
                "postProcessor" => isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget] : array(),
                "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),

            );
            $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



        //region processing sub-post-processors, always
        //<editor-fold desc="----------sub postProc">

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail'] : array();
        if (sizeof($iterator) > 0) {
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, initializing values <br>";
                echo "<script>top.writeProgress('MENYIAPKAN DATA SUB-PROCESSORS UNTUK DIKIRIM...', 'head');</script>";

                $tmpOutParams[$cCtr] = array();
                foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                    $subParams = array();
                    if (isset($tComSpec['loop'])) {
                        foreach ($tComSpec['loop'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                            $subParams['loop'][$key] = $realValue;

                        }
                    }
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                            $subParams['static'][$key] = $realValue;
                            cekBiru("$key diisi dengan $realValue");

                        }

                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                            foreach ($paramPatchers[$comName] as $k => $v) {
                                if (!isset($subParams['static'][$k])) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                }
                            }
                        }
                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                            $jenis = $_SESSION[$cCode]['main']['jenis'];
                            foreach ($paramForceFillers[$comName] as $k => $v) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                cekorange(":: $k diisikan dengan " . $subParams['static'][$k]);
                            }
                        }

                        $subParams['static']["fulldate"] = date("Y-m-d");
                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                    }

                    if (sizeof($subParams) > 0) {
                        $tmpOutParams[$cCtr][] = $subParams;
                    }
                    echo "<script>top.writeProgress('" . isset($subParams['static']['name']) ? $subParams['static']['name'] : "" . " " . isset($subParams['static']['extern_nama']) ? $subParams['static']['extern_nama'] : "" . " " . isset($subParams['static']['nama']) ? $subParams['static']['nama'] : "" . "');</script>";
                }
            }

            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, sending values <br>";
                echo "<script>top.writeProgress('SENDING SUB-PROCESSORS ($comName)...', 'head');</script>";
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                cekBiru($this->db->last_query());
            }
        }

        //endregion

        //
        //region processing main-post-processors, always
        //<editor-fold desc="----------postProc">

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master'] : array();
        if (sizeof($iterator) > 0) {
            echo "<script>top.writeProgress('MEMPROSES MAIN-PROCESSORS...', 'head');</script>";
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "post-processor: $comName<br>";

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['loop'][$key] = $realValue;

                    }
                }
                if (isset($tComSpec['static'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                                echo "<script>top.writeProgress(':: $key diisikan dengan " . $tmpOutParams['static'][$k] . ");</script>";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            echo "<script>top.writeProgress(':: $key diisikan dengan " . $tmpOutParams['static'][$k] . ");</script>";
                        }
                    }
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //                cekBiru("kiriman komponem $comName");
                //                                    arrPrint($tmpOutParams);
                $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


            }
        }


        //</editor-fold>
        //endregion


        //
        //region ----------subcomponents GESER KE CLI

        //        $componentGate['detail'] = array();
        //        //arrPrint($paramForceFillers);
        $iterator = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
        $componentConfig['detail'] = $iterator;
        //        if (sizeof($iterator) > 0) {
        //            $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
        //            $filterNeeded = false;
        //            if (in_array($mdlName, $compValidators)) {//perlu validasi filter
        //                $filterNeeded = true;
        //            }
        //            foreach ($iterator as $cCtr => $tComSpec) {
        ////                $comName = $tComSpec['comName'];
        //                $srcGateName = $tComSpec['srcGateName'];
        //                $srcRawGateName = $tComSpec['srcRawGateName'];
        //
        //                echo "sub-component: $comName, $srcGateName, initializing values <br>";
        //                $tmpOutParams[$cCtr] = array();
        //                foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
        //                    cekmerah("mengevaluasi $srcGateName..");
        //                    $comName = $tComSpec['comName'];
        //                    if (substr($comName, 0, 1) == "{") {
        //                        $comName = trim($comName, "{");
        //                        $comName = trim($comName, "}");
        //                        $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
        //                        $tComSpec['comName'] = $comName;
        //                        $iterator[$cCtr]['comName'] = $comName;
        //                    }
        //
        //                    $filterNeeded = false;
        //                    $mdlName = "Com" . ucfirst($comName);
        //                    if (in_array($mdlName, $compValidators)) {//perlu validasi filter
        //                        $filterNeeded = true;
        //                    }
        //
        //
        //                    $subParams = array();
        //                    if (isset($tComSpec['loop'])) {
        //                        foreach ($tComSpec['loop'] as $key => $value) {
        //                            if (substr($key, 0, 1) == "{") {
        //                                $key = trim($key, "{");
        //                                $key = trim($key, "}");
        //                                $key = str_replace($key, $_SESSION[$cCode][$srcGateName][$id][$key], $key);
        //                            }
        //                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
        //                            $subParams['loop'][$key] = $realValue;
        //                            cekKuning("LOOP: $key diisi dengan $realValue");
        //
        //                            if ($filterNeeded) {
        //                                if ($subParams['loop'][$key] == 0) {
        //                                    unset($subParams['loop'][$key]);
        //                                }
        //                            }
        //                        }
        //                    }
        //                    if (isset($tComSpec['static'])) {
        //                        foreach ($tComSpec['static'] as $key => $value) {
        //
        //                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
        //                            $subParams['static'][$key] = $realValue;
        //                            cekKuning("STATIC: $key diisi dengan $realValue");
        //
        //                        }
        //                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
        //                            foreach ($paramPatchers[$comName] as $k => $v) {
        //                                if (!isset($subParams['static'][$k])) {
        //                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
        //                                    cekOrange("fill :: $comName :: $k => " . $subParams['static'][$k]);
        //                                }
        //                            }
        //                        }
        //                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
        //                            //                            cekOrange("comName:: $comName");
        //                            $jenis = $_SESSION[$cCode]['main']['jenis'];
        //                            foreach ($paramForceFillers[$comName] as $k => $v) {
        //                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
        //                                cekOrange("fillforce :: $comName :: $k => " . $subParams['static'][$k]);
        //                            }
        //                        }
        //                        $subParams['static']["fulldate"] = date("Y-m-d");
        //                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
        //                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
        //                    }
        //                    cekHitam("cetak subParams");
        //                    arrPrint($subParams);
        //                    if (sizeof($subParams) > 0) {
        //                        if ($filterNeeded) {
        //                            if (isset($subParams['loop']) && sizeof($subParams['loop']) > 0) {
        //                                $tmpOutParams[$cCtr][] = $subParams;
        //                            }
        //                        }
        //                        else {
        //
        //                            $tmpOutParams[$cCtr][] = $subParams;
        //                        }
        //                    }
        //                }
        //
        //                $componentGate['detail'][$cCtr] = $subParams;
        //            }
        //
        //
        //            $it = 0;
        //            foreach ($iterator as $cCtr => $tComSpec) {
        //                $it++;
        //
        //
        //                $comName = $tComSpec['comName'];
        //                $srcGateName = $tComSpec['srcGateName'];
        //                $srcRawGateName = $tComSpec['srcRawGateName'];
        //
        //                echo "sub component #$it: $comName, sending values <br>";
        //
        //                $mdlName = "Com" . ucfirst($comName);
        //                $this->load->model("Coms/" . $mdlName);
        //                $m = new $mdlName();
        //
        //
        //                if (sizeof($tmpOutParams[$cCtr]) > 0) {
        //                    $tobeExecuted = true;
        //                }
        //                else {
        //                    $tobeExecuted = false;
        //                }
        //
        //
        //                if ($tobeExecuted) {
        //                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
        //                    $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
        //                }
        //                else {
        //                    cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
        //                }
        //            }
        //        }
        //        else {
        //            //cekKuning("subcomponents is not set");
        //        }

        //endregion


        //region ----------components
        //<editor-fold desc="----------components">

        $componentGate['master'] = array();
        $componentConfig['master'] = array();
        if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
            $iterator = isset($_SESSION[$cCode]['revert']['jurnal'][$stepNum]['master']) ? $_SESSION[$cCode]['revert']['jurnal'][$stepNum]['master'] : array();
        }
        else {
            if (isset($_SESSION[$cCode]['componentsBuilder'][$stepNum]['master'])) {
                $iterator = $_SESSION[$cCode]['componentsBuilder'][$stepNum]['master'];
            }
            elseif (isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'])) {
                $iterator = $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'];
            }
            else {
                $iterator = array();
            }
        }


        if (sizeof($iterator) > 0) {
            echo "<script>top.writeProgress('KOMPONEN...', 'head');</script>";
            $componentConfig['master'] = $iterator;

            $it = 0;
            //==filter nilai, jika NOL tidak dikirim, sesuai config==
            $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
            foreach ($iterator as $cCtr => $tComSpec) {
                //                cekPink($tComSpec);
                //                mati_disini();
                $it++;
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "component #$it: $comName :: $srcGateName <br>";

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {
                        if (substr($key, 0, 1) == "{") {
                            $key = trim($key, "{");
                            $key = trim($key, "}");
                            //                            $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
                            $key = str_replace($key, $_SESSION[$cCode][$srcGateName][$key], $key);
                        }
                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        if ($key != null) {
                            $tmpOutParams['loop'][$key] = $realValue;
                        }

                    }
                }
                //                cekBiru($tmpOutParams);
                //                mati_disini(__LINE__);
                if (isset($tComSpec['static'])) {
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;
                        cekHijau(":: NORMAL :: $key => $realValue ::");
                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        cekHijau(":: masuk ke PATCHER ::");
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            cekHijau(":: ada yang mau di-PATCHER ::");
                            arrPrint($tmpOutParams['static']);
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                                cekHijau(":: PATCHER :: $key => $realValue ::");
                            }

                        }
                    }
                    else {
                        cekMerah(":: TIDAK TERMASUK PATCHER ::");
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            cekHijau(":: FORCEFILL :: $key => $realValue ::");
                        }
                    }
                    $tmpOutParams['static']["urut"] = $cCtr;
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //===filter value nol, jika harus difilter
                $tobeExecuted = true;

                if (in_array($mdlName, $compValidators)) {

                    $loopParams = isset($tmpOutParams['loop']) ? $tmpOutParams['loop'] : array();
                    if (sizeof($loopParams) > 0) {
                        foreach ($loopParams as $key => $val) {
                            cekmerah("$comName : $key = $val ");
                            if ($val == 0) {
                                unset($tmpOutParams['loop'][$key]);
                            }
                        }
                    }
                    if (sizeof($tmpOutParams['loop']) < 1) {
                        $tobeExecuted = false;
                    }

                }


                if ($tobeExecuted) {
                    cekBiru("kiriman komponen $comName");
                    arrPrint($tmpOutParams);
                    $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                }
                else {
                    cekBiru("komponem $comName tidak memenuhi syarat untuk ditulis");
                }

                $componentGate['master'][$cCtr] = $tmpOutParams;
            }
        }
        else {
            //cekKuning("components is not set");
        }


        //endregion


        //region nulis paymentSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_source");
        if (array_key_exists($stepCode, $paymentSources)) {
            $payConfigs = isset($paymentSources[$stepCode][$stepNum]) ? $paymentSources[$stepCode][$stepNum] : array();
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    $valueSrc = $paymentSrcConfig['valueSrc'];
                    $externSrc = $paymentSrcConfig['externSrc'];
                    if (isset($paymentSrcConfig['model'])) {
                        $mdlName = $paymentSrcConfig['model'];
                        $this->load->model("Mdls/$mdlName");
                        $pMdl = New $mdlName();
                        $pTmpMdl = $pMdl->lookupAll()->result();
                        $pTmpMdlResult = array();
                        if (sizeof($pTmpMdl) > 0) {
                            foreach ($pTmpMdl as $pTmpMdlSpec) {
                                $pTmpMdlResult[$pTmpMdlSpec->id] = $pTmpMdlSpec;
                            }
                        }
                    }
                    else {
                        $pTmpMdlResult = array();
                    }

                    if (isset($_SESSION[$cCode]['main'][$valueSrc]) && $_SESSION[$cCode]['main'][$valueSrc] > 0) {
                        if (isset($externSrc['extern_label2'])) {
                            //cek ada isinya atau kosong
                            $cek = strlen($_SESSION[$cCode]['main'][$externSrc['extern_label2']]) > 4 ? "" : matiHere("jenis biaya tidak dikenali " . __LINE__);//
                        }
                        $arrPymSrc = array(
                            "jenis" => $stepCode,
                            "target_jenis" => $paymentSrcConfig['jenisTarget'],
                            "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                            "extern_id" => isset($_SESSION[$cCode]['main'][$externSrc['id']]) ? $_SESSION[$cCode]['main'][$externSrc['id']] : "",
                            "extern_nama" => isset($_SESSION[$cCode]['main'][$externSrc['nama']]) ? $_SESSION[$cCode]['main'][$externSrc['nama']] : "",
                            "nomer" => $tmpNomorNota2,
                            "label" => $paymentSrcConfig['label'],

                            "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                            "terbayar" => 0,
                            "sisa" => $_SESSION[$cCode]['main'][$valueSrc],

                            "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                            "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "fulldate" => date("Y-m-d"),
                            "valas_id" => isset($externSrc['valasId']) && isset($_SESSION[$cCode]['main'][$externSrc['valasId']]) ? $_SESSION[$cCode]['main'][$externSrc['valasId']] : '',
                            "valas_nama" => isset($externSrc['valasLabel']) && isset($_SESSION[$cCode]['main'][$externSrc['valasLabel']]) ? $_SESSION[$cCode]['main'][$externSrc['valasLabel']] : '',
                            "valas_nilai" => isset($externSrc['valasValue']) && isset($_SESSION[$cCode]['main'][$externSrc['valasValue']]) ? $_SESSION[$cCode]['main'][$externSrc['valasValue']] : '',

                            "tagihan_valas" => isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : '',
                            "terbayar_valas" => 0,
                            "sisa_valas" => isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',

                            //                            "extern_label2" => isset($_SESSION[$cCode]['main']['pihakMainName']) ? $_SESSION[$cCode]['main']['pihakMainName'] : "",
                            "extern_label2" => (isset($externSrc['extern_label2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_label2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_label2']] : "",

                            "ppn" => (isset($externSrc['ppn']) && ($_SESSION[$cCode]['main'][$externSrc['ppn']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn']] : "",
                            "ppn_approved" => (isset($externSrc['ppn_approved']) && ($_SESSION[$cCode]['main'][$externSrc['ppn_approved']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn_approved']] : 0,
                            "ppn_sisa" => (isset($externSrc['ppn']) && ($_SESSION[$cCode]['main'][$externSrc['ppn']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn']] : "",
                            "ppn_status" => (isset($externSrc['ppn_status'])) ? $externSrc['ppn_status'] : 0,
                            "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : 0,
                            "extern_date2" => (isset($externSrc['extern_date2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_date2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_date2']] : "",
                            "pph_23" => (isset($externSrc['pph_23']) && ($_SESSION[$cCode]['main'][$externSrc['pph_23']])) ? $_SESSION[$cCode]['main'][$externSrc['pph_23']] : "",

                            "npwp" => (isset($externSrc['npwp']) && ($_SESSION[$cCode]['main'][$externSrc['npwp']])) ? $_SESSION[$cCode]['main'][$externSrc['npwp']] : "",
                            "extern2_id" => (isset($externSrc['extern2_id']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_id']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_id']] : "",
                            "extern2_nama" => (isset($externSrc['extern2_nama']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_nama']] : "",
                            "ppn_pph_faktor" => (isset($externSrc['ppn_pph_faktor']) && ($_SESSION[$cCode]['main'][$externSrc['ppn_pph_faktor']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn_pph_faktor']] : "",
                            "extern_jenis" => (isset($externSrc['extern_jenis']) && ($_SESSION[$cCode]['main'][$externSrc['extern_jenis']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_jenis']] : "",
                            "extern_nilai3" => (isset($externSrc['extern_nilai3']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai3']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai3']] : "",
                            "extern_nilai4" => (isset($externSrc['extern_nilai4']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai4']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai4']] : "",
                            "npwp" => (isset($externSrc['npwp']) && ($_SESSION[$cCode]['main'][$externSrc['npwp']])) ? $_SESSION[$cCode]['main'][$externSrc['npwp']] : "",
                            //                            "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : "",
                            "payment_locked" => (isset($externSrc['payment_locked']) && ($_SESSION[$cCode]['main'][$externSrc['payment_locked']])) ? $_SESSION[$cCode]['main'][$externSrc['payment_locked']] : 0,
                            "cash_account" => (isset($externSrc['cash_account']) && ($_SESSION[$cCode]['main'][$externSrc['cash_account']])) ? $_SESSION[$cCode]['main'][$externSrc['cash_account']] : 0,
                            "cash_account_nama" => (isset($externSrc['cash_account_nama']) && ($_SESSION[$cCode]['main'][$externSrc['cash_account_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['cash_account_nama']] : 0,
                        );
                        $tr->writePaymentSrc($insertID, $arrPymSrc);

                    }


                    cekMerah($this->db->last_query());
                }
            }

        }
        else {
            cekMerah("TIDAK nulis paymentSrc");
        }

        //matiHere("hoopppp");
        //cek additional step
        $addPaymentSource = isset($this->configUi[$this->jenisTr]['steps'][$stepNum]['additionalStep']['shippingService']) ? $this->configUi[$this->jenisTr]['steps'][$stepNum]['additionalStep']['shippingService'] : array();
        //        arrPrint($addPaymentSource);
        //endregion



        //
        //region nulis paymentAntiSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_antiSource");
        if (array_key_exists($stepCode, $paymentSources)) {
            cekMerah(":: starting PAYMENT ANTI SOURCE");
            $payConfigs = $paymentSources[$stepCode];
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    //					$paymentSrcConfig = $paymentSources[$stepCode];
                    $valueSrc = $paymentSrcConfig['valueSrc'];
                    $externSrc = $paymentSrcConfig['externSrc'];
                    $tr->writePaymentAntiSrc($insertID, array(
                        "jenis" => $stepCode,
                        "target_jenis" => $paymentSrcConfig['jenisTarget'],
                        "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                        "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                        "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                        "nomer" => $tmpNomorNota2,
                        "label" => $paymentSrcConfig['label'],
                        "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                        "terbayar" => 0,
                        "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                        "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                        "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "dtime" => date("Y-m-d H:i:s"),
                        "fulldate" => date("Y-m-d"),
                    ));
                    //cekMerah($this->db->last_query());
                }
            }

        }
        else {
            //cekMerah("TIDAK nulis paymentSrc");
        }
        //endregion

        //region nulis uangMukaSource
        /*dimatiin geser ke ComUangmukaSourceDetail karena ada di items.
        /*revisi tanggal 27 mei 2020 subject digeser ke vendor dari jenis transaksi misal uangmuka asuransi,uang muka pembelian ->uang muka.
         *
         */
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $uangMukaSources = $this->config->item("uang_muka");

        if (array_key_exists($stepCode, $uangMukaSources)) {
            cekMerah(":: starting UANG MUKA  SOURCE");
            //            matiHere();
            $uangMukaConfigs = isset($uangMukaSources[$stepCode][$stepNum]) ? $uangMukaSources[$stepCode][$stepNum] : array();
            if (sizeof($uangMukaConfigs) > 0) {
                $cekPreValue = "";
                $this->load->model("Mdls/MdlPaymentUangMuka");
                $l = new MdlPaymentUangMuka();
                foreach ($uangMukaConfigs as $uangMukaSrcConfig) {
                    //					$paymentSrcConfig = $paymentSources[$stepCode];
                    //                    arrPrint($uangMukaSrcConfig);
                    $valueSrc = $uangMukaSrcConfig['valueSrc'];
                    $externSrc = $uangMukaSrcConfig['externSrc'];
                    $l->addFilter("extern_id='" . $_SESSION[$cCode]['main'][$externSrc['id']] . "'");
                    $l->addFilter("extern_label2='" . $externSrc['extLabel'] . "'");
                    $tmpUm = $l->lookupAll()->result();
                    //                    arrPrint($tmpUm);
                    if (sizeof($tmpUm) > 0) {
                        //update here broo
                        $preTagihan = $tmpUm[0]->tagihan;
                        $preSisa = $tmpUm[0]->sisa;

                        $newTahigan = $preTagihan + $_SESSION[$cCode]['main'][$valueSrc];
                        $newsisa = $preSisa + $_SESSION[$cCode]['main'][$valueSrc];
                        $update = array(
                            "tagihan" => $newTahigan,
                            "sisa" => $newsisa,
                        );
                        $where = array(
                            "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                        );
                        $tr->updateUangMukaSrc($where, $update);
                        cekHitam($this->db->last_query());
                    }
                    else {
                        //insertbaru brooo
                        $tr->writeUangMukaSrc($insertID, array(
                            "jenis" => $stepCode,
                            "target_jenis" => $uangMukaSrcConfig['jenisTarget'],
                            "reference_jenis" => $uangMukaSrcConfig['jenisSrc'],
                            "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                            "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                            "nomer" => "",
                            "note" => "",
                            "label" => $uangMukaSrcConfig['label'],
                            "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                            "terbayar" => 0,
                            "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                            "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                            "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "fulldate" => date("Y-m-d"),
                            "extern_label2" => $externSrc['extLabel'],
                        ));
                    }
                    cekMerah($this->db->last_query());
                }
            }
            else {
                cekLime("not write uang muka");
            }

        }
        else {
            cekMerah("not write uang muka");
        }
        //endregion

        cekMerah("MULAI LAST_VALIDATE");
        $va->setJenisTr($this->jenisTr);
        $va->lastValidate($insertID);
        //        mati_disini("setelah lastValidate");

//        cekKuning(":: mulai cek rek besar dan rek pembantu");
//        $cabangID_validate = $this->session->login['cabang_id'];


//        validateBalancesComparison($cabangID_validate, $componentGate, $componentConfig, "master", $insertID, $tmpNomorNota2);
//        validateJurnal($insertID, $componentConfig);
//        validateAllBalances();


        //==================================================================================================
        $this->load->model("Mdls/MdlTransaksiLaporan");
        $lt = New MdlTransaksiLaporan();
        $dataTransaksiLaporan = array(
            "transaksi_id" => $insertID,
            "master_id" => $masterID,
            "nomer" => $tmpNomorNota2,
            "metode" => "reguler",
        );
        $lt->addData($dataTransaksiLaporan);
        showLast_query("ungu");
        //==================================================================================================
        //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
        $this->load->model("Mdls/MdlLockerTransaksi");
        $lt = New MdlLockerTransaksi();
        $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], $transaksiID_reference, $insertID);
        //==================================================================================================



        //==tampilkan receipt
        cekOrange("-- DONE --");

        //region writelog
        echo "<script>top.writeProgress('sedang menulis ke log');</script>";
        $this->load->model("Mdls/" . "MdlActivityLog");
        $hTmp = new MdlActivityLog();
        $tmpHData = array(
            "title" => $_SESSION[$cCode]['main']['jenisTrName'],
            "sub_title" => "Saving followup process",
            "uid" => $this->session->login['id'],
            "uname" => $this->session->login['nama'],
            "dtime" => date("Y-m-d H:i:s"),
            "transaksi_id" => $insertID,
            "deskripsi_old" => "",
            "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
            "jenis" => $this->jenisTr,
            "ipadd" => $_SERVER['REMOTE_ADDR'],
            "devices" => $_SERVER['HTTP_USER_AGENT'],
            "category" => "transaksi",
            "controller" => $this->uri->segment(1),
            "method" => $this->uri->segment(2),
            "url" => current_url(),

        );
        $logID = $hTmp->addData($tmpHData, $hTmp->getTableName()) or die(lgShowError("Gagal menulis riwayat data", __FILE__));
        //endregion


        $endtime = microtime(true); // Bottom of page
        $val = $endtime - $starttime;

//        mati_disini(__FUNCTION__ . "  TRANSAKSI BERHASIL (UNDER MAINTENANCE)  <br> silahkan tutup browser terlebih dahulu. <br>execute in " . $val . " ms");
//        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");

        $pakai_ini = 0;
        if($pakai_ini == 1){
            if (isset($_SESSION[$cCode])) {
                unset($_SESSION[$cCode]);
            }

            if (isset($_SESSION["_TR_" . $origJenis])) {
                unset($_SESSION["_TR_" . $origJenis]);
            }

            if (isset($oldCode)) {
                if (isset($_SESSION[$oldCode])) {
                    unset($_SESSION[$oldCode]);
                }
            }
        }

        return $insertID;
    }
    public function doFollowup_3_unused($trID, $nextStepNumber, $fromStepNumber)
    {
        $ipadd = $_SERVER['REMOTE_ADDR'];
        $starttime = microtime(true);
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

        $gmr = img_working();
        echo "\n" . 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'>");

//        $transaksiID_reference = $no = rtrim($this->uri->segment(5), "-");
//        $stepNum = $this->uri->segment(6);
//        $stepNumCurrent = $this->uri->segment(7);
        $transaksiID_reference = $no = $trID;
        $stepNum = $nextStepNumber;
        $stepNumCurrent = $fromStepNumber;

        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'] : 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

            $tokoID = $_SESSION[$cCode]['main']['tokoID'];
            $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];
            $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>";
                        if (isset($detailValues[$row->produk_id][$key])) {
                            $items[$row->produk_id][$key] = $detailValues[$row->produk_id][$key];
                        }
                        else {
                            if (isset($row->$key)) {
                                $items[$row->produk_id][$key] = $row->$key;
                            }
                        }
                        echo "dan sekarang nilainya: " . $items[$row->produk_id][$key] . "<br>";
                    }
                }
            }
        }
        else {
            $masterID = 0;
            $tmpNomorNota = "XXXX";
            $origJenis = 0;
            $topID = 0;
            die(lgShowAlert("No such receipt ID: $no!"));
        }

        //-------------------------------------------------

        $this->load->library("Transaksional");
        $lt = New Transaksional();
        //-------
        $sessionData[$this->cCode] = $_SESSION[$this->cCode];
        //-------
        $lt->setCCode($this->cCode);
        $lt->setModul($this->modul);
        $lt->setJenisTr($this->jenisTr);
        $lt->setCCodeData($sessionData);
        $lt->setStepNum($stepNum);
        $lt->setStepNumCurrent($stepNumCurrent);
        $lt->setTransaksiNumber($no);
        $lt->setConfigUiModul($this->configUi);
        $lt->setConfigLayoutModul($this->configLayout);
        $lt->setConfigCoreModul($this->configCore);
        $lt->setConfigValuesModul($this->configValues);
        $lt->setConfigCoreMaster($this->config->item('heTransaksi_core'));
        //-------

        //region build table rekening
        if ($runCoreAkunting == true) {
            $lt->buildTableRekening();
        }
        //endregion

        /* ------------------------------
         * TRANSAKSIONAL TERJADI DI DALAM SINI
         * $dieForDebug = false; --------> kondisi normal transaksi bisa lanjot
         * untuk mematikan transksi di jadikan true
         * ------------------------*/
        $dieForDebug = false;
//        $dieForDebug = true;

        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();

        arrPrintWebs($sessionData[$this->cCode]);


        $libResult = $lt->doFollowup();

        $tmpNomorNota2 = isset($libResult["tmpNomerNota"]) ? $libResult["tmpNomerNota"] : "";
        $tmpTransaksiID = isset($libResult["transaksiId"]) ? $libResult["transaksiId"] : "";
        $tmpTransaksConectingiID = isset($libResult["transaksiIdConnecting"]) ? $libResult["transaksiIdConnecting"] : "";

        //==tampilkan receipt
        cekOrange("-- DONE -- $ipadd");
        if ($dieForDebug === true) {
            cekMerah( json_encode($libResult) );
            mati_disini(__FUNCTION__ . " *** under maintenance ***  <br> TUNGGU SEBENTAR YA... @" . __LINE__);
        }

        //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" => $tmpTransaksConectingiID,
            "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;


//        cekHere("this->jenisTr : " . $this->jenisTr);
//        cekHere("stepNum : " . $stepNum);
//      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!");

        $connectToApk = isset($this->configUi[$this->jenisTr]["steps"][$stepNum]["connectToApk"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNum]["connectToApk"] : array();

        if(!empty($connectToApk)){

            switch($stepNum){
                case "2":
//                    $response = array(
//                        "status" => 999,
//                        "toko_id" => $this->session->login['toko_id'],
//                        "nomor_referensi" => $_SESSION[$cCode]['tableIn_master']['nomer'],
//                        "nomer" => $libResult["sessionData"]['main']['nomer'],
//                        "oleh_id" => $this->session->login['id'],
//                        "oleh_nama" => $this->session->login['nama'],
//                        "seller_id" => $_SESSION[$cCode]['main']['logistikInternal'],
//                        "datetime" => date("Y-m-d H:i:s"),
//                        "seller_nama" => $_SESSION[$cCode]['main']['logistikInternal__nama'],
//                        "customer_id" => $_SESSION[$cCode]['main']['customerDetails'],
//                        "customer_nama" => $_SESSION[$cCode]['main']['customerDetails__nama'],
//                        "customer_alamat" => $_SESSION[$cCode]['main']['customerDetails__alamat_1'],
//                        "customer_telp" => $_SESSION[$cCode]['main']['customerDetails__tlp_1'],
//                        "produk_blob" => base64_encode(json_encode($_SESSION[$cCode]['items'])), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agakr bisa di urai di javascript
//                    );
//                    $sendToApk = $curl->_simple_call("post", "https://boga.mayagrahakencana.com/run_sakura_apk/eusvc/Entries/writeDataLogistik", $response);
                    break;
                case "3":
//                    $response = array(
//                        "nomor_referensi" => $_SESSION[$cCode]['tableIn_master']['nomer'],
//                        "logistik_approve_nomer" => $libResult["sessionData"]['main']['nomer'],
//                        "logistik_approve_by_id" => $this->session->login['id'],
//                        "logistik_approve_by_nama" => $this->session->login['nama'],
//                    );
//                    $sendToApk = $curl->_simple_call("post", "https://boga.mayagrahakencana.com/run_sakura_apk/eusvc/Entries/updateDataLogistik", $response);
//                    cekMerah("sendToApk");
//                    arrPrint($sendToApk);
                    break;
                case "4":
                    $this->load->library("Curl");
                    $curl = New Curl();
                    $arrProduk = $libResult['sessionData']['items'];
                    $response = array(
                        "status" => 999,
                        "toko_id" => $this->session->login['toko_id'],
                        "nomor_referensi" => $_SESSION[$cCode]['tableIn_master']['nomer'],
                        "nomer" => $libResult["sessionData"]['main']['nomer'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "seller_id" => $_SESSION[$cCode]['main']['logistikInternal'],
                        "datetime" => date("Y-m-d H:i:s"),
                        "seller_nama" => $_SESSION[$cCode]['main']['logistikInternal__nama'],
                        "customer_id" => $_SESSION[$cCode]['main']['customerDetails'],
                        "customer_nama" => $_SESSION[$cCode]['main']['customerDetails__nama'],
                        "customer_alamat" => $_SESSION[$cCode]['main']['customerDetails__alamat_1'],
                        "customer_telp" => $_SESSION[$cCode]['main']['customerDetails__tlp_1'],
                        "produk_blob" => base64_encode(json_encode($arrProduk)), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agakr bisa di urai di javascript
                    );
                    $writeDataLogistik = $curl->_simple_call("post", "https://boga.mayagrahakencana.com/run_sakura_apk/eusvc/Entries/writeDataLogistik", $response);
                    $this->load->library("Curl");
                    $curl = New Curl();
                    $response = array(
                        "status"            => 999,
                        "toko_id"           => $libResult['sessionData']['main']['tokoID'],
                        "validGrandTotal"   => $libResult['sessionData']['main']['piutang_dagang'],
                        "nomor_referensi"   => $libResult['sessionData']['main']['nomer'],
                        "referensi_id"      => $tmpTransaksiID,
                        "oleh_id"           => $libResult['sessionData']['main']['olehID'],
                        "oleh_nama"         => $libResult['sessionData']['main']['olehName'],
//                        "collector_id"      => $libResult['sessionData']['main']['penagihID'],
                        "datetime"          => date("Y-m-d H:i:s"),
//                        "collector_nama"    => $libResult['sessionData']['main']['penagihName'],
                        "customer_id"       => $libResult['sessionData']['main']['customerDetails'],
                        "customer_nama"     => $libResult['sessionData']['main']['customerDetails__nama'],
                        "customer_alamat"   => $libResult['sessionData']['main']['customerDetails__alamat_1'],
                        "customer_telp"     => $libResult['sessionData']['main']['customerDetails__tlp_1'],
                        "produk_blob"       => base64_encode(json_encode($arrProduk)), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agakr bisa di urai di javascript
                    );
                    $writeDataCollector = $curl->_simple_call("post", "https://boga.mayagrahakencana.com/run_sakura_apk/eusvc/Entries/writeDataCollector", $response);
                    break;
            }
        }

// matiHere("stok dulu cek apk ");
// cekMerah("response yang di kirim");
// arrPrintWebs($response);
// cekMerah("stepNum: $stepNum");
// cekMerah("connectToApk");
// arrPrint($connectToApk);
// matiHere("mati dulu cek API");

//        if (isset($_SESSION[$cCode])) {
//            if (isset($_SESSION[$cCode]["main"]["print_barcode"]) && $_SESSION[$cCode]["main"]["print_barcode"] == "1") {
//                echo "<script>";
//                echo "window.open('" . base_url() . "Addons/BarcodePrinter/doPrint/?FromTransaksi=" . $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);
//        }

                $pakai_ini = 0;
        if($pakai_ini == 1){
            if (isset($_SESSION[$cCode])) {
                unset($_SESSION[$cCode]);
            }

            if (isset($_SESSION["_TR_" . $origJenis])) {
                unset($_SESSION["_TR_" . $origJenis]);
            }

            if (isset($oldCode)) {
                if (isset($_SESSION[$oldCode])) {
                    unset($_SESSION[$oldCode]);
                }
            }
        }

cekHere("stepNum Sekarang: " . $stepNum);

        $arrStep = $this->configUi[$this->jenisTr]['steps'];
        foreach ($arrStep as $step => $spec) {

            $paramStep = "step_$step";
            $paramAutoStep = "auto_step_$step";
            $$paramStep = $step;
            $$paramAutoStep = isset($spec['autoStep']) ? $spec['autoStep'] : 0;

            if($step==$stepNum){
                cekHijau("$paramAutoStep: " . $$paramAutoStep);
                if($$paramAutoStep*1>0 && $arrStep[$step+1]){
                    arrPrintWebs($arrStep[$step+1]);
                    //jalankan auto selanjutnya
                    $return = array(
                        "autostep" => 1,
                        "stepNum" => $stepNum*1,
                        "stepNow" => $step*1,
                        "fromStepNumber" => $stepNum*1,
                        "nextStepNumber" => ($step+1)*1,
                        "transaksi_id" => $tmpTransaksiID*1,
                        "state" => "#1",
                    );
                    return $return;
                }
                else{
                    //tidak menjalankan auto step
                    $return = array(
                        "autostep" => 0,
                        "stepNow" => $step*1,
                        "stepNum" => $stepNum*1,
                        "transaksi_id" => $tmpTransaksiID*1,
                        "state" => "#2",
                    );
                    return $return;
                }
            }
        }
    }
    public function doFollowup_4_unused($trID, $nextStepNumber, $fromStepNumber)
    {
        echo "\n<script>top.writeProgress('MEMULAI PROSES FOLLOWUP....');</script>";
        $starttime = microtime(true);
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

//        $transaksiID_reference = $no = rtrim($this->uri->segment(5), "-");
//        $stepNum = $this->uri->segment(6);
//        $stepNumCurrent = $this->uri->segment(7);
        $transaksiID_reference = $no = $trID;
        $stepNum = $nextStepNumber;
        $stepNumCurrent = $fromStepNumber;


        echo "\n<script>top.writeProgress('MEMUAT CONFIG', 'HEAD');</script>";

        $paramPatchers = $this->config->item('heTransaksi_paramPatchers') != null ? $this->config->item('heTransaksi_paramPatchers') : array();
        $paramForceFillers = $this->config->item('heTransaksi_paramForceFillers') != null ? $this->config->item('heTransaksi_paramForceFillers') : array();

        echo "\n<script>top.writeProgress('MENYIAPKAN CALCULATOR', 'HEAD');</script>";

        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();

        echo "\n<script>top.writeProgress('MENYIAPKAN DATA-DATA TRANSAKSI', 'HEAD');</script>";

        //==ambil datanya
        $stepNowParameter = array();
        $this->load->model("MdlTransaksi");
        $tr = new MdlTransaksi();
        $tr->addFilter("id in (" . implode(",", explode("-", $no)) . ")");
        $tr->addFilter("step_number='" . $stepNumCurrent . "'");
        $tr->addFilterJoin("transaksi_data.trash='0'");
        $tmpTr = $tr->lookupJoined();
        if (sizeof($tmpTr) > 0) {
            $this->jenisTr = $tmpTr[0]->jenis_master;

            $cCode = "_TR_" . $this->jenisTr;
            //region session init
            if (!isset($_SESSION[$cCode])) {
                $_SESSION[$cCode] = array(
                    "items" => array(),
                    "main" => array(),
                );
            }
            if (!isset($_SESSION[$cCode]['main'])) {
                $_SESSION[$cCode]['main'] = array();
            }
            if (!isset($_SESSION[$cCode]['items'])) {
                $_SESSION[$cCode]['items'] = array();
            }
            $_SESSION[$cCode]['rsltItems'] = array();
            $_SESSION[$cCode]['rsltItems2'] = array();
            //endregion

            $jenisTrTarget = isset($this->configUi[$this->jenisTr]["steps"][$stepNum]["target"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNum]["target"] : NULL;
            $detailValuesConfig = isset($this->configCore[$this->jenisTr]['tableIn']['detailValues']) ? $this->configCore[$this->jenisTr]['tableIn']['detailValues'] : array();
            $additionalData = isset($this->configUi[$this->jenisTr]["addDetailData"][$stepNum]) ? $this->configUi[$this->jenisTr]["addDetailData"][$stepNum] : array();

            $masterID = $_SESSION[$cCode]['main']['masterID'];
            $topID = $tmpTr[0]->id_top;
            $tmpNomorNota = $tmpTr[0]->nomer;
            $origJenis = $tmpTr[0]->jenis_master;

            //            $trID = $tmpTr[0]->id_master;
            $trID = $tmpTr[0]->transaksi_id;


            $totalSteps = sizeof($this->configUi[$this->jenisTr]['steps']);


            //==references, previous entry
            $prevProp = array(
                "id" => $tmpTr[0]->transaksi_id,
                "jenis" => $tmpTr[0]->jenis,
                "nomer" => $tmpTr[0]->nomer,
            );


            //------
            $stepNowParameter = array(
                "next_step_code" => $tmpTr[0]->next_step_code,
                "next_step_label" => $tmpTr[0]->next_step_label,
                "next_group_code" => $tmpTr[0]->next_group_code,
                "next_step_num" => $tmpTr[0]->next_step_num,
                "step_current" => $tmpTr[0]->step_current,
            );


            $tmpVal_main = $tr->lookupMainValuesByTransID($trID)->result();
            $tmpVal_detail = $tr->lookupDetailValuesByTransID($trID)->result();
            $mainValues = array();
            if (sizeof($tmpVal_main) > 0) {
                foreach ($tmpVal_main as $row) {
                    $mainValues[$row->key] = $row->value;
                }
            }
            $detailValues = array();
            if (sizeof($tmpVal_detail) > 0) {
                foreach ($tmpVal_detail as $row) {
                    $detailValues[$row->produk_id][$row->key] = $row->value;
                }
            }


            $main = array();
            $items = array();
            $prevIDs = array();
            $prevNos = array();
            foreach ($tmpTr as $row) {
                $items[$row->produk_id] = array(
                    "id" => $row->produk_id,
                    "nama" => $row->produk_nama,
                    "jml" => $row->produk_ord_jml,
                    "harga" => $row->produk_ord_hrg,
                    "valid_qty" => $row->valid_qty,
                    "transaksi_id" => $row->transaksi_id,
                    "nomer" => $row->nomer,
                );

                if ($row->valid_qty > 0) {
                    cekHitam("ok lanjut");
                }
                else {
                    if (isset($_SESSION[$cCode]['items'][$row->produk_id])) {
                        matiHere("Followed up already. Please close and refresh your browser " . $row->produk_nama . " " . $row->produk_id);//kalo session active ya harus dimatiin biar gak dobel
                    }
                }

                if (!in_array($row->transaksi_id, $prevIDs)) {
                    $prevIDs[] = $row->transaksi_id;
                }
                if (!in_array($row->nomer, $prevNos)) {
                    $prevNos[] = $row->nomer;
                }
                if (sizeof($detailValuesConfig) > 0) {
                    echo "\ndetail values ada..<br>";
                    foreach ($detailValuesConfig as $key => $src) {
                        echo "\n$key akan ambil nilai dari $src<br>";
                        echo "\n<script>top.writeProgress('$key akan ambil nilai dari $src');</script>";
                        //                            $tmp[$key]=isset($iSpec[$val])?$iSpec[$val]:0;
                        if (isset($detailValues[$row->produk_id][$key])) {
                            //                            $tmp[$key] = formatField($key, $detailValues[$row->produk_id][$key]);
                            $items[$row->produk_id][$key] = $detailValues[$row->produk_id][$key];
                        }
                        else {
                            if (isset($row->$key)) {
                                //                                $tmp[$key] = formatField($key, $row->$key);
                                $items[$row->produk_id][$key] = $row->$key;
                            }
                        }
                        echo "\ndan sekarang nilainya: " . $items[$row->produk_id][$key] . "<br>";
                        echo "\n<script>top.writeProgress('dan sekarang nilainya: " . $items[$row->produk_id][$key] . "');</script>";
                    }
                }
            }

        }
        else {
            $masterID = 0;
            $tmpNomorNota = "XXXX";
            $origJenis = 0;
            $topID = 0;
            die(lgShowAlert("No such receipt ID: $no!"));
        }


        //==ongkir dll (additional fees) harus diselipkan kedalam masterGates aktual
        //region ongkir dll diselipkan ke masterGates
        if (isset($this->configCore[$this->jenisTr]['externalValues']) && sizeof($this->configCore[$this->jenisTr]['externalValues']) > 0) {
            foreach ($this->configCore[$this->jenisTr]['externalValues'] as $exKey => $exSpec) {
                if ($exSpec['useAt'] == $stepNum) {
                    if (isset($exSpec['mdlName']) && strlen($exSpec['mdlName']) > 3) {
                        $_SESSION[$cCode]['main'][$exKey . "_src"] = $_POST[$exKey . "_src"];
                        if (isset($_SESSION[$cCode]['main_add_values'][$exKey . "_src"])) {
                            $_SESSION[$cCode]['main_add_values'][$exKey . "_src"] = $_POST[$exKey . "_src"];
                        }
                    }
                    $_SESSION[$cCode]['main'][$exKey] = $_POST[$exKey];
                    if (isset($_SESSION[$cCode]['main_add_values'][$exKey])) {
                        $_SESSION[$cCode]['main_add_values'][$exKey] = $_POST[$exKey];
                    }

                    if ($exSpec['taxFactor'] > 0) {
                        $_SESSION[$cCode]['main'][$exKey . "_tax"] = $_POST[$exKey . "_tax"];
                        if (isset($_SESSION[$cCode]['main_add_values'][$exKey . "_tax"])) {
                            $_SESSION[$cCode]['main_add_values'][$exKey . "_tax"] = $_POST[$exKey . "_tax"];
                        }
                    }
                }
            }
        }
        //endregion


        //region baca seting optional step
        if (isset($this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField']) && strlen($this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField']) > 0) {
            echo "\n<script>top.writeProgress('READING OPTIONAL STEPs', 'HEAD');</script>";
            $criteriaField = $this->configUi[$this->jenisTr]['steps'][$stepNum]['optCriteriaField'];
            if (isset($_SESSION[$cCode]['main'][$criteriaField]) && $_SESSION[$cCode]['main'][$criteriaField] > 0) {
                echo "\nnextstepnum normal<br>";
                $nextStepNum = ($stepNum + 1);
                $useAdditionalStep = true;
            }
            else {
                echo "\nnextstepnum hampir normal<br>";
                $useAdditionalStep = false;
                $nextStepNum = ($stepNum + 2);
            }
        }
        else {
            //            //cekBiru("OPT TIDAK ditentukan");
            echo "\nnextstepnum TIDAK normal<br>";
            $useAdditionalStep = false;
            $nextStepNum = ($stepNum + 1);
            echo "\nyaitu $nextStepNum<br>";
        }
        //endregion


        //region build table rekening
//        $buildTablesMaster = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'] : array();
//        $buildTablesDetail = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
//
//        //arrPrint($buildTablesMaster);
//
//        $addMasterTables = array(
//            "rugilaba",
//            "laba ditahan",
//            "rugilaba lain lain",
//        );
//        foreach ($addMasterTables as $trek) {
//            $buildTablesMaster[] = array(
//                "comName" => "RugiLaba",
//                "loop" => array(
//                    "$trek" => .0,
//                ),
//            );
//        }
//
//        if (sizeof($buildTablesMaster) > 0) {
//            foreach ($buildTablesMaster as $buildTablesMaster_specs) {
//                $mdlName = $buildTablesMaster_specs['comName'];
//                if (substr($mdlName, 0, 1) == "{") {
//                    //                        cekkuning("mengandung kurawal");
//                    $mdlName = trim($mdlName, "{");
//                    $mdlName = trim($mdlName, "}");
//                    $mdlName = str_replace($mdlName, $_SESSION[$cCode]['main'][$mdlName], $mdlName);
//                }
//                else {
//                    //                        cekkuning("TIDAK mengandung kurawal");
//                }
//                $mdlName = "Com" . $mdlName;
//                cekHitam("model: $mdlName");
//
//
//                if (isset($buildTablesMaster_specs['loop'])) {
//                    foreach ($buildTablesMaster_specs['loop'] as $key => $val) {
//                        unset($buildTablesMaster_specs['loop'][$key]);
//                        //                        if (isset($_SESSION[$cCode]['main'][$key])) {
//                        if (substr($key, 0, 1) == "{") {
//                            $key = trim($key, "{");
//                            $key = trim($key, "}");
//                            $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
//                        }
//                        $buildTablesMaster_specs['loop'][$key] = $val;
//                        //                        }
//                    }
//                }
//
//                $this->load->model("Coms/" . $mdlName);
//                $m = new $mdlName();
//                if (method_exists($m, "getTableNameMaster")) {
//                    if (sizeof($m->getTableNameMaster())) {
//                        $m->buildTables($buildTablesMaster_specs);
//                    }
//                }
//            }
//        }
//
//        if (sizeof($buildTablesDetail) > 0) {
//            foreach ($buildTablesDetail as $buildTablesDetail_specs) {
//                foreach ($_SESSION[$cCode]['items'] as $itemSpec) {
//
//                    $mdlName = $buildTablesDetail_specs['comName'];
//                    if (substr($mdlName, 0, 1) == "{") {
//                        $mdlName = trim($mdlName, "{");
//                        $mdlName = trim($mdlName, "}");
//                        $mdlName = str_replace($mdlName, $itemSpec[$mdlName], $mdlName);
//                    }
//
//                    if (isset($buildTablesDetail_specs['loop'])) {
//                        foreach ($buildTablesDetail_specs['loop'] as $key => $val) {
//                            unset($buildTablesDetail_specs['loop'][$key]);
//
//                            if (substr($key, 0, 1) == "{") {
//                                $key = trim($key, "{");
//                                $key = trim($key, "}");
//                                $key = str_replace($key, $itemSpec[$key], $key);
//                            }
//                            $buildTablesDetail_specs['loop'][$key] = $val;
//                            cekHitam("LINE: " . __LINE__ . " ::sini bukan??  akan build tabel detail $key");
//
//                        }
//                    }
//
//
//                    $mdlName = "Com" . $mdlName;
//                    $this->load->model("Coms/" . $mdlName);
//                    $m = new $mdlName();
//                    if (method_exists($m, "getTableNameMaster")) {
//                        if (sizeof($m->getTableNameMaster())) {
//                            $m->buildTables($buildTablesDetail_specs);
//                            arrPrint($buildTablesDetail_specs);
//                            cekHitam(":: build tabel detail");
//                        }
//                    }
//                }
//            }
//        }
        //endregion


//        $this->db->trans_start();

        //region pembulatan replacer disini
        $injectBulat = isset($this->configCore[$this->jenisTr]['valuePembulatan'][$stepNum]) ? $this->configCore[$this->jenisTr]['valuePembulatan'][$stepNum] : array();
        if (sizeof($injectBulat) > 0) {
            echo "\n<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 "\n<script>top.writeProgress('PEMBULATAN ($fields)');</script>";
            }

        }
        //endregion


        cekMerah(":: MEMULAI PRE-PROCC ITEMS...");


        //region pre-processors (item)
        if (isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail'])) {
            $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail'] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNum]) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'][$stepNum] : array();
            echo "ITEM NUM LABELS";

            if (sizeof($iterator) > 0) {
                echo "\n<script>top.writeProgress('PERSIAPAN PRE-PROCESSOR...', 'HEAD');</script>";
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo "\n".__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 "\nsub 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);
                }
            }
            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);
        }
        else {
            echo "\nno processor defined. skipping preprocessor..<br>";
        }

        //endregion


        //region pre-processors (master)
        if (isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master'])) {
            $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master'] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields']) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'] : array();

            echo "ITEM NUM LABELS";

            if (sizeof($iterator) > 0) {
                echo "\n<script>top.writeProgress('PERSIAPAN PRE-PROCESSOR...', 'HEAD');</script>";
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                    $switchResultParams = isset($tComSpec['switchResultParams']) ? $tComSpec['switchResultParams'] : false;

                    echo "\nmaster-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);


        }
        else {
            echo "\nno processor defined. skipping preprocessor..<br>";
        }

        //endregion

        //region pre-proc value injector items2 items2_sum dari gerbang main
        $injectValues = isset($this->configCore[$this->jenisTr]['preInjectValue'][$stepNum]) ? $this->configCore[$this->jenisTr]['preInjectValue'][$stepNum] : array();
        if (sizeof($injectValues) > 0) {
            $iterator = isset($this->configCore[$this->jenisTr]['preInjectValue'][$stepNum]['master']) ? $this->configCore[$this->jenisTr]['preInjectValue'][$stepNum]['master'] : array();
            $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields']) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'] : array();
            if (sizeof($iterator) > 0) {
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    $resultParams = isset($tComSpec['resultParams']) ? $tComSpec['resultParams'] : array();
                    //                    echo "master-preproc: $comName, initializing values <br>";
                    $tmpOutParams[$cCtr] = array();


                    $subParams = array();
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                            $subParams['static'][$key] = $realValue;

                        }

                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                            foreach ($paramPatchers[$comName] as $k => $v) {
                                if (!isset($subParams['static'][$k])) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                }
                            }
                        }
                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                            $jenis = $_SESSION[$cCode]['main']['jenis'];
                            foreach ($paramForceFillers[$comName] as $k => $v) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }

                        $subParams['static']["fulldate"] = date("Y-m-d");
                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                    }
                    if (sizeof($subParams) > 0) {
                        $tmpOutParams[$cCtr] = $subParams;
                    }


                    $mdlName = "Pre" . ucfirst($comName);
                    $this->load->model("Preprocs/" . $mdlName);
                    $m = new $mdlName($resultParams);


                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
                        $tobeExecuted = true;
                    }
                    else {
                        $tobeExecuted = false;
                    }

                    if ($tobeExecuted) {
                        $m->pair($masterID, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        $gotParams = $m->exec();
                        if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                            //                            cekhijau("ada gotparam, sekarang mau replace");
                            foreach ($gotParams as $gateName => $gSpec) {
                                if ($gateName == "main") {
                                    foreach ($gSpec as $key => $val) {
                                        $_SESSION[$cCode]['main'][$key] = $val;
                                    }
                                }
                                if ($gateName == "items2") {
                                    foreach ($_SESSION[$cCode]['items2'] as $k => $tmpSes) {
                                        foreach ($gSpec as $key => $val) {
                                            foreach ($tmpSes as $y => $sesData) {
                                                if (array_key_exists($key, $sesData)) {
                                                    $_SESSION[$cCode]['items2'][$k][$y][$key] = $val;
                                                }
                                            }
                                        }
                                    }

                                }
                                if ($gateName == "items2_sum") {
                                    foreach ($_SESSION[$cCode]['items2_sum'] as $k => $tmpSes) {
                                        foreach ($gSpec as $key => $val) {
                                            $_SESSION[$cCode]['items2_sum'][$k][$key] = $val;
                                        }
                                    }

                                }

                            }
                        }
                        else {
                            cekmerah("TIDAK ada gotparam, tidak perlu replace");
                        }

                    }
                    else {
                        cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                    }

                }
            }
            else {
                //cekKuning("sub-preproc is not set");
            }

            $this->load->helper("he_value_builder");
            fillValues_he_value_builder($this->jenisTr, $stepNumCurrent, $stepNum, $this->configCoreJenis, $this->configUiJenis);

        }
        //endregion


//        $step = $_SESSION[$cCode]['main']['step_number'];
        $this->load->library("Validator");
        $va = new Validator();
        $va->setConfigUiJenis($this->configUi[$this->jenisTr]);
        $va->setCCode($this->cCode);
        $va->midValidate($stepNum);
        $va->unionValidate();
        //==tulis komponen, if any


        //region update step2an
        if (isset($this->configUi[$this->jenisTr]['steps'][$nextStepNum])) {//===masih ada langkah selanjutnya
            echo "\nauthorizing 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 "\nchecking components..<br>";
        echo "\n<script>top.writeProgress('CHECKING KOMPONEN');</script>";
        //referensi_id pada steps (dimatikan)
        //        $masterReplacers = array(
        //            "referensi_id" => $masterID,
        //        );
        //        $childReplacers = array(
        //            "referensi_id" => $masterID,
        //        );
        //        foreach ($masterReplacers as $key => $val) {
        //            $_SESSION[$cCode]['main'][$key] = $val;
        //        }
        //        foreach ($childReplacers as $key => $val) {
        //            foreach ($_SESSION[$cCode]['out_detail'] as $xid => $cSpec) {
        //                $id = $cSpec['id'];
        //                $_SESSION[$cCode]['out_detail'][$id][$key] = $val;
        //            }
        //
        //        }


        //==tulis signature

        $dwsign = $tr->writeSignature($masterID, array(
            "nomer" => $tmpNomorNota,
            "step_number" => $stepNum,
            "step_code" => $this->configUi[$origJenis]['steps'][$stepNum]['target'],
            "step_name" => $this->configUi[$origJenis]['steps'][$stepNum]['label'],
            "group_code" => $this->configUi[$origJenis]['steps'][$stepNum]['userGroup'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "keterangan" => $this->configUi[$origJenis]['steps'][$stepNum]['label'] . " oleh " . $this->session->login['nama'],
            "transaksi_id" => $masterID,
        )) or die("Failed to write signature");
        $mongoList['sign'][] = $dwsign;
        //cekKuning($this->db->last_query());

        //region update step terdahulu
        $tr = new MdlTransaksi();
        $dupState = $tr->updateData(array("id" => $topID), array(
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            "next_step_num" => $nextProp['num'],
            "step_current" => $stepNum,

            "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,

        )) or die("Failed to update tr next-state!");
        $mongUpdateList['update']['main'][] = array(
            "where" => array("id" => "$topID"),
            "value" => array(
                "next_step_code" => $nextProp['code'],
                "next_step_label" => $nextProp['label'],
                "next_group_code" => $nextProp['groupID'],
                "next_step_num" => $nextProp['num'],
                "step_current" => $stepNum,
            ),
        );
        cekHijau($this->db->last_query());

        //-------------------------------------------------
        $tr = new MdlTransaksi();
        $dupState = $tr->updateData(array("id" => $trID), array(
            "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,
        )) or die("Failed to update tr next-state!");
        $mongUpdateList['update']['main'][] = array(
            "where" => array("id" => "$trID"),
            "value" => array(
                "partial" => isset($_SESSION[$cCode]['main']['partial']) ? $_SESSION[$cCode]['main']['partial'] : 0,
            ),
        );


        //mati_disini("==== ==== ====");
        //endregion


        //==prepare kloningan
        $tCode = $this->configUi[$origJenis]['steps'][$stepNum]['target'];
        $tCodeName = $this->configUi[$origJenis]['steps'][$stepNum]['label'];
        $masterReplacers = array(
            //            "referensi_id" => $masterID, (dimatikan)
            //            "id_master"       => $masterID,
            //            "id_top"          => $topID,
            "inv" => $tmpNomorNota,
            //            "jenis_top"           => $tCode,
            "jenis" => $tCode,
            "jenis_label" => $tCodeName,
            "transaksi_jenis" => $tCode,
            "cabang_id" => selectedTransactionSession() ? $_SESSION[$cCode]['main']['cabangID'] : $this->session->login['cabang_id'],
            "cabang_nama" => selectedTransactionSession() ? $_SESSION[$cCode]['main']['cabangName'] : $this->session->login['cabang_nama'],
            "oleh_id" => $this->session->login['id'],
            "oleh_nama" => $this->session->login['nama'],
            "step_current" => "0",
            "step_number" => $stepNum,
            //            "next_step_code"      => "",
            //            "next_step_label"     => "",
            //            "next_group_code"     => "",
            "next_step_code" => $nextProp['code'],
            "next_step_label" => $nextProp['label'],
            "next_group_code" => $nextProp['groupID'],
            //===references
            "id_master" => $masterID,
            "id_top" => $topID,
            "ids_prev" => base64_encode(serialize($prevIDs)),
            "ids_prev_intext" => print_r($prevIDs, true),
            "nomer_top2" => isset($_SESSION[$cCode]['main']['nomer_top2']) ? $_SESSION[$cCode]['main']['nomer_top2'] : "",
            "nomer_top" => $_SESSION[$cCode]['tableIn_master']['nomer_top'],
            "nomers_prev" => base64_encode(serialize($prevNos)),
            "nomers_prev_intext" => print_r($prevNos, true),
            //            "jenis_top"           => $this->jenisTr,
            "jenises_prev" => base64_encode(serialize(array($prevProp['jenis']))),
            "jenises_prev_intext" => print_r(array($prevProp['jenis']), true),
            "tail_number" => $stepNum,
            "tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
        );

        foreach ($masterReplacers as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        $childTableRepaclers = array(
            "sub_step_number" => $stepNum,
            "sub_step_current" => $stepNum,
            "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
            "next_substep_num" => $nextProp['num'],
            "next_substep_code" => $nextProp['code'],
            "next_substep_label" => $nextProp['label'],
            "next_subgroup_code" => $nextProp['groupID'],
        );
        foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
            //			$id = $dSpec['id'];
            foreach ($childTableRepaclers as $key => $val) {
                $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
            }
        }


        $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->configCore[$origJenis]['formatNota']);
        if (!in_array($counterForNumber[0], $this->configCore[$origJenis]['counters'])) {
            die(__LINE__ . " Used number should be registered in 'counters' config as well");
        }

        foreach ($counterForNumber as $i => $cRawParams) {
            $cParams = explode("|", $cRawParams);
            $cValues = array();
            foreach ($cParams as $param) {
                $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
            }
            $cRawValues = implode("|", $cValues[$i]);
            $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);
        }
        $tmpNomorNota2 = $paramSpec['paramString'];
        $tmpNomorNota2Alias = formatNota("nomer_nolink", $tmpNomorNota2);

        //endregion

        //region dynamic counters #1
        echo "\n<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->configCore[$origJenis]['counters'];
        $configCustomParams[] = "stepCode";
        if (sizeof($configCustomParams) > 0) {
            $cContent = array();
            foreach ($configCustomParams as $i => $cRawParams) {
                $cParams = explode("|", $cRawParams);
                $cValues = array();
                foreach ($cParams as $param) {
                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                }
                $cRawValues = implode("|", $cValues[$i]);
                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                switch ($paramSpec['id']) {
                    case 0: //===counter type is new
                        $paramKeyRaw = print_r($cParams, true);
                        $paramValuesRaw = print_r($cValues[$i], true);
                        $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                        break;
                    default: //===counter to be updated
                        $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                        break;
                }
                //echo "<hr>";
            }
        }
        $appliedCounters2 = base64_encode(serialize($cContent));
        $appliedCounters_inText2 = print_r($cContent, true);


        $masterReplacers = array(
            "nomer" => $tmpNomorNota2,
            "nomer2" => $tmpNomorNota2Alias,
            "counters" => $appliedCounters2,
            "counters_intext" => $appliedCounters_inText2,
        );
        foreach ($masterReplacers as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        $addValues = array(
            'counters' => $appliedCounters2,
            'counters_intext' => $appliedCounters_inText2,
            'nomer' => $tmpNomorNota2,
            'nomer2' => $tmpNomorNota2Alias,
            'dtime' => date("Y-m-d H:i:s"),
            'fulldate' => date("Y-m-d"),
        );
        foreach ($addValues as $key => $val) {
            $_SESSION[$cCode]['tableIn_master'][$key] = $val;
        }

        // </editor-fold>
        //endregion


        //==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']);
            showLast_query("ungu");
            $epID = $tr->writeMainEntries_entryPoint($insertID, $masterID, $_SESSION[$cCode]['tableIn_master']);
            $mongoList['main'] = array($insertID, $epID);
            $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
            $_SESSION[$cCode]['main']['nomer'] = $insertNum;
            if ($insertID < 1) {
                die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
            }


            if (isset($_SESSION[$cCode]['tableIn_master']['ids_his'])) {
                $idHis_decode = blobDecode($_SESSION[$cCode]['tableIn_master']['ids_his']);
                $idHis_decode[$stepNum] = array(
                    "olehID" => $_SESSION[$cCode]['main']['olehID'],
                    "olehName" => $_SESSION[$cCode]['main']['olehName'],
                    "step" => $stepNum,
                    "trID" => $insertID,
                    "nomer" => $tmpNomorNota2,
                    "nomer2" => $tmpNomorNota2Alias,
                    "counters" => $appliedCounters2,
                    "counters_intext" => $appliedCounters_inText2,
                );
                $idHis_blob = blobEncode($idHis_decode);
                $idHis_intext = print_r($idHis_decode, true);

                $_SESSION[$cCode]['tableIn_master']['ids_his'] = $idHis_blob;
                $_SESSION[$cCode]['tableIn_master']['ids_his_intext'] = $idHis_intext;


                $tr = new MdlTransaksi();
                $dup = $tr->updateData(array("id" => $insertID), array(
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

                )) or die("Failed to update tr next-state!");
                cekUngu($this->db->last_query());
            }


            cekUngu(":: insertID => $insertID ::");
            if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                $inserMainValues = array();
                $mongoList['mainValues'] = array();
                foreach ($_SESSION[$cCode]['tableIn_master_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $inserMainValues[] = $dd;
                    $mongoList['mainValues'][] = $dd;
                }
                if (sizeof($inserMainValues) > 0) {
                    $arrBlob = blobEncode($inserMainValues);
                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $mongoList['mainValues'][] = $dd;
                }
            }
            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $mongoList['mainValues'][] = $dd;
                }
            }
            if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                    $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                }
            }


            if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                //                cekMerah("ada mainElements $cCode");
                //                arrprint($_SESSION[$cCode]['main_elements']);die();
                foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                    $tr->writeMainElements($insertID, array(
                        "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                        "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                        "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                        "name" => $aSpec['name'],
                        "label" => $aSpec['label'],
                        "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                        "contents_intext" => isset($aSpec['contents_intext']) ? print_r($aSpec['contents_intext'], true) : "",

                    ));
                }
            }
            else {
                //                cekMerah("TAK ada mainElements");
            }

            if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => isset($dSpec[$src]) ? $dSpec[$src] : 0,
                            ));
                            $insertIDs[$pID][] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }

                    }
                }
                if (sizeof($insertIDs) > 0) {
                    $arrBlob = blobEncode($insertIDs);
                    $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                            $insertIDs[] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }


                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detail_rsltItems'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail_rsltItems'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                            $insertIDs[$pID][] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }


                }
            }


            //region update validQty pada step sebelumnya yang di-refer
            echo "<script>top.writeProgress('EXTRACT ITEMS...','head');</script>";
            $seluruhnya = true;
            $prevTrID = 0;
            $arrvalidQtySisa = array();
            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {
                $closedRequest = isset($this->configCore[$origJenis]['closedRequest'][$stepNum]['enabled']) ? $this->configCore[$origJenis]['closedRequest'][$stepNum]['enabled'] : false;
                $insertIDs = array();
                $insertDeIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail'] as $iID => $dSpec) {
                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                    if ($insertDetailID < 1) {
                        die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                    }
                    else {
                        $insertIDs[] = $insertDetailID;
                        $insertDeIDs[$insertID][] = $insertDetailID;
                        $mongoList['detail'][] = $insertDetailID;

                    }

                    if ($epID != 999) {
                        $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                        if ($insertEpID < 1) {
                            die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                        }
                        else {
                            $insertIDs[] = $insertEpID;
                            $insertDeIDs[$epID][] = $insertEpID;
                            $mongoList['detail'][] = $insertDetailID;
                        }
                    }

                    cekHitam("EXTRACTED ITEMS... [$iID]");
                    echo "<script>top.writeProgress('" . strtoupper($dSpec['produk_nama']) . "');</script>";


                    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;
                                $updateContents = array(
                                    "valid_qty" => $newValidQty,
                                    "valid_qty_no_approve" => $newValidQtyNotApprove,
                                );
                                if ($newValidQty < 1) {
                                    $childPrevRepaclers = array(
                                        "next_substep_code" => "",
                                        "next_substep_label" => "",
                                        "next_subgroup_code" => "",
                                        "sub_tail_number" => $stepNum,
                                        "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'],
                                    );
                                    foreach ($childPrevRepaclers as $key => $val) {
                                        $updateContents[$key] = $val;
                                    }
                                }
                                else {//==kalau ada yang tidak habis, berarti TIDAK seluruhnya yang dilanjutkan pada step berikutnya
                                    $seluruhnya = false;
                                    $arrvalidQtySisa[$iID] = $newValidQty;
                                }
                                $dupState = $tru->updateData(array(
                                    "produk_id" => $iID,
                                    "id" => $triID,
                                    "transaksi_id" => $triSpec['transaksi_id'],
                                ), $updateContents) or die("Failed to update previous detail entries!");
                                cekHijau($this->db->last_query());

                                $mongUpdateList['update']['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


            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($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget] : array(),
                "preProcessor" => isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget] : array(),
                "postProcessor" => isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget] : array(),
                "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
                "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),

            );
            $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


        //region processing sub-post-processors, always
        //<editor-fold desc="----------sub postProc">

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail'] : array();
        if (sizeof($iterator) > 0) {
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, initializing values <br>";
                echo "<script>top.writeProgress('MENYIAPKAN DATA SUB-PROCESSORS UNTUK DIKIRIM...', 'head');</script>";

                $tmpOutParams[$cCtr] = array();
                foreach ($_SESSION[$cCode][$srcGateName] as $cnt => $dSpec) {
                    $subParams = array();
                    if (isset($tComSpec['loop'])) {
                        foreach ($tComSpec['loop'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                            $subParams['loop'][$key] = $realValue;

                        }
                    }
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cnt], $_SESSION[$cCode][$srcGateName][$cnt], 0);
                            $subParams['static'][$key] = $realValue;
                            cekBiru("$key diisi dengan $realValue");

                        }

                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                            foreach ($paramPatchers[$comName] as $k => $v) {
                                if (!isset($subParams['static'][$k])) {
                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                }
                            }
                        }
                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                            $jenis = $_SESSION[$cCode]['main']['jenis'];
                            foreach ($paramForceFillers[$comName] as $k => $v) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                                cekorange(":: $k diisikan dengan " . $subParams['static'][$k]);
                            }
                        }

                        $subParams['static']["fulldate"] = date("Y-m-d");
                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                    }

                    if (sizeof($subParams) > 0) {
                        $tmpOutParams[$cCtr][] = $subParams;
                    }
                    echo "<script>top.writeProgress('" . isset($subParams['static']['name']) ? $subParams['static']['name'] : "" . " " . isset($subParams['static']['extern_nama']) ? $subParams['static']['extern_nama'] : "" . " " . isset($subParams['static']['nama']) ? $subParams['static']['nama'] : "" . "');</script>";
                }
            }

            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "sub-postProcessor: $comName, sending values <br>";
                echo "<script>top.writeProgress('SENDING SUB-PROCESSORS ($comName)...', 'head');</script>";
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                cekBiru($this->db->last_query());
            }
        }

        //endregion

        //
        //region processing main-post-processors, always
        //<editor-fold desc="----------postProc">

        $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master'] : array();
        if (sizeof($iterator) > 0) {
            echo "<script>top.writeProgress('MEMPROSES MAIN-PROCESSORS...', 'head');</script>";
            foreach ($iterator as $cCtr => $tComSpec) {
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "post-processor: $comName<br>";

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['loop'][$key] = $realValue;

                    }
                }
                if (isset($tComSpec['static'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                                echo "<script>top.writeProgress(':: $key diisikan dengan " . $tmpOutParams['static'][$k] . ");</script>";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            echo "<script>top.writeProgress(':: $key diisikan dengan " . $tmpOutParams['static'][$k] . ");</script>";
                        }
                    }
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    //cekHere("DISINI OIII");
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$cCtr], $_SESSION[$cCode][$srcGateName][$cCtr], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //                cekBiru("kiriman komponem $comName");
                //                                    arrPrint($tmpOutParams);
                $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);


            }
        }


        //</editor-fold>
        //endregion


        //
        //region ----------subcomponents GESER KE CLI

        //        $componentGate['detail'] = array();
        //        //arrPrint($paramForceFillers);
        $iterator = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
        $componentConfig['detail'] = $iterator;
        //        if (sizeof($iterator) > 0) {
        //            $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
        //            $filterNeeded = false;
        //            if (in_array($mdlName, $compValidators)) {//perlu validasi filter
        //                $filterNeeded = true;
        //            }
        //            foreach ($iterator as $cCtr => $tComSpec) {
        ////                $comName = $tComSpec['comName'];
        //                $srcGateName = $tComSpec['srcGateName'];
        //                $srcRawGateName = $tComSpec['srcRawGateName'];
        //
        //                echo "sub-component: $comName, $srcGateName, initializing values <br>";
        //                $tmpOutParams[$cCtr] = array();
        //                foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
        //                    cekmerah("mengevaluasi $srcGateName..");
        //                    $comName = $tComSpec['comName'];
        //                    if (substr($comName, 0, 1) == "{") {
        //                        $comName = trim($comName, "{");
        //                        $comName = trim($comName, "}");
        //                        $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
        //                        $tComSpec['comName'] = $comName;
        //                        $iterator[$cCtr]['comName'] = $comName;
        //                    }
        //
        //                    $filterNeeded = false;
        //                    $mdlName = "Com" . ucfirst($comName);
        //                    if (in_array($mdlName, $compValidators)) {//perlu validasi filter
        //                        $filterNeeded = true;
        //                    }
        //
        //
        //                    $subParams = array();
        //                    if (isset($tComSpec['loop'])) {
        //                        foreach ($tComSpec['loop'] as $key => $value) {
        //                            if (substr($key, 0, 1) == "{") {
        //                                $key = trim($key, "{");
        //                                $key = trim($key, "}");
        //                                $key = str_replace($key, $_SESSION[$cCode][$srcGateName][$id][$key], $key);
        //                            }
        //                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
        //                            $subParams['loop'][$key] = $realValue;
        //                            cekKuning("LOOP: $key diisi dengan $realValue");
        //
        //                            if ($filterNeeded) {
        //                                if ($subParams['loop'][$key] == 0) {
        //                                    unset($subParams['loop'][$key]);
        //                                }
        //                            }
        //                        }
        //                    }
        //                    if (isset($tComSpec['static'])) {
        //                        foreach ($tComSpec['static'] as $key => $value) {
        //
        //                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
        //                            $subParams['static'][$key] = $realValue;
        //                            cekKuning("STATIC: $key diisi dengan $realValue");
        //
        //                        }
        //                        if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
        //                            foreach ($paramPatchers[$comName] as $k => $v) {
        //                                if (!isset($subParams['static'][$k])) {
        //                                    $subParams['static'][$k] = isset($$v) ? $$v : "_v";
        //                                    cekOrange("fill :: $comName :: $k => " . $subParams['static'][$k]);
        //                                }
        //                            }
        //                        }
        //                        if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
        //                            //                            cekOrange("comName:: $comName");
        //                            $jenis = $_SESSION[$cCode]['main']['jenis'];
        //                            foreach ($paramForceFillers[$comName] as $k => $v) {
        //                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
        //                                cekOrange("fillforce :: $comName :: $k => " . $subParams['static'][$k]);
        //                            }
        //                        }
        //                        $subParams['static']["fulldate"] = date("Y-m-d");
        //                        $subParams['static']["dtime"] = date("Y-m-d H:i:s");
        //                        $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
        //                    }
        //                    cekHitam("cetak subParams");
        //                    arrPrint($subParams);
        //                    if (sizeof($subParams) > 0) {
        //                        if ($filterNeeded) {
        //                            if (isset($subParams['loop']) && sizeof($subParams['loop']) > 0) {
        //                                $tmpOutParams[$cCtr][] = $subParams;
        //                            }
        //                        }
        //                        else {
        //
        //                            $tmpOutParams[$cCtr][] = $subParams;
        //                        }
        //                    }
        //                }
        //
        //                $componentGate['detail'][$cCtr] = $subParams;
        //            }
        //
        //
        //            $it = 0;
        //            foreach ($iterator as $cCtr => $tComSpec) {
        //                $it++;
        //
        //
        //                $comName = $tComSpec['comName'];
        //                $srcGateName = $tComSpec['srcGateName'];
        //                $srcRawGateName = $tComSpec['srcRawGateName'];
        //
        //                echo "sub component #$it: $comName, sending values <br>";
        //
        //                $mdlName = "Com" . ucfirst($comName);
        //                $this->load->model("Coms/" . $mdlName);
        //                $m = new $mdlName();
        //
        //
        //                if (sizeof($tmpOutParams[$cCtr]) > 0) {
        //                    $tobeExecuted = true;
        //                }
        //                else {
        //                    $tobeExecuted = false;
        //                }
        //
        //
        //                if ($tobeExecuted) {
        //                    $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
        //                    $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
        //                }
        //                else {
        //                    cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
        //                }
        //            }
        //        }
        //        else {
        //            //cekKuning("subcomponents is not set");
        //        }

        //endregion


        //region ----------components
        //<editor-fold desc="----------components">

        $componentGate['master'] = array();
        $componentConfig['master'] = array();
        if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
            $iterator = isset($_SESSION[$cCode]['revert']['jurnal'][$stepNum]['master']) ? $_SESSION[$cCode]['revert']['jurnal'][$stepNum]['master'] : array();
        }
        else {
            if (isset($_SESSION[$cCode]['componentsBuilder'][$stepNum]['master'])) {
                $iterator = $_SESSION[$cCode]['componentsBuilder'][$stepNum]['master'];
            }
            elseif (isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'])) {
                $iterator = $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'];
            }
            else {
                $iterator = array();
            }
        }


        if (sizeof($iterator) > 0) {
            echo "<script>top.writeProgress('KOMPONEN...', 'head');</script>";
            $componentConfig['master'] = $iterator;

            $it = 0;
            //==filter nilai, jika NOL tidak dikirim, sesuai config==
            $compValidators = ($this->config->item('transaksi_value_required_components') != null) ? $this->config->item('transaksi_value_required_components') : array();
            foreach ($iterator as $cCtr => $tComSpec) {
                //                cekPink($tComSpec);
                //                mati_disini();
                $it++;
                $comName = $tComSpec['comName'];
                $srcGateName = $tComSpec['srcGateName'];
                $srcRawGateName = $tComSpec['srcRawGateName'];
                echo "component #$it: $comName :: $srcGateName <br>";

                $dSpec = $_SESSION[$cCode][$srcGateName];
                $tmpOutParams = array();
                if (isset($tComSpec['loop'])) {
                    foreach ($tComSpec['loop'] as $key => $value) {
                        if (substr($key, 0, 1) == "{") {
                            $key = trim($key, "{");
                            $key = trim($key, "}");
                            //                            $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
                            $key = str_replace($key, $_SESSION[$cCode][$srcGateName][$key], $key);
                        }
                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        if ($key != null) {
                            $tmpOutParams['loop'][$key] = $realValue;
                        }

                    }
                }
                //                cekBiru($tmpOutParams);
                //                mati_disini(__LINE__);
                if (isset($tComSpec['static'])) {
                    foreach ($tComSpec['static'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static'][$key] = $realValue;
                        cekHijau(":: NORMAL :: $key => $realValue ::");
                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        cekHijau(":: masuk ke PATCHER ::");
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            cekHijau(":: ada yang mau di-PATCHER ::");
                            arrPrint($tmpOutParams['static']);
                            if (!isset($tmpOutParams['static'][$k])) {
                                $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                                cekHijau(":: PATCHER :: $key => $realValue ::");
                            }

                        }
                    }
                    else {
                        cekMerah(":: TIDAK TERMASUK PATCHER ::");
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $tmpOutParams['static'][$k] = isset($$v) ? $$v : "_v";
                            cekHijau(":: FORCEFILL :: $key => $realValue ::");
                        }
                    }
                    $tmpOutParams['static']["urut"] = $cCtr;
                    $tmpOutParams['static']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }
                if (isset($tComSpec['static2'])) {
                    foreach ($tComSpec['static2'] as $key => $value) {

                        $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                        $tmpOutParams['static2'][$key] = $realValue;

                    }
                    if (isset($paramPatchers[$comName]) && sizeof($paramPatchers[$comName]) > 0) {
                        foreach ($paramPatchers[$comName] as $k => $v) {
                            if (!isset($subParams['static'][$k])) {
                                $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                            }
                        }
                    }
                    if (isset($paramForceFillers[$comName]) && sizeof($paramForceFillers[$comName]) > 0) {
                        $jenis = $_SESSION[$cCode]['main']['jenis'];
                        foreach ($paramForceFillers[$comName] as $k => $v) {
                            $subParams['static'][$k] = isset($$v) ? $$v : "_v";
                        }
                    }
                    $tmpOutParams['static2']["fulldate"] = date("Y-m-d");
                    $tmpOutParams['static2']["dtime"] = date("Y-m-d H:i:s");
                    $tmpOutParams['static2']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][$stepNum]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];


                }

                //lgShowError("Ada kesalahan",);
                $mdlName = "Com" . ucfirst($comName);
                $this->load->model("Coms/" . $mdlName);
                $m = new $mdlName();

                //===filter value nol, jika harus difilter
                $tobeExecuted = true;

                if (in_array($mdlName, $compValidators)) {

                    $loopParams = isset($tmpOutParams['loop']) ? $tmpOutParams['loop'] : array();
                    if (sizeof($loopParams) > 0) {
                        foreach ($loopParams as $key => $val) {
                            cekmerah("$comName : $key = $val ");
                            if ($val == 0) {
                                unset($tmpOutParams['loop'][$key]);
                            }
                        }
                    }
                    if (sizeof($tmpOutParams['loop']) < 1) {
                        $tobeExecuted = false;
                    }

                }


                if ($tobeExecuted) {
                    cekBiru("kiriman komponen $comName");
                    arrPrint($tmpOutParams);
                    $m->pair($tmpOutParams) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $m->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                }
                else {
                    cekBiru("komponem $comName tidak memenuhi syarat untuk ditulis");
                }

                $componentGate['master'][$cCtr] = $tmpOutParams;
            }
        }
        else {
            //cekKuning("components is not set");
        }


        //endregion


        //region nulis paymentSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_source");
        if (array_key_exists($stepCode, $paymentSources)) {
            $payConfigs = isset($paymentSources[$stepCode][$stepNum]) ? $paymentSources[$stepCode][$stepNum] : array();
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    $valueSrc = $paymentSrcConfig['valueSrc'];
                    $externSrc = $paymentSrcConfig['externSrc'];
                    if (isset($paymentSrcConfig['model'])) {
                        $mdlName = $paymentSrcConfig['model'];
                        $this->load->model("Mdls/$mdlName");
                        $pMdl = New $mdlName();
                        $pTmpMdl = $pMdl->lookupAll()->result();
                        $pTmpMdlResult = array();
                        if (sizeof($pTmpMdl) > 0) {
                            foreach ($pTmpMdl as $pTmpMdlSpec) {
                                $pTmpMdlResult[$pTmpMdlSpec->id] = $pTmpMdlSpec;
                            }
                        }
                    }
                    else {
                        $pTmpMdlResult = array();
                    }

                    if (isset($_SESSION[$cCode]['main'][$valueSrc]) && $_SESSION[$cCode]['main'][$valueSrc] > 0) {
                        if (isset($externSrc['extern_label2'])) {
                            //cek ada isinya atau kosong
                            $cek = strlen($_SESSION[$cCode]['main'][$externSrc['extern_label2']]) > 4 ? "" : matiHere("jenis biaya tidak dikenali " . __LINE__);//
                        }
                        $arrPymSrc = array(
                            "jenis" => $stepCode,
                            "target_jenis" => $paymentSrcConfig['jenisTarget'],
                            "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                            "extern_id" => isset($_SESSION[$cCode]['main'][$externSrc['id']]) ? $_SESSION[$cCode]['main'][$externSrc['id']] : "",
                            "extern_nama" => isset($_SESSION[$cCode]['main'][$externSrc['nama']]) ? $_SESSION[$cCode]['main'][$externSrc['nama']] : "",
                            "nomer" => $tmpNomorNota2,
                            "label" => $paymentSrcConfig['label'],

                            "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                            "terbayar" => 0,
                            "sisa" => $_SESSION[$cCode]['main'][$valueSrc],

                            "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                            "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "fulldate" => date("Y-m-d"),
                            "valas_id" => isset($externSrc['valasId']) && isset($_SESSION[$cCode]['main'][$externSrc['valasId']]) ? $_SESSION[$cCode]['main'][$externSrc['valasId']] : '',
                            "valas_nama" => isset($externSrc['valasLabel']) && isset($_SESSION[$cCode]['main'][$externSrc['valasLabel']]) ? $_SESSION[$cCode]['main'][$externSrc['valasLabel']] : '',
                            "valas_nilai" => isset($externSrc['valasValue']) && isset($_SESSION[$cCode]['main'][$externSrc['valasValue']]) ? $_SESSION[$cCode]['main'][$externSrc['valasValue']] : '',

                            "tagihan_valas" => isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : '',
                            "terbayar_valas" => 0,
                            "sisa_valas" => isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',

                            //                            "extern_label2" => isset($_SESSION[$cCode]['main']['pihakMainName']) ? $_SESSION[$cCode]['main']['pihakMainName'] : "",
                            "extern_label2" => (isset($externSrc['extern_label2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_label2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_label2']] : "",

                            "ppn" => (isset($externSrc['ppn']) && ($_SESSION[$cCode]['main'][$externSrc['ppn']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn']] : "",
                            "ppn_approved" => (isset($externSrc['ppn_approved']) && ($_SESSION[$cCode]['main'][$externSrc['ppn_approved']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn_approved']] : 0,
                            "ppn_sisa" => (isset($externSrc['ppn']) && ($_SESSION[$cCode]['main'][$externSrc['ppn']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn']] : "",
                            "ppn_status" => (isset($externSrc['ppn_status'])) ? $externSrc['ppn_status'] : 0,
                            "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : 0,
                            "extern_date2" => (isset($externSrc['extern_date2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_date2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_date2']] : "",
                            "pph_23" => (isset($externSrc['pph_23']) && ($_SESSION[$cCode]['main'][$externSrc['pph_23']])) ? $_SESSION[$cCode]['main'][$externSrc['pph_23']] : "",

                            "npwp" => (isset($externSrc['npwp']) && ($_SESSION[$cCode]['main'][$externSrc['npwp']])) ? $_SESSION[$cCode]['main'][$externSrc['npwp']] : "",
                            "extern2_id" => (isset($externSrc['extern2_id']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_id']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_id']] : "",
                            "extern2_nama" => (isset($externSrc['extern2_nama']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_nama']] : "",
                            "ppn_pph_faktor" => (isset($externSrc['ppn_pph_faktor']) && ($_SESSION[$cCode]['main'][$externSrc['ppn_pph_faktor']])) ? $_SESSION[$cCode]['main'][$externSrc['ppn_pph_faktor']] : "",
                            "extern_jenis" => (isset($externSrc['extern_jenis']) && ($_SESSION[$cCode]['main'][$externSrc['extern_jenis']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_jenis']] : "",
                            "extern_nilai3" => (isset($externSrc['extern_nilai3']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai3']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai3']] : "",
                            "extern_nilai4" => (isset($externSrc['extern_nilai4']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai4']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai4']] : "",
                            "npwp" => (isset($externSrc['npwp']) && ($_SESSION[$cCode]['main'][$externSrc['npwp']])) ? $_SESSION[$cCode]['main'][$externSrc['npwp']] : "",
                            //                            "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : "",
                            "payment_locked" => (isset($externSrc['payment_locked']) && ($_SESSION[$cCode]['main'][$externSrc['payment_locked']])) ? $_SESSION[$cCode]['main'][$externSrc['payment_locked']] : 0,
                            "cash_account" => (isset($externSrc['cash_account']) && ($_SESSION[$cCode]['main'][$externSrc['cash_account']])) ? $_SESSION[$cCode]['main'][$externSrc['cash_account']] : 0,
                            "cash_account_nama" => (isset($externSrc['cash_account_nama']) && ($_SESSION[$cCode]['main'][$externSrc['cash_account_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['cash_account_nama']] : 0,
                        );
                        $tr->writePaymentSrc($insertID, $arrPymSrc);

                    }


                    cekMerah($this->db->last_query());
                }
            }

        }
        else {
            cekMerah("TIDAK nulis paymentSrc");
        }

        //matiHere("hoopppp");
        //cek additional step
        $addPaymentSource = isset($this->configUi[$this->jenisTr]['steps'][$stepNum]['additionalStep']['shippingService']) ? $this->configUi[$this->jenisTr]['steps'][$stepNum]['additionalStep']['shippingService'] : array();
        //        arrPrint($addPaymentSource);
        //endregion


        //
        //region nulis paymentAntiSource
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $paymentSources = $this->config->item("payment_antiSource");
        if (array_key_exists($stepCode, $paymentSources)) {
            cekMerah(":: starting PAYMENT ANTI SOURCE");
            $payConfigs = $paymentSources[$stepCode];
            if (sizeof($payConfigs) > 0) {
                foreach ($payConfigs as $paymentSrcConfig) {
                    //					$paymentSrcConfig = $paymentSources[$stepCode];
                    $valueSrc = $paymentSrcConfig['valueSrc'];
                    $externSrc = $paymentSrcConfig['externSrc'];
                    $tr->writePaymentAntiSrc($insertID, array(
                        "jenis" => $stepCode,
                        "target_jenis" => $paymentSrcConfig['jenisTarget'],
                        "reference_jenis" => $paymentSrcConfig['jenisSrc'],
                        "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                        "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                        "nomer" => $tmpNomorNota2,
                        "label" => $paymentSrcConfig['label'],
                        "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                        "terbayar" => 0,
                        "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                        "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                        "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "dtime" => date("Y-m-d H:i:s"),
                        "fulldate" => date("Y-m-d"),
                    ));
                    //cekMerah($this->db->last_query());
                }
            }

        }
        else {
            //cekMerah("TIDAK nulis paymentSrc");
        }
        //endregion

        //region nulis uangMukaSource
        /*dimatiin geser ke ComUangmukaSourceDetail karena ada di items.
        /*revisi tanggal 27 mei 2020 subject digeser ke vendor dari jenis transaksi misal uangmuka asuransi,uang muka pembelian ->uang muka.
         *
         */
        $stepCode = $this->configUi[$this->jenisTr]['steps'][$stepNum]['target'];
        $uangMukaSources = $this->config->item("uang_muka");

        if (array_key_exists($stepCode, $uangMukaSources)) {
            cekMerah(":: starting UANG MUKA  SOURCE");
            //            matiHere();
            $uangMukaConfigs = isset($uangMukaSources[$stepCode][$stepNum]) ? $uangMukaSources[$stepCode][$stepNum] : array();
            if (sizeof($uangMukaConfigs) > 0) {
                $cekPreValue = "";
                $this->load->model("Mdls/MdlPaymentUangMuka");
                $l = new MdlPaymentUangMuka();
                foreach ($uangMukaConfigs as $uangMukaSrcConfig) {
                    //					$paymentSrcConfig = $paymentSources[$stepCode];
                    //                    arrPrint($uangMukaSrcConfig);
                    $valueSrc = $uangMukaSrcConfig['valueSrc'];
                    $externSrc = $uangMukaSrcConfig['externSrc'];
                    $l->addFilter("extern_id='" . $_SESSION[$cCode]['main'][$externSrc['id']] . "'");
                    $l->addFilter("extern_label2='" . $externSrc['extLabel'] . "'");
                    $tmpUm = $l->lookupAll()->result();
                    //                    arrPrint($tmpUm);
                    if (sizeof($tmpUm) > 0) {
                        //update here broo
                        $preTagihan = $tmpUm[0]->tagihan;
                        $preSisa = $tmpUm[0]->sisa;

                        $newTahigan = $preTagihan + $_SESSION[$cCode]['main'][$valueSrc];
                        $newsisa = $preSisa + $_SESSION[$cCode]['main'][$valueSrc];
                        $update = array(
                            "tagihan" => $newTahigan,
                            "sisa" => $newsisa,
                        );
                        $where = array(
                            "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                        );
                        $tr->updateUangMukaSrc($where, $update);
                        cekHitam($this->db->last_query());
                    }
                    else {
                        //insertbaru brooo
                        $tr->writeUangMukaSrc($insertID, array(
                            "jenis" => $stepCode,
                            "target_jenis" => $uangMukaSrcConfig['jenisTarget'],
                            "reference_jenis" => $uangMukaSrcConfig['jenisSrc'],
                            "extern_id" => $_SESSION[$cCode]['main'][$externSrc['id']],
                            "extern_nama" => $_SESSION[$cCode]['main'][$externSrc['nama']],
                            "nomer" => "",
                            "note" => "",
                            "label" => $uangMukaSrcConfig['label'],
                            "tagihan" => $_SESSION[$cCode]['main'][$valueSrc],
                            "terbayar" => 0,
                            "sisa" => $_SESSION[$cCode]['main'][$valueSrc],
                            "cabang_id" => $_SESSION[$cCode]['main']['placeID'],
                            "cabang_nama" => $_SESSION[$cCode]['main']['placeName'],
                            "oleh_id" => $this->session->login['id'],
                            "oleh_nama" => $this->session->login['nama'],
                            "dtime" => date("Y-m-d H:i:s"),
                            "fulldate" => date("Y-m-d"),
                            "extern_label2" => $externSrc['extLabel'],
                        ));
                    }
                    cekMerah($this->db->last_query());
                }
            }
            else {
                cekLime("not write uang muka");
            }

        }
        else {
            cekMerah("not write uang muka");
        }
        //endregion

        cekMerah("MULAI LAST_VALIDATE");
        $va->setJenisTr($this->jenisTr);
        $va->lastValidate($insertID);
        //        mati_disini("setelah lastValidate");


//        cekKuning(":: mulai cek rek besar dan rek pembantu");
//        $cabangID_validate = $this->session->login['cabang_id'];


//        validateBalancesComparison($cabangID_validate, $componentGate, $componentConfig, "master", $insertID, $tmpNomorNota2);
//        validateJurnal($insertID, $componentConfig);
//        validateAllBalances();


        //==================================================================================================
        $this->load->model("Mdls/MdlTransaksiLaporan");
        $lt = New MdlTransaksiLaporan();
        $dataTransaksiLaporan = array(
            "transaksi_id" => $insertID,
            "master_id" => $masterID,
            "nomer" => $tmpNomorNota2,
            "metode" => "reguler",
        );
        $lt->addData($dataTransaksiLaporan);
        showLast_query("ungu");
        //==================================================================================================
        //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
        $this->load->model("Mdls/MdlLockerTransaksi");
        $lt = New MdlLockerTransaksi();
        $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], $transaksiID_reference, $insertID);
        //==================================================================================================



        //==tampilkan receipt
        cekOrange("-- DONE --");

        //region writelog
        echo "<script>top.writeProgress('sedang menulis ke log');</script>";
        $this->load->model("Mdls/" . "MdlActivityLog");
        $hTmp = new MdlActivityLog();
        $tmpHData = array(
            "title" => $_SESSION[$cCode]['main']['jenisTrName'],
            "sub_title" => "Saving followup process",
            "uid" => $this->session->login['id'],
            "uname" => $this->session->login['nama'],
            "dtime" => date("Y-m-d H:i:s"),
            "transaksi_id" => $insertID,
            "deskripsi_old" => "",
            "deskripsi_new" => base64_encode(serialize($_SESSION[$cCode])),
            "jenis" => $this->jenisTr,
            "ipadd" => $_SERVER['REMOTE_ADDR'],
            "devices" => $_SERVER['HTTP_USER_AGENT'],
            "category" => "transaksi",
            "controller" => $this->uri->segment(1),
            "method" => $this->uri->segment(2),
            "url" => current_url(),

        );
        $logID = $hTmp->addData($tmpHData, $hTmp->getTableName()) or die(lgShowError("Gagal menulis riwayat data", __FILE__));
        //endregion


        $endtime = microtime(true); // Bottom of page
        $val = $endtime - $starttime;

//        mati_disini(__FUNCTION__ . "  TRANSAKSI BERHASIL (UNDER MAINTENANCE)  <br> silahkan tutup browser terlebih dahulu. <br>execute in " . $val . " ms");

//        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");

        $pakai_ini = 0;
        if($pakai_ini == 1){
            if (isset($_SESSION[$cCode])) {
                unset($_SESSION[$cCode]);
            }

            if (isset($_SESSION["_TR_" . $origJenis])) {
                unset($_SESSION["_TR_" . $origJenis]);
            }

            if (isset($oldCode)) {
                if (isset($_SESSION[$oldCode])) {
                    unset($_SESSION[$oldCode]);
                }
            }
        }

        return $insertID;
    }

    //followup pakai yang ini cok, versi auto next transaksi
    public function doFollowup_auto($trID, $nextStepNumber, $fromStepNumber)
    {
        $ipadd = $_SERVER['REMOTE_ADDR'];
        $starttime = microtime(true);
        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

        $gmr = img_working();
        echo "\n" . lgWait("doFollowup_auto: Harap menunggu ...., <br>Transaksi sedang diproses <br>halaman akan refresh setelah proses selesai<br>Sangat tergantung seberapa banyak data yang diproses <img src='$gmr'><div class='clearfix'>&nbsp;</div> <div id='h_wadah_human_time_start'></div> <div id='header_wadah_progress'></div> <div id='wadah_progress'></div> <div id='wadah_human_time_start'></div> <div id='wadah_microtime_start'></div>");

        $transaksiID_reference = $no = $trID;
        $stepNum = $nextStepNumber;
        $stepNumCurrent = $fromStepNumber;

        echo "\n<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'] : 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

            $tokoID = $_SESSION[$cCode]['main']['tokoID'];
            $tokoNama = $_SESSION[$cCode]['main']['tokoNama'];
            $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 "\ndetail values ada..<br>";
                    foreach ($detailValuesConfig as $key => $src) {
                        echo "\n$key akan ambil nilai dari $src<br>";
                        if (isset($detailValues[$row->produk_id][$key])) {
                            $items[$row->produk_id][$key] = $detailValues[$row->produk_id][$key];
                        }
                        else {
                            if (isset($row->$key)) {
                                $items[$row->produk_id][$key] = $row->$key;
                            }
                        }
                        echo "\ndan sekarang nilainya: " . $items[$row->produk_id][$key] . "<br>";
                    }
                }
            }
        }
        else {
            $masterID = 0;
            $tmpNomorNota = "XXXX";
            $origJenis = 0;
            $topID = 0;
            die(lgShowAlert("No such receipt ID: $no!"));
        }

        //-------------------------------------------------

        $this->load->library("Transaksional");
        $lt = New Transaksional();
        //-------
        $sessionData[$this->cCode] = $_SESSION[$this->cCode];
        //-------
        $lt->setCCode($this->cCode);
        $lt->setModul($this->modul);
        $lt->setJenisTr($this->jenisTr);
        $lt->setCCodeData($sessionData);
        $lt->setStepNum($stepNum);
        $lt->setStepNumCurrent($stepNumCurrent);
        $lt->setTransaksiNumber($no);
        $lt->setConfigUiModul($this->configUi);
        $lt->setConfigLayoutModul($this->configLayout);
        $lt->setConfigCoreModul($this->configCore);
        $lt->setConfigValuesModul($this->configValues);
        $lt->setConfigCoreMaster($this->config->item('heTransaksi_core'));
        //-------

        //region build table rekening
        if ($runCoreAkunting == true) {
            $lt->buildTableRekening();
        }
        //endregion

        /* ------------------------------
         * TRANSAKSIONAL TERJADI DI DALAM SINI
         * $dieForDebug = false; --------> kondisi normal transaksi bisa lanjot
         * untuk mematikan transksi di jadikan true
         * ------------------------*/
        $dieForDebug = false;
//        $dieForDebug = true;

        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();
//        arrPrintWebs($sessionData[$this->cCode]);

        $libResult = $lt->doFollowup();

        $tmpNomorNota2 = isset($libResult["tmpNomerNota"]) ? $libResult["tmpNomerNota"] : "";
        $tmpTransaksiID = isset($libResult["transaksiId"]) ? $libResult["transaksiId"] : "";
        $tmpTransaksConectingiID = isset($libResult["transaksiIdConnecting"]) ? $libResult["transaksiIdConnecting"] : "";

        //==tampilkan receipt
        cekOrange("-- DONE -- $ipadd");
        if ($dieForDebug === true) {
            cekMerah( json_encode($libResult) );
            mati_disini(__FUNCTION__ . " *** under maintenance ***  <br> TUNGGU SEBENTAR YA... @" . __LINE__);
        }

        //region writelog
        echo "\n<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" => $tmpTransaksConectingiID,
            "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;

//        cekHere("this->jenisTr : " . $this->jenisTr);
//        cekHere("stepNum : " . $stepNum);
//      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!");

        $connectToApk = isset($this->configUi[$this->jenisTr]["steps"][$stepNum]["connectToApk"]) ? $this->configUi[$this->jenisTr]["steps"][$stepNum]["connectToApk"] : array();

        if(!empty($connectToApk)){
            switch($stepNum){
                case "4":
                    $this->load->library("AndroidConnect");
                    $ac = New AndroidConnect();

                    $this->load->model("Mdls/MdlCustomer");
                    $cus = new MdlCustomer();
                    $cus->addFilter("id=".$libResult['sessionData']['main']['customerDetails']);
                    $tmpCus = $cus->lookupAll()->result();

                    if(!empty($tmpCus)){
                        if($tmpCus[0]->va_id*1>0){
                            $this->load->model("Mdls/MdlVirtualAccount");
                            $va = new MdlVirtualAccount();
                            $va->addFilter("id=".$tmpCus[0]->va_id);
                            $tmpVa = $va->lookupAll()->result();
                            if(!empty($tmpVa[0])){
                                switch($tmpVa[0]->folders_nama){
                                    case "BRI":
                                        $this->load->library('briapi');

                                        $url_sandbox        = $tmpVa[0]->url_sandbox;       //from va setting
                                        $url_production     = $tmpVa[0]->url_production;    //from va setting
                                        $endpoint           = $tmpVa[0]->endpoint;          //from va setting
                                        $client_key         = $tmpVa[0]->client_key;        //from va setting
                                        $server_key         = $tmpVa[0]->server_key;        //from va setting
                                        $institutionCode    = $tmpVa[0]->institutionCode;   //(generated from bank) from va setting
                                        $va_kode_from_bank  = $tmpVa[0]->va_kode_from_bank; //(brivaNo generated from bank) from va setting

                                        /*
                                         * SETT VALUE KE Library
                                         */
                                        $this->briapi->clientID         = $client_key;
                                        $this->briapi->clientSecret     = $server_key;
                                        $this->briapi->institutionCode  = $institutionCode;
                                        $this->briapi->brivaNo          = $va_kode_from_bank;

//                                        $this->briapi->endpoint = $endpoint; //masih ikut endpoint pada library

                                        $custCode       = $tmpCus[0]->tlp_1;
                                        $custDataId     = $tmpCus[0]->id;
                                        $custNama       = $tmpCus[0]->nama;
                                        $amount         = $libResult['sessionData']['main']['piutang_dagang'];
                                        $noInvoice      = $libResult['sessionData']['main']['nomer'];
                                        $cust_due_days  = $tmpCus[0]->due_days;

                                        /*
                                         * cek VA sudah terdaftar atau belum
                                         * jika sudah terdaftar maka akan di hapus dulu
                                         * dan akan di daftarkan ulang dibawah
                                         */
                                        $vaCekResult = array();
                                        $this->briapi->custCode = $custCode;
                                        $vaCekResult[$custCode] = $this->briapi->getData();

                                        if($vaCekResult[$custCode]['status']){
                                            //hapus dulu ya
                                            $vaDelResult = array();
                                            $this->briapi->custCode = $custCode;
                                            $vaDelResult[$custCode] = $this->briapi->delete();

                                            if($vaDelResult[$custCode]['status']){
                                                $this->load->model("Mdls/MdlTransaksiVirtualAccount");
                                                $insTrVa = new MdlTransaksiVirtualAccount();
                                                $tmpTrDelData = array(
                                                    "status" => 0,
                                                    "trash" => 1,
                                                    "reason" => "renew tagihan " . $noInvoice . " " . date("Y-m-d H:i:s"),
                                                );
                                                $del = $insTrVa->updateData(array(
                                                    "status"=>1,
                                                    "institutionCode"=>$institutionCode,
                                                    "brivaNo"=>$va_kode_from_bank,
                                                    "custCode"=>$custCode,
                                                ), $tmpTrDelData);
                                            }
                                        }

                                        /*
                                         * daftarkan VA disini
                                         */

                                        $vaResult = array();
                                        $this->briapi->custCode     = $custCode;
                                        $this->briapi->nama         = $custNama;
                                        $this->briapi->amount       = $amount;
                                        $this->briapi->keterangan   = "$noInvoice";
                                        $this->briapi->expiredDate  = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s')."+$cust_due_days days")); //"2021-03-27 23:59:00"; //static
                                        $vaResult[$custCode] = $this->briapi->create();

                                        if($vaResult[$custCode]['status']){
                                            $brivaNo            = $vaResult[$custCode]['data']['brivaNo'];
                                            $custCode           = $vaResult[$custCode]['data']['custCode'];
                                            $institutionCode    = $vaResult[$custCode]['data']['institutionCode'];
                                            $keterangan         = $vaResult[$custCode]['data']['keterangan'];
                                            $expiredDate        = $vaResult[$custCode]['data']['expiredDate'];

                                            $this->load->model("Mdls/MdlTransaksiVirtualAccount");
                                            $cekTrVa = new MdlTransaksiVirtualAccount();
                                            $cekTrVa->addFilter("status=1");
                                            $cekTrVa->addFilter("trash=0");
                                            $cekTrVa->addFilter("customer_id=".$custDataId);
                                            $cekTrVa->addFilter("brivaNo=".$brivaNo);
                                            $cekTrVa->addFilter("custCode=".$custCode);
                                            $cekTrVa->addFilter("institutionCode=".$institutionCode);
                                            $cekTrVa->addFilter("nomer=".$keterangan);

                                            $tmpCekTrVa = $cekTrVa->lookupAll()->result();

                                            if(empty($tmpCekTrVa)){
                                                $insTrVa = new MdlTransaksiVirtualAccount();
                                                $tmpTrVaData = array(
                                                    "nomer" => $keterangan,
                                                    "customer_id" => $custDataId,
                                                    "customer_nama" => $custNama,
                                                    "transaksi_id" => $tmpTransaksiID,
                                                    "tagihan" => $amount,
                                                    "time_insert" => date("Y-m-d H:i:s"),
                                                    "expiredDate" => $expiredDate,
                                                    "brivaNo" => $brivaNo,
                                                    "custCode" => $custCode,
                                                    "institutionCode" => $institutionCode,
                                                    "jenis_va" => "BRI",
                                                );
                                                $insert = $insTrVa->addData($tmpTrVaData, $insTrVa->getTableName());

                                            }
                                        }

                                        break;
                                    case "BCA":
                                        break;
                                    default:
                                        matiHere('bank va tidak di temukan');
                                        break;
                                }
                            }

                            $ac->writeDataCollector($libResult,$tmpTransaksiID,1000); // tetap di kirim tapi pake status 1000 bukan 999 (default 999 agar terbaca di android)
                        }
                        else{
                            /*
                             * default va tidak dibuatkan tagihan di android
                             * jika mau di tagih pake android, harus di send lewat penerimaan
                             */
                            $ac->writeDataCollector($libResult,$tmpTransaksiID);
                        }

                        /*
                         * semua pengiriman akan di kirim ke android
                         * jika penjualan tanpa pengiriman, silahkan dimatikan
                         */
                        $ac->writeDataLogistik($libResult,$tmpTransaksiID);
                    }
                    else{

                        // customer tidak ditemukan...???
                    }




//                    $arrProduk = $libResult['sessionData']['items'];
//                    $this->load->library("Curl");
//                    $curl = New Curl();
//                    $response = array(
//                        "status" => 999,
//                        "toko_id" => $this->session->login['toko_id'],
//                        "nomor_referensi" => $_SESSION[$cCode]['tableIn_master']['nomer'],
//                        "nomer" => $libResult["sessionData"]['main']['nomer'],
//                        "oleh_id" => $this->session->login['id'],
//                        "oleh_nama" => $this->session->login['nama'],
//                        "seller_id" => $_SESSION[$cCode]['main']['logistikInternal'],
//                        "datetime" => date("Y-m-d H:i:s"),
//                        "seller_nama" => $_SESSION[$cCode]['main']['logistikInternal__nama'],
//                        "customer_id" => $_SESSION[$cCode]['main']['customerDetails'],
//                        "customer_nama" => $_SESSION[$cCode]['main']['customerDetails__nama'],
//                        "customer_alamat" => $_SESSION[$cCode]['main']['customerDetails__alamat_1'],
//                        "customer_telp" => $_SESSION[$cCode]['main']['customerDetails__tlp_1'],
//                        "produk_blob" => base64_encode(json_encode($arrProduk)), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agar bisa di urai di javascript
//                    );
//                    $writeDataLogistik = $curl->_simple_call("post", "https://boga.mayagrahakencana.com/run_sakura_apk/eusvc/Entries/writeDataLogistik", $response);

//                    $this->load->library("Curl");
//                    $curl = New Curl();
//                    $response = array(
//                        "status"            => 999,
//                        "toko_id"           => $libResult['sessionData']['main']['tokoID'],
//                        "validGrandTotal"   => $libResult['sessionData']['main']['piutang_dagang'],
//                        "nomor_referensi"   => $libResult['sessionData']['main']['nomer'],
//                        "referensi_id"      => $tmpTransaksiID,
//                        "oleh_id"           => $libResult['sessionData']['main']['olehID'],
//                        "oleh_nama"         => $libResult['sessionData']['main']['olehName'],
//                        "datetime"          => date("Y-m-d H:i:s"),
//                        "customer_id"       => $libResult['sessionData']['main']['customerDetails'],
//                        "customer_nama"     => $libResult['sessionData']['main']['customerDetails__nama'],
//                        "customer_alamat"   => $libResult['sessionData']['main']['customerDetails__alamat_1'],
//                        "customer_telp"     => $libResult['sessionData']['main']['customerDetails__tlp_1'],
//                        "produk_blob"       => base64_encode(json_encode($arrProduk)), //jadikan blob JS ( pake base64_encode(json_encode($produk)) ) agar bisa di urai di javascript
//                    );
//                    $writeDataCollector = $curl->_simple_call("post", "https://boga.mayagrahakencana.com/run_sakura_apk/eusvc/Entries/writeDataCollector", $response);

                    //cek konsumen VA



                break;
            }
        }

// matiHere("stok dulu cek apk ");
// cekMerah("response yang di kirim");
// arrPrintWebs($response);
// cekMerah("stepNum: $stepNum");
// cekMerah("connectToApk");
// arrPrint($connectToApk);
// matiHere("mati dulu cek API");

//        if (isset($_SESSION[$cCode])) {
//            if (isset($_SESSION[$cCode]["main"]["print_barcode"]) && $_SESSION[$cCode]["main"]["print_barcode"] == "1") {
//                echo "<script>";
//                echo "window.open('" . base_url() . "Addons/BarcodePrinter/doPrint/?FromTransaksi=" . $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);
//        }

        $pakai_ini = 0;
        if($pakai_ini == 1){
            if (isset($_SESSION[$cCode])) {
                unset($_SESSION[$cCode]);
            }
            if (isset($_SESSION["_TR_" . $origJenis])) {
                unset($_SESSION["_TR_" . $origJenis]);
            }
            if (isset($oldCode)) {
                if (isset($_SESSION[$oldCode])) {
                    unset($_SESSION[$oldCode]);
                }
            }
        }

        cekHere("stepNum Sekarang: " . $stepNum);

        $arrStep = $this->configUi[$this->jenisTr]['steps'];
        foreach ($arrStep as $step => $spec) {
            $paramStep = "step_$step";
            $paramAutoStep = "auto_step_$step";
            $$paramStep = $step;
            $$paramAutoStep = isset($spec['autoStep']) ? $spec['autoStep'] : 0;
            if($step==$stepNum){
                cekHijau("$paramAutoStep: " . $$paramAutoStep);
                if($$paramAutoStep*1>0 && $arrStep[$step+1]){
                    arrPrintWebs($arrStep[$step+1]);
                    //jalankan auto selanjutnya
                    $return = array(
                        "autostep" => 1,
                        "stepNum" => $stepNum*1,
                        "stepNow" => $step*1,
                        "fromStepNumber" => $stepNum*1,
                        "nextStepNumber" => ($step+1)*1,
                        "transaksi_id" => $tmpTransaksiID*1,
                        "state" => "#1",
                    );
                    return $return;
                }
                else{
                    //tidak menjalankan auto step
                    $return = array(
                        "autostep" => 0,
                        "stepNow" => $step*1,
                        "stepNum" => $stepNum*1,
                        "transaksi_id" => $tmpTransaksiID*1,
                        "state" => "#2",
                    );
                    return $return;
                }
            }
        }
    }
    public function followupPrePreviewAuto($trID, $nextStepNumber, $fromStepNumber)
    {
        $srcIdTr = $no = $trID;
        $stepNum = $stepNumber = $nextStepNumber;
        $currentStepNum = $fromStepNumber;

//        $rawBuilderURL = blobEncode(current_url());
//        $srcIdTr = $no = rtrim($this->uri->segment(5), "-");
//        $stepNum = $stepNumber = $this->uri->segment(6);
//        $currentStepNum = $this->uri->segment(7);

        $rawBuilderURL = url_cleanup(blobEncode(current_url()));
        $cCode = $this->cCode;

        // arrPrint($this->uri->segment_array());
        // matiHere();
        //-------
        $this->load->library("Transaksional");
        $lt = New Transaksional();
        //-------
        $sessionData[$this->cCode] = $_SESSION[$this->cCode];
        //-------
        $lt->setCCode($this->cCode);
        $lt->setModul($this->modul);
        $lt->setJenisTr($this->jenisTr);
        $lt->setCCodeData($sessionData);
        $lt->setStepNum($stepNum);
        $lt->setStepNumCurrent($currentStepNum);
        $lt->setTransaksiNumber($no);
        $lt->setConfigUiModul($this->configUi);
        $lt->setConfigLayoutModul($this->configLayout);
        $lt->setConfigCoreModul($this->configCore);
        $lt->setConfigValuesModul($this->configValues);
        $lt->setConfigCoreMaster($this->config->item('heTransaksi_core'));
        //-------
        $libResult = $lt->followupPrePreview();
        // arrPrint($libResult);
        // matiHere();
        $_SESSION[$cCode] = $libResult["sessionData"];
        //-------

//        $mb = New MobileDetect();
//        $isMob = $mb->isMobile();
//        $mobileSupport = isset($this->configUi[$this->jenisTr]["mobileSupport"]) ? $this->configUi[$this->jenisTr]["mobileSupport"] : false;
//        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>";
    }
    public function save()
    {
        echo "<script>top.writeProgress('MEMULAI PROSES SAVING....');</script>";

        if ($this->transaksiMaintenance === true) {
            $msg = $this->transaksiMaintenanceMsg['title'] . "<br>" . $this->transaksiMaintenanceMsg['mesage'];
            mati_disini($msg);
        }

//        $this->jenisTr = $this->uri->segment(3);
        $cCode = $this->cCode;
        $configUi = $this->configUi;

        $jenisTrTarget = isset($this->configUi[$this->jenisTr]["steps"][1]["target"]) ? $this->configUi[$this->jenisTr]["steps"][1]["target"] : NULL;
        $relOptionConfigs = isset($this->configUi[$this->jenisTr]['relativeOptions']) ? $this->configUi[$this->jenisTr]['relativeOptions'] : array();
        $inputLabels = array();
        $inputAuthConfigs = array();

        $this->load->model("MdlTransaksi");
        $this->load->library("FieldCalculator");
        $cal = new FieldCalculator();

        $rawPrevURL = isset($_GET['rawPrev']) ? $_GET['rawPrev'] : "";
        $prevUrl = blobDecode($rawPrevURL);
        $mongoList = array();
        $mongRegID = array();
        if (isset($_SESSION[$cCode])) {

            if (!isset($_SESSION[$cCode]['items'])) {
                die("belum ada item yang dipilih");
            }
            else {
                if (sizeof($_SESSION[$cCode]['items']) < 1) {
                    die("belum ada item yang dipilih");
                }
            }
            echo("now processing your transaction..<br>");


            //region build table rekening
//            $buildTablesMaster = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'] : array();
//            $buildTablesDetail = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
//            $addMasterTables = array(
//                "rugilaba",
//                "laba ditahan",
//                "rugilaba lain lain",
//            );
//            foreach ($addMasterTables as $trek) {
//                $buildTablesMaster[] = array(
//                    "comName" => "RugiLaba",
//                    "loop" => array(
//                        "$trek" => .0,
//                    ),
//                );
//            }
//            if (sizeof($buildTablesMaster) > 0) {
//                //                arrprint($buildTablesMaster);
//                $bCtr = 0;
//                foreach ($buildTablesMaster as $buildTablesMaster_specs) {
//
//                    $bCtr++;
//                    $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;
//
//                    $this->load->model("Coms/" . $mdlName);
//                    $m = new $mdlName();
//
//
//                    if (isset($buildTablesMaster_specs['loop']) && sizeof($buildTablesMaster_specs['loop']) > 0) {
//                        foreach ($buildTablesMaster_specs['loop'] as $key => $val) {
//                            if (substr($key, 0, 1) == "{") {
//                                $oldParam = $buildTablesMaster_specs['loop'][$key];
//                                cekHere($oldParam);
//                                unset($buildTablesMaster_specs['loop'][$key]);
//                                $key = trim($key, "{");
//                                $key = trim($key, "}");
//                                $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
//                                $buildTablesMaster_specs['loop'][$key] = $oldParam;
//                            }
//                        }
//                    }
//
//
//                    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) {
//                        //arrPrint($itemSpec);
//                        $mdlName = $buildTablesDetail_specs['comName'];
//                        cekLime($mdlName);
//                        if (substr($mdlName, 0, 1) == "{") {
//                            $mdlName = trim($mdlName, "{");
//                            $mdlName = trim($mdlName, "}");
//                            $mdlName = str_replace($mdlName, $itemSpec[$mdlName], $mdlName);
//                            //                        $mdlName = str_replace($mdlName, $_SESSION[$cCode]['main'][$mdlName], $mdlName);
//                        }
//                        $mdlName = "Com" . $mdlName;
//                        cekbiru("model: $mdlName");
//                        $this->load->model("Coms/" . $mdlName);
//                        $m = new $mdlName();
//
//                        if (isset($buildTablesDetail_specs['loop']) && sizeof($buildTablesDetail_specs['loop']) > 0) {
//                            foreach ($buildTablesDetail_specs['loop'] as $key => $val) {
//                                if (substr($key, 0, 1) == "{") {
//                                    $oldParam = $buildTablesDetail_specs['loop'][$key];
//                                    unset($buildTablesDetail_specs['loop'][$key]);
//                                    $key = trim($key, "{");
//                                    $key = trim($key, "}");
//                                    $key = str_replace($key, $itemSpec[$key], $key);
//                                    //                                    $key = str_replace($key, $_SESSION[$cCode]['main'][$key], $key);
//                                    $buildTablesDetail_specs['loop'][$key] = $oldParam;
//                                }
//                            }
//                        }
//                        if (method_exists($m, "getTableNameMaster")) {
//                            if (sizeof($m->getTableNameMaster())) {
//                                $m->buildTables($buildTablesDetail_specs);
//                            }
//                        }
//                    }
//                }
//            }
            //endregion


//            $this->db->trans_start();

//            cekMerah("start pre-processor...");
            //
            //region pre-processors (item)
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['preProc']['detail']) ? $_SESSION[$cCode]['revert']['preProc']['detail'] : array();
                cekMerah(":: iterator preprocc dari gerbang revert ::");
                arrPrintWebs($iterator);
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['detail'] : array();
            }

            if (sizeof($iterator) > 0) {


                $itemNumLabels = isset($this->configUi[$this->jenisTr]['shoppingCartNumFields']) ? $this->configUi[$this->jenisTr]['shoppingCartNumFields'] : array();
                echo "ITEM NUM LABELS";

                if (sizeof($iterator) > 0) {
                    foreach ($iterator as $cCtr => $tComSpec) {
                        $comName = $tComSpec['comName'];
                        $srcGateName = $tComSpec['srcGateName'];
                        $srcRawGateName = $tComSpec['srcRawGateName'];

                        echo "sub-preproc: $comName, initializing values <br>";

                        foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                            $tmpOutParams[$cCtr] = array();

                            //                            $id = $dSpec['id'];
                            $id = $xid;
                            $subParams = array();

                            if (isset($tComSpec['static'])) {
                                foreach ($tComSpec['static'] as $key => $value) {

                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                    $subParams['static'][$key] = $realValue;

                                }

                                if (!isset($subParams['static']["transaksi_id"])) {
                                    //									$subParams['static']["transaksi_id"] = $masterID;
                                }


                                $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'][1]['label'] . " oleh " . $this->session->login['nama'];
                            }
                            //                            cekLime(":: cetak preprocc... $comName :: $srcGateName ::");
                            //                            arrPrint($subParams);
                            //mati_disini();
                            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(0, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                                    $gotParams = $m->exec();

                                    cekmerah("gotparams dari pre-proc $comName");
                                    arrprint($gotParams);


                                    if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor

                                        foreach ($gotParams as $gateName => $paramSpec) {
                                            cekBiru(":: getParams inject ke $gateName ::");
                                            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) {
                                                            cekHere(":: injecte ke $gateName, ::: $key diisi dengan $val");
                                                            $_SESSION[$cCode][$gateName][$id][$key] = $val;
                                                        }

                                                    }
                                                }
                                                //==inject gotParams to child gate
                                                cekHitam("srcGateName = $srcGateName :: " . __LINE__);
                                                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");
                                                        if (isset($_SESSION[$cCode][$gateName][$id][$key])) {
                                                            $_SESSION[$cCode][$gateName][$id]['sub_' . $key] = ($_SESSION[$cCode][$gateName][$id]['jml'] * $_SESSION[$cCode][$gateName][$id][$key]);
                                                        }
                                                    }
                                                }
                                            }
                                            //                                    arrPrint($items);die();
                                        }


                                    }

                                }
                                else {
                                    cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                                }


                            }
                        }
                    }
                }
                else {
                    //cekKuning("sub-preproc is not set");
                }


                $this->load->helper("he_value_builder");
                fillValues_he_value_builder($this->jenisTr, 1, 1, $this->configCoreJenis, $this->configUiJenis);


                //region injector gerbang value untuk pembatalan ppv dan selisih
                if (isset($_SESSION[$cCode]["revert"]["preProc"]["replacer"])) {
                    $replace = $_SESSION[$cCode]["revert"]["preProc"]["replacer"];
                    $jenisTrReference = $_SESSION[$cCode]["main"]["jenisTr_reference"];
                    switch ($jenisTrReference) {
                        case "460":
                            $tempCalculate = array(
                                //                                "selisih" => ($_SESSION[$cCode]["main"]["hpp_riil"] + $_SESSION[$cCode]["main"]["exchange__nilai_tambah_ppn_in"]) - ($_SESSION[$cCode]["main"]["exchange__nilai_tambah_piutang_pembelian"]),
                                //                                "exchange__harga" => $_SESSION[$cCode]["main"]["hpp_riil"],//riil
                                //                                "exchange__hpp_nppv" => $_SESSION[$cCode]["main"]["hpp_nppv"],//riil+ppv
                                //                                "exchange__ppv" => $_SESSION[$cCode]["main"]["ppv_riil"],//riil+ppv
                            );
                            break;
                        default:
                            $tempCalculate = array(
                                "selisih" => ($_SESSION[$cCode]["main"]["hpp"] + $_SESSION[$cCode]["main"]["ppn"]) - ($_SESSION[$cCode]["main"]["nett"] + $_SESSION[$cCode]["main"]["ppv"]),
                                "hpp_nppv" => $_SESSION[$cCode]["main"]["hpp"],
                                "hpp_nppn" => $_SESSION[$cCode]["main"]["hpp"] + $_SESSION[$cCode]["main"]["ppn"],
                            );
                            break;
                    }
                    //                    $tempCalculate = array(
                    //                        "selisih" => ($_SESSION[$cCode]["main"]["hpp"] + $_SESSION[$cCode]["main"]["ppn"]) - ($_SESSION[$cCode]["main"]["nett"] + $_SESSION[$cCode]["main"]["ppv"]),
                    //                        "hpp_nppv" => $_SESSION[$cCode]["main"]["hpp"],
                    //                        "hpp_nppn" => $_SESSION[$cCode]["main"]["hpp"] + $_SESSION[$cCode]["main"]["ppn"],
                    //                    );

                    //arrPrintWebs($tempCalculate);
                    foreach ($replace['recalculate'] as $iKey => $gate) {
                        $_SESSION[$cCode]["main"][$gate] = $tempCalculate[$gate];
                    }

                    cekLime($_SESSION[$cCode]["main"]["hpp"] . "+" . $_SESSION[$cCode]["main"]["ppn"] . "-" . $_SESSION[$cCode]["main"]["nett"]);

                }

                //endregion


            }
            else {
                echo("no processor defined. skipping preprocessor..<br>");
            }
            //endregion


            //region pre-processors (master)
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['preProc']['master']) ? $_SESSION[$cCode]['revert']['preProc']['master'] : array();
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]['master'] : array();
            }

            if (sizeof($iterator) > 0) {

                $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();
                        $switchResultParams = isset($tComSpec['switchResultParams']) ? $tComSpec['switchResultParams'] : false;

                        $subParams = array();

                        if (isset($tComSpec['static'])) {
                            foreach ($tComSpec['static'] as $key => $value) {
                                $realValue = makeValue($value, $_SESSION[$cCode]['main'], $_SESSION[$cCode]['main'], 0);
                                $subParams['static'][$key] = $realValue;

                                //                                cekPink2("$comName == $value || $realValue");
                                //                                cekPink2("valas_harga " . $_SESSION[$cCode]['main']['valas_harga']);
                                //                                cekPink2("uang_muka_valas_harga " . $_SESSION[$cCode]['main']['uang_muka_valas_harga']);
                            }

                            if (!isset($subParams['static']["transaksi_id"])) {
                                //									$subParams['static']["transaksi_id"] = $masterID;
                            }

                            $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'][1]['label'] . " oleh " . $this->session->login['nama'];
                        }
                        $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(0, $tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada pre-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                            $gotParams = $m->exec();

                            cekbiru("gotparams dari pre-proc $comName");
                            arrprint($gotParams);

                            if (sizeof($gotParams) > 0) {//==gotParams means result from preprocessor
                                foreach ($gotParams as $gateName => $gSpec) {
                                    //										$id=$gSpec['id'];

                                    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) {
                                                    $_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;
                                                }
                                            }
                                        }
                                        //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]['main'][$key])) {
                                                    $_SESSION[$cCode]['main']['sub_' . $key] = ($_SESSION[$cCode]['main']['jml'] * $_SESSION[$cCode]['main'][$key]);
                                                }
                                            }
                                        }
                                    }

                                }
                            }
                        }
                        else {
                            cekBiru("sub-komponem $comName tidak memenuhi syarat untuk ditulis");
                        }

                        cekPink2("fillvalue setelah $comName");
                        $this->load->helper("he_value_builder");
                        fillValues_he_value_builder($this->jenisTr, 1, 1, $this->configCoreJenis, $this->configUiJenis);


                    }
                }
                else {
                    //cekKuning("sub-preproc is not set");
                }

                $this->load->helper("he_value_builder");
                fillValues_he_value_builder($this->jenisTr, 1, 1, $this->configCoreJenis, $this->configUiJenis);
            }
            else {
                echo("no processor defined. skipping preprocessor..<br>");
            }
            //endregion


            $this->load->library("Validator");
            $vd = new Validator();
            $vd->setCCode($this->cCode);
            $vd->setConfigUiJenis($this->configUi[$this->jenisTr]);
            $step = $_SESSION[$cCode]['main']['step_number'];
            $vd->midValidate($step);
            $vd->unionValidate();
//            cekOrange("lolos validator @" . __LINE__ . " " . __METHOD__);

            //mati_disini(__LINE__ . "==== ==== ====");
            //===finalisasi sebelum masuk tabel beneran
            //===isinya ada pembentukan nomor nota dll

            //
            //region penomoran receipt
            //<editor-fold desc="==========penomoran">
            $this->load->model("CustomCounter");
            $cn = new CustomCounter("transaksi");
            $cn->setType("transaksi");

            $counterForNumber = array($this->configCore[$this->jenisTr]['formatNota']);
            arrPrintWebs($counterForNumber);
            if (!in_array($counterForNumber[0], $this->configCore[$this->jenisTr]['counters'])) {
                die(__LINE__ . " Used number should be registered in 'counters' config as well");
            }
            echo "<div style='background:#ff7766;'>";
            foreach ($counterForNumber as $i => $cRawParams) {
                $cParams = explode("|", $cRawParams);
                $cValues = array();
                foreach ($cParams as $param) {
                    $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                }
                $cRawValues = implode("|", $cValues[$i]);
                $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

            }
            echo "</div style='background:#ff7766;'>";
            //arrPrintWebs($paramSpec);
            //mati_disini("hahaha");


            $stepNumber = 1;

            $tmpNomorNota = $paramSpec['paramString'];
            $tmpNomorNotaAlias = formatNota("nomer_nolink", $tmpNomorNota);

            if (isset($this->configUi[$this->jenisTr]['steps'][2])) {
                $nextProp = array(
                    "num" => 2,
                    "code" => $this->configUi[$this->jenisTr]['steps'][2]['target'],
                    "label" => $this->configUi[$this->jenisTr]['steps'][2]['label'],
                    "groupID" => $this->configUi[$this->jenisTr]['steps'][2]['userGroup'],
                );
            }
            else {
                $nextProp = array(
                    "num" => 0,
                    "code" => "",
                    "label" => "",
                    "groupID" => "",
                );
            }

            //</editor-fold>
            //endregion
            //
            //region dynamic counters
            // <editor-fold defaultstate="collapsed" desc="==========__init+update dynamic-counters ">
            $cn = new CustomCounter("transaksi");
            $cn->setType("transaksi");
            $configCustomParams = $this->configCore[$this->jenisTr]['counters'];
            $configCustomParams[] = "stepCode";
            //arrPrint($configCustomParams);
            if (sizeof($configCustomParams) > 0) {
                $cContent = array();
                foreach ($configCustomParams as $i => $cRawParams) {
                    $cParams = explode("|", $cRawParams);
                    $cValues = array();
                    foreach ($cParams as $param) {
                        $cValues[$i][$param] = $_SESSION[$cCode]['main'][$param];
                    }
                    $cRawValues = implode("|", $cValues[$i]);
                    $paramSpec = $cn->getNewCount($cParams, $cValues[$i]);

                    $cContent[$cRawParams][$cRawValues] = $paramSpec['value'];
                    switch ($paramSpec['id']) {
                        case 0: //===counter type is new
                            $paramKeyRaw = print_r($cParams, true);
                            $paramValuesRaw = print_r($cValues[$i], true);
                            $cn->writeNewCount($cParams, $cValues[$i], $paramKeyRaw, $paramValuesRaw);
                            break;
                        default: //===counter to be updated
                            $cn->updateCount($paramSpec['id'], $paramSpec['value']);
                            break;
                    }
                    //echo "<hr>";
                }
            }
            $appliedCounters = base64_encode(serialize($cContent));
            $appliedCounters_inText = print_r($cContent, true);
            //mati_disini();

            //
            //region addition on master


            $addValues = array(
                'counters' => $appliedCounters,
                'counters_intext' => $appliedCounters_inText,
                'nomer' => $tmpNomorNota,
                'nomer2' => $tmpNomorNotaAlias,
                'dtime' => date("Y-m-d H:i:s"),
                'fulldate' => date("Y-m-d"),
                "step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                "step_number" => 1,
                "step_current" => 1,
                "next_step_num" => $nextProp['num'],
                "next_step_code" => $nextProp['code'],
                "next_step_label" => $nextProp['label'],
                "next_group_code" => $nextProp['groupID'],
                "tail_number" => 1,
                "tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


            );
            foreach ($addValues as $key => $val) {
                $_SESSION[$cCode]['tableIn_master'][$key] = $val;
            }
            //endregion

            //
            //region addition on detail
            $addSubValues = array(
                "sub_step_number" => 1,
                "sub_step_current" => 1,
                "sub_step_avail" => sizeof($this->configUi[$this->jenisTr]['steps']),
                "next_substep_num" => $nextProp['num'],
                "next_substep_code" => $nextProp['code'],
                "next_substep_label" => $nextProp['label'],
                "next_subgroup_code" => $nextProp['groupID'],
                "sub_tail_number" => 1,
                "sub_tail_code" => $this->configUi[$this->jenisTr]['steps'][1]['target'],


            );
            foreach ($_SESSION[$cCode]['tableIn_detail'] as $id => $dSpec) {
                foreach ($addSubValues as $key => $val) {
                    $_SESSION[$cCode]['tableIn_detail'][$id][$key] = $val;
                }
            }
            //endregion
            // </editor-fold>
            //endregion

            //
            //region ----------write transaksi, transaksi_data, main_fields, main_values, main_applets, etc
            if (isset($_SESSION[$cCode]['tableIn_master']) && sizeof($_SESSION[$cCode]['tableIn_master']) > 0) {

                $_SESSION[$cCode]['tableIn_master']['status_4'] = 11;
                $_SESSION[$cCode]['tableIn_master']['trash_4'] = 0;


                $tr = new MdlTransaksi();
                $tr->addFilter("transaksi.cabang_id='" . $this->session->login['cabang_id'] . "'");
                $insertID = $tr->writeMainEntries($_SESSION[$cCode]['tableIn_master']);
                cekHitam($this->db->last_query());
                $epID = $tr->writeMainEntries_entryPoint($insertID, $insertID, $_SESSION[$cCode]['tableIn_master']);
                $insertNum = $_SESSION[$cCode]['tableIn_master']['nomer'];
                $_SESSION[$cCode]['main']['nomer'] = $insertNum;
                if ($insertID < 1) {
                    die("Gagal saat berusaha  write transaction entry pada " . __FILE__ . " baris " . __LINE__);
                }
                $mongoList['main'] = array($insertID, $epID);
                //==transaksi_id dan nomor nota diinject kan ke gate utama
                $injectors = array(
                    "transaksi_id" => $insertID,
                    "nomer" => $tmpNomorNota,
                    "nomer2" => $tmpNomorNotaAlias,
                );
                $arrInjectorsTarget = array(
                    "items",
                    "items2_sum",
                    "rsltItems",
                );
                foreach ($injectors as $key => $val) {
                    $_SESSION[$cCode]['main'][$key] = $val;
                    foreach ($arrInjectorsTarget as $target) {
                        if (isset($_SESSION[$cCode][$target])) {
                            foreach ($_SESSION[$cCode][$target] as $xid => $iSpec) {
                                $id = isset($iSpec['id']) && $iSpec['id'] > 0 ? $iSpec['id'] : $xid;
                                if (isset($_SESSION[$cCode][$target][$id])) {
                                    $_SESSION[$cCode][$target][$id][$key] = $val;
                                }
                            }
                        }
                    }
                }

                //===signature
                $dwsign = $tr->writeSignature($insertID, array(
                    "nomer" => $_SESSION[$cCode]['main']['nomer'],
                    "step_number" => 1,
                    "step_code" => $this->jenisTr,
                    "step_name" => $this->configUi[$this->jenisTr]['steps'][1]['label'],
                    "group_code" => $this->configUi[$this->jenisTr]['steps'][1]['userGroup'],
                    "oleh_id" => $this->session->login['id'],
                    "oleh_nama" => $this->session->login['nama'],
                    "keterangan" => $this->configUi[$this->jenisTr]['steps'][1]['label'] . " oleh " . $this->session->login['nama'],
                    "transaksi_id" => $insertID,
                )) or die("Failed to write signature");
                $mongoList['sign'][] = $dwsign;
                $idHis = array(
                    $stepNumber => array(
                        "olehID" => $_SESSION[$cCode]['main']['olehID'],
                        "olehName" => $_SESSION[$cCode]['main']['olehName'],
                        "step" => $stepNumber,
                        "trID" => $insertID,
                        "nomer" => $tmpNomorNota,
                        "nomer2" => $tmpNomorNotaAlias,
                        "counters" => $appliedCounters,
                        "counters_intext" => $appliedCounters_inText,
                    ),
                );
                $idHis_blob = blobEncode($idHis);
                $idHis_intext = print_r($idHis, true);
                $tr = new MdlTransaksi();
                $dupState = $tr->updateData(array("id" => $insertID), array(
                    "next_step_num" => $nextProp['num'],
                    "next_step_code" => $nextProp['code'],
                    "next_step_label" => $nextProp['label'],
                    "next_group_code" => $nextProp['groupID'],

                    //===references
                    "id_master" => $insertID,
                    "id_top" => $insertID,
                    "ids_prev" => "",
                    "ids_prev_intext" => "",
                    "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                    "nomers_prev" => "",
                    "nomers_prev_intext" => "",
                    "jenises_prev" => "",
                    "jenises_prev_intext" => "",
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,

                )) or die("Failed to update tr next-state!");
                cekHijau($this->db->last_query());

                $addValues = array(
                    //===references
                    "id_master" => $insertID,
                    "id_top" => $insertID,
                    "ids_prev" => "",
                    "ids_prev_intext" => "",
                    "nomer_top" => $_SESSION[$cCode]['main']['nomer'],
                    "nomers_prev" => "",
                    "nomers_prev_intext" => "",
                    "jenises_prev" => "",
                    "jenises_prev_intext" => "",
                    "ids_his" => $idHis_blob,
                    "ids_his_intext" => $idHis_intext,
                );
                foreach ($addValues as $key => $val) {
                    $_SESSION[$cCode]['tableIn_master'][$key] = $val;
                }

            }
            if (isset($_SESSION[$cCode]['tableIn_master_values']) && sizeof($_SESSION[$cCode]['tableIn_master_values']) > 0) {
                $inserMainValues = array();
                if (isset($this->configCore[$this->jenisTr]['tableIn']['mainValues'])) {
                    //matiHEre("hooppp");
                    $inserMainValues = array();
                    foreach ($this->configCore[$this->jenisTr]['tableIn']['mainValues'] as $key => $src) {
                        if (isset($_SESSION[$cCode]['tableIn_master_values'][$key])) {
                            $dd = $tr->writeMainValues($insertID, array(
                                "key" => $key,
                                "value" => $_SESSION[$cCode]['tableIn_master_values'][$key],
                            ));

                            $inserMainValues[] = $dd;
                            $mongoList['mainValues'][] = $dd;
                        }
                    }
                }

                if (sizeof($inserMainValues) > 0) {
                    $arrBlob = blobEncode($inserMainValues);
                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                }

            }
            if (isset($_SESSION[$cCode]['main_add_values']) && sizeof($_SESSION[$cCode]['main_add_values']) > 0) {
                $inserMainValues = array();
                foreach ($_SESSION[$cCode]['main_add_values'] as $key => $val) {
                    $dd = $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    $inserMainValues[] = $dd;
                    $mongoList['mainValues'][] = $dd;
                }

                if (sizeof($inserMainValues) > 0) {
                    $arrBlob = blobEncode($inserMainValues);
                    $this->db->query("UPDATE transaksi SET indexing_main_values = '$arrBlob' WHERE id=$insertID");
                }
            }
            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                foreach ($_SESSION[$cCode]['main_inputs'] as $key => $val) {
                    $tr->writeMainValues($insertID, array("key" => $key, "value" => $val));
                    //                    cekkuning("making a clone for input key $key / $val");
                    //                    $tmpTableIn=$_SESSION[$cCode]['tableIn_master'];
                    //                    $replacers=array(
                    //                        "nomer"=>$_SESSION[$cCode]['tableIn_master']['nomer']."_$key",
                    //                    );
                    //                    foreach($replacers as $key=>$val){
                    //                        $tmpTableIn[$key]=$val;
                    //                    }
                    //                    $subInputInsertID = $tr->writeMainEntries($tmpTableIn);
                }
            }
            if (isset($_SESSION[$cCode]['main_add_fields']) && sizeof($_SESSION[$cCode]['main_add_fields']) > 0) {
                foreach ($_SESSION[$cCode]['main_add_fields'] as $key => $val) {
                    $tr->writeMainFields($insertID, array("key" => $key, "value" => $val));
                }
            }
            if (isset($_SESSION[$cCode]['main_applets']) && sizeof($_SESSION[$cCode]['main_applets']) > 0) {
                foreach ($_SESSION[$cCode]['main_applets'] as $amdl => $aSpec) {
                    $tr->writeMainApplets($insertID, array(
                        "mdl_name" => $amdl,
                        "key" => $aSpec['key'],
                        "label" => $aSpec['labelValue'],
                        "description" => $aSpec['description'],
                    ));
                }
            }
            if (isset($_SESSION[$cCode]['main_elements']) && sizeof($_SESSION[$cCode]['main_elements']) > 0) {
                foreach ($_SESSION[$cCode]['main_elements'] as $elName => $aSpec) {
                    $tr->writeMainElements($insertID, array(
                        "mdl_name" => isset($aSpec['mdl_name']) ? $aSpec['mdl_name'] : "",
                        "key" => isset($aSpec['key']) ? $aSpec['key'] : 0,
                        "value" => isset($aSpec['value']) ? $aSpec['value'] : "",
                        "name" => $aSpec['name'],
                        "label" => $aSpec['label'],
                        "contents" => isset($aSpec['contents']) ? $aSpec['contents'] : "",
                        "contents_intext" => isset($aSpec['contents_intext']) ? $aSpec['contents_intext'] : "",

                    ));


                    //==nebeng bikin inputLabels
                    $currentValue = "";
                    switch ($aSpec['elementType']) {
                        case "dataModel":
                            $currentValue = $aSpec['key'];
                            break;
                        case "dataField":
                            $currentValue = $aSpec['value'];
                            break;
                    }
                    if (array_key_exists($elName, $relOptionConfigs)) {
                        //					cekhijau("$eName terdaftar pada relInputs");


                        if (isset($relOptionConfigs[$elName][$currentValue])) {
                            if (sizeof($relOptionConfigs[$elName][$currentValue]) > 0) {
                                foreach ($relOptionConfigs[$elName][$currentValue] as $oValueName => $oValSpec) {
                                    $inputLabels[$oValueName] = $oValSpec['label'];
                                    if (isset($oValSpec['auth'])) {
                                        if (isset($oValSpec['auth']['groupID'])) {
                                            $inputAuthConfigs[$oValueName] = $oValSpec['auth']['groupID'];
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            //						cekKuning("option $currentValue pada $eName TIDAK ada pilihannya");
                        }

                    }

                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail']) && sizeof($_SESSION[$cCode]['tableIn_detail']) > 0) {

                $insertIDs = array();
                $insertDeIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail'] as $dSpec) {
                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                    if ($insertDetailID < 1) {
                        die("Gagal saat berusaha write transaction detail entry pada " . __FILE__ . " baris " . __LINE__);
                    }
                    else {
                        $insertIDs[] = $insertDetailID;
                        $insertDeIDs[$insertID][] = $insertDetailID;
                        $mongoList['detail'][] = $insertDetailID;
                    }
                    if ($epID != 999) {
                        $insertEpID = $tr->writeDetailEntries($epID, $dSpec);
                        if ($insertEpID < 1) {
                            die("Gagal saat berusaha write transaction detail entry point pada " . __FILE__ . " baris " . __LINE__);
                        }
                        else {
                            $insertIDs[] = $insertEpID;
                            $insertDeIDs[$epID][] = $insertEpID;
                            $mongoList['detail'][] = $insertEpID;
                        }
                    }
                    cekUngu($this->db->last_query());
                }


                if (sizeof($insertIDs) == 0) {
                    die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
                }
                else {
                    $indexing_details = array();
                    foreach ($insertDeIDs as $key => $numb) {
                        $indexing_details[$key] = $numb;
                    }

                    foreach ($indexing_details as $k => $arrID) {
                        $arrBlob = blobEncode($arrID);
                        $this->db->query("UPDATE transaksi SET indexing_details = '$arrBlob' WHERE id=$k");
                        cekOrange($this->db->last_query());
                    }
                }
            }
            else {
                die(lgShowAlert("Transaksi gagal disimpan karena rincian transaksi kosong."));
            }
            if (isset($_SESSION[$cCode]['tableIn_detail2']) && sizeof($_SESSION[$cCode]['tableIn_detail2']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2'] as $dSpec) {
                    $insertIDs[] = $tr->writeDetailEntries($insertID, $dSpec);
                    $mongoList['detail'] = $insertIDs;
                    if ($epID != 999) {
                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                        $mongoList['detail'] = $insertIDs;
                    }
                    cekUngu($this->db->last_query());
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail2_sum']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail2_sum'] as $dSpec) {
                    $insertDetailID = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $insertDetailID;
                    $mongoList['detail'][] = $insertDetailID;
                    if ($epID != 999) {
                        $dd = $tr->writeDetailEntries($epID, $dSpec);
                        $insertIDs[] = $dd;
                        $mongoList['detail'][] = $dd;
                    }
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) && sizeof($_SESSION[$cCode]['tableIn_detail_rsltItems']) > 0) {
                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail_rsltItems'] as $dSpec) {
                    $dd = $tr->writeDetailEntries($insertID, $dSpec);
                    $insertIDs[] = $dd;
                    $mongoList['detil'][] = $dd;
                    if ($epID != 999) {
                        $insertIDs[] = $tr->writeDetailEntries($epID, $dSpec);
                        $mongoList['detil'] = $insertIDs;
                    }
                    cekUngu($this->db->last_query());
                }
            }
            if (isset($_SESSION[$cCode]['tableIn_detail_values']) && sizeof($_SESSION[$cCode]['tableIn_detail_values']) > 0) {

                $insertIDs = array();
                foreach ($_SESSION[$cCode]['tableIn_detail_values'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues'])) {
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues'] as $key => $src) {
                            if (isset($_SESSION[$cCode]['tableIn_detail'][$pID])) {
                                $dd = $tr->writeDetailValues($insertID, array(
                                    "produk_jenis" => $_SESSION[$cCode]['tableIn_detail'][$pID]['produk_jenis'],
                                    "produk_id" => $pID,
                                    "key" => $key,
                                    "value" => isset($dSpec[$src]) ? $dSpec[$src] : "0",
                                ));
                                $insertIDs[$pID][] = $dd;
                                $mongoList['detailValues'][] = $dd;

                            }
                        }
                    }
                }

                if (sizeof($insertIDs) > 0) {
                    $arrBlob = blobEncode($insertIDs);
                    $this->db->query("UPDATE transaksi SET indexing_detail_values = '$arrBlob' WHERE id=$insertID");
                }

            }
            if (isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) && sizeof($_SESSION[$cCode]['tableIn_detail_values2_sum']) > 0) {
                foreach ($_SESSION[$cCode]['tableIn_detail_values2_sum'] as $pID => $dSpec) {
                    if (isset($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'])) {
                        $insertIDs = array();
                        foreach ($this->configCore[$this->jenisTr]['tableIn']['detailValues2_sum'] as $key => $src) {
                            $dd = $tr->writeDetailValues($insertID, array(
                                "produk_jenis" => $_SESSION[$cCode]['tableIn_detail2_sum'][$pID]['produk_jenis'],
                                "produk_id" => $pID,
                                "key" => $key,
                                "value" => $dSpec[$src],
                            ));
                            $insertIDs[] = $dd;
                            $mongoList['detailValues'][] = $dd;
                        }
                    }
                }
            }
            //endregion


            //===components akan langsung dieksekusi jika steps-nya tidak pakai approval
            $steps = $this->configUi[$this->jenisTr]['steps'];

            //region processing sub-components, if in single step geser ke CLI

            $componentGate['detail'] = array();
            $componentConfig['detail'] = array();
            //            //==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();
            $filterNeeded = false;
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['jurnal']['detail']) ? $_SESSION[$cCode]['revert']['jurnal']['detail'] : array();
                $revertedTarget = $_SESSION[$cCode]['main']['pihakExternID'];
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['detail'] : array();
                $revertedTarget = "";
            }
            $componentConfig['detail'] = $iterator;
            //            //region processing sub-components
            //            if (sizeof($iterator) > 0) {
            //                foreach ($iterator as $cCtr => $tComSpec) {
            //                    $tmpOutParams[$cCtr] = array();
            //                    $gg = 0;
            //                    $srcGateName = $tComSpec['srcGateName'];
            //                    foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
            //                        $srcRawGateName = $tComSpec['srcRawGateName'];
            //                        $comName = $tComSpec['comName'];
            //                        if (substr($comName, 0, 1) == "{") {
            //                            $comName = trim($comName, "{");
            //                            $comName = trim($comName, "}");
            //                            //                            $comName = str_replace($comName, $_SESSION[$cCode]['main'][$comName], $comName);
            //                            cekLime($cCode . " || " . $srcGateName . " || " . $id . " || " . $comName);
            //                            $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
            //                        }
            //                        cekHitam(":: $comName ::");
            //                        $mdlName = "Com" . ucfirst($comName);
            //                        if (in_array($mdlName, $compValidators)) {//perlu validasi filter
            ////cekLime($mdlName. "line");
            //                            $filterNeeded = true;
            //                        }
            //                        else {
            //                            cekLime($mdlName . "like");
            //                            $filterNeeded = false;
            //                        }
            //                        echo "sub-component: $comName, initializing values <br>";
            //                        //                        cekHitam(__LINE__);
            //                        //                        $tmpOutParams[$cCtr] = array();
            //
            //                        //                        cekhitam("$comName filterneeded: $filterNeeded");
            //                        //                        cekhitam("mau mengiterasi $srcGateName");
            //                        //                        cekhitam("telah mengiterasi $srcGateName");
            //                        //
            //                        $subParams = array();
            ////arrPrint($tComSpec);
            //                        if (isset($tComSpec['loop'])) {
            //                            foreach ($tComSpec['loop'] as $key => $value) {
            //                                cekMerah(":: $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][$id][$key], $key);
            //                                }
            //
            //                                $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
            //                                $subParams['loop'][$key] = $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;
            //
            //                            }
            //                            if (!isset($subParams['static']["transaksi_id"])) {
            //                                $subParams['static']["transaksi_id"] = $insertID;
            //                            }
            //                            if (!isset($subParams['static']["transaksi_no"])) {
            //                                $subParams['static']["transaksi_no"] = $insertNum;
            //                            }
            //
            //                            $subParams['static']["fulldate"] = date("Y-m-d");
            //                            $subParams['static']["dtime"] = date("Y-m-d H:i:s");
            //                            $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][1]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
            //                            if (strlen($revertedTarget) > 1) {
            //                                $subParams['static']['reverted_target'] = $revertedTarget;
            //                            }
            //                        }
            //                        //arrPrint($subParams);
            //                        if (sizeof($subParams) > 0) {
            ////                            arrprint($subParams);
            //                            cekhitam("subparam ada isinya");
            //                            if ($filterNeeded) {
            //                                if (isset($subParams['loop']) && sizeof($subParams['loop']) > 0) {
            //                                    $tmpOutParams[$cCtr][] = $subParams;
            //                                }
            //                            }
            //                            else {
            //                                $tmpOutParams[$cCtr][] = $subParams;
            ////                                CekHijiau("asem" .$gg++);
            //                            }
            //                        }
            //                        else {
            //                            cekhitam("subparam TIDAK ada isinya");
            //                        }
            //                    }
            //
            //                    $componentGate['detail'][$cCtr] = $subParams;
            //                }
            //                //cekHitam("cetak tmpOutParams");
            //
            //                foreach ($iterator as $cCtr => $tComSpec) {
            //                    $srcGateName = $tComSpec['srcGateName'];
            //                    foreach ($_SESSION[$cCode][$srcGateName] as $id => $dSpec) {
            //
            //                        $srcRawGateName = $tComSpec['srcRawGateName'];
            //                        $comName = $tComSpec['comName'];
            //                        if (substr($comName, 0, 1) == "{") {
            //                            $comName = trim($comName, "{");
            //                            $comName = trim($comName, "}");
            //                            $comName = str_replace($comName, $_SESSION[$cCode][$srcGateName][$id][$comName], $comName);
            //                            //                        $comName = str_replace($comName, $_SESSION[$cCode]['main'][$comName], $comName);
            //                        }
            //                    }
            //                    echo "sub component: $comName, sending values <br>";
            //
            //                    $mdlName = "Com" . ucfirst($comName);
            //                    $this->load->model("Coms/" . $mdlName);
            //                    $m = new $mdlName();
            //                    //===filter value nol, jika harus difilter
            ////                    arrPrint($tmpOutParams[$cCtr]);
            //                    if (sizeof($tmpOutParams[$cCtr]) > 0) {
            //                        $tobeExecuted = true;
            //                    }
            //                    else {
            //                        $tobeExecuted = false;
            //                    }
            //
            //                    if ($tobeExecuted) {
            //                        cekMerah("$comName dieksekusiii");
            //                        arrPrint($tmpOutParams[$cCtr]);
            //                        $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__);
            //                        cekBiru($this->db->last_query());
            //                    }
            //                    else {
            //                        cekMerah("$comName tidak eksekusi");
            //                    }
            //
            //                }
            //            }
            //            else {
            //                //cekKuning("subcomponents is not set");
            //            }
            //            //endregion

            //endregion

            //region processing main components, if in single step

            $componentGate['master'] = array();
            $componentConfig['master'] = array();
            //==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();
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['jurnal']['master']) ? $_SESSION[$cCode]['revert']['jurnal']['master'] : array();
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['components'][$jenisTrTarget]['master'] : array();
            }

            if (sizeof($iterator) > 0) {
                $componentConfig['master'] = $iterator;
                $cCtr = 0;
                foreach ($iterator as $cCtr => $tComSpec) {
                    $cCtr++;
                    $comName = $tComSpec['comName'];
                    if (substr($comName, 0, 1) == "{") {
                        $comName = trim($comName, "{");
                        $comName = trim($comName, "}");
                        $comName = str_replace($comName, $_SESSION[$cCode]['main'][$comName], $comName);
                    }
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo "component # $cCtr: $comName<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);
                            }

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                            $tmpOutParams['loop'][$key] = $realValue;
                            //                            cekKuning("LOOP $key diisi dengan $realValue");
                        }
                    }
                    if (isset($tComSpec['static'])) {
                        foreach ($tComSpec['static'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                            $tmpOutParams['static'][$key] = $realValue;

                        }
                        if (!isset($tmpOutParams['static']["transaksi_id"])) {
                            $tmpOutParams['static']["transaksi_id"] = $insertID;
                        }
                        if (!isset($tmpOutParams['static']["transaksi_no"])) {
                            $tmpOutParams['static']["transaksi_no"] = $insertNum;
                        }
                        $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'][1]['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($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'];


                    }


                    $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 komponem $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__);
                    }

                    $componentGate['master'][$cCtr] = $tmpOutParams;
                }
            }
            else {
                //cekKuning("components is not set");
            }


            //endregion


            cekHitam(":: START POST PROCC DETAIL... ::");

            //region processing sub-post-processors, always
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['postProc']['detail']) ? $_SESSION[$cCode]['revert']['postProc']['detail'] : array();
                cekHitam("post procc pakai revert");
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['detail'] : array();
                cekHitam("post procc pakai config core");
            }
            if (sizeof($iterator) > 0) {
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo "[$cCtr] sub-postProcessor: $comName, gate: $srcGateName, initializing values <br>";
                    $tmpOutParams[$cCtr] = array();
                    if (isset($_SESSION[$cCode][$srcGateName]) && (sizeof($_SESSION[$cCode][$srcGateName]) > 0)) {
                        arrPrint($_SESSION[$cCode][$srcGateName]);
                        foreach ($_SESSION[$cCode][$srcGateName] as $xid => $dSpec) {
                            //                            $id = $dSpec['id'];
                            $id = $xid;
                            $subParams = array();
                            if (isset($tComSpec['loop'])) {
                                foreach ($tComSpec['loop'] as $key => $value) {

                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                    $subParams['loop'][$key] = $realValue;

                                }
                            }
                            if (isset($tComSpec['static'])) {
                                foreach ($tComSpec['static'] as $key => $value) {
                                    cekHitam("gate: $srcGateName, dengan key $id");
                                    $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName][$id], $_SESSION[$cCode][$srcGateName][$id], 0);
                                    $subParams['static'][$key] = $realValue;

                                }
                                if (!isset($subParams['static']["transaksi_id"])) {
                                    $subParams['static']["transaksi_id"] = $insertID;
                                }
                                if (!isset($subParams['static']["transaksi_no"])) {
                                    $subParams['static']["transaksi_no"] = $insertNum;
                                }
                                $subParams['static']["fulldate"] = date("Y-m-d");
                                $subParams['static']["dtime"] = date("Y-m-d H:i:s");
                                if (isset($_SESSION[$cCode]['revert']['postProc']['detail'])) {
                                    $subParams['static']["reverted_target"] = $_SESSION[$cCode]['main']['pihakExternID'];
                                }

                                $subParams['static']["keterangan"] = $this->configUi[$this->jenisTr]['steps'][1]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];
                            }

                            if (sizeof($subParams) > 0) {
                                $tmpOutParams[$cCtr][] = $subParams;
                            }
                        }
                    }
                }

                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    if (isset($_SESSION[$cCode][$srcGateName])) {
                        echo "[$cCtr] sub-postProcessor: $comName, sending values <br>";

                        $mdlName = "Com" . ucfirst($comName);
                        $this->load->model("Coms/" . $mdlName);
                        //arrPrint($tmpOutParams[$cCtr]);
                        $m = new $mdlName();
                        $m->pair($tmpOutParams[$cCtr]) or die("Tidak berhasil memasang  values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        $m->exec() or die("Gagal saat berusaha  exec values pada post-processor: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                        cekPink($this->db->last_query());
                    }

                }
            }
            //endregion


            //region relesaese connected payment source dan marking trash transaksi
            //            arrPrint($_SESSION[$cCode]["revert"]);
            if (isset($_SESSION[$cCode]["revert"]["connectedPaymentsource"]) && $_SESSION[$cCode]["revert"]["connectedPaymentsource"] == true) {
                $keyRel = $_SESSION[$cCode]["main"]["referenceID"];
                $keyRelRef = $_SESSION[$cCode]["main"]["pihakExternID"];
                $relPaymentSrc = isset($this->config->item("payment_source")[$keyRelRef]) ? $this->config->item("payment_source")[$keyRelRef] : array();
                if (sizeof($relPaymentSrc) > 0) {
                    $this->load->model("Mdls/MdlPaymentSource");
                    $m = new MdlPaymentSource();
                    $m->addFilter("transaksi_id='$keyRel'");
                    $tmpRelPay = $m->lookupAll()->result();
                    $paymentRelUsed = array(
                        "cabang_id" => "placeID",
                        "extern_id" => "id",
                        "extern_nama" => "name",
                        "label" => ".hutang biaya",
                        "target_jenis" => "jenisTr",
                        "transaksi_id" => "refID",
                        "terbayar" => "nilai_bayar",
                        "sisa" => "new_sisa",
                        "ppn" => "valid_ppn",
                        "extern_nilai2" => "valid_dpp",
                    );
                    if (sizeof($tmpRelPay) > 0) {
                        $tmpOutParams = array();
                        $iterator = array();
                        foreach ($tmpRelPay as $indexKey => $relData) {
                            $tmp = array();
                            foreach ($paymentRelUsed as $key => $keyGate) {
                                if ($key == "terbayar") {
                                    $val = $relData->sisa;
                                }
                                else {
                                    if ($key == "sisa") {
                                        $val = "-" . $relData->sisa;
                                    }
                                    else {
                                        $val = $relData->$key;
                                    }
                                }
                                $tmp["static"][$key] = $val;
                                $tmp["static"]["keterangan"] = $this->configUi[$this->jenisTr]['steps'][1]['label'] . " nomor " . $tmpNomorNota . " oleh " . $this->session->login['nama'];

                            }
                            $iterator[$indexKey]["loop"] = array();
                            $iterator[$indexKey]["comName"] = "PaymentSrcItem";
                            if (sizeof($tmp) > 0) {
                                $tmpOutParams[$indexKey][] = $tmp;
                            }
                        }
                        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__);
                            //                            cekHitam($this->db->last_query());
                        }
                    }
                    //                    foreach()
                    cekLime("yuk direset paymentsource**");
                }


            }
            //endregion


            //region processing main-post-processors, always
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {
                $iterator = isset($_SESSION[$cCode]['revert']['postProc']['detail']) ? $_SESSION[$cCode]['revert']['postProc']['master'] : array();
            }
            else {
                $iterator = isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master']) ? $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]['master'] : array();
            }

            if (sizeof($iterator) > 0) {
                foreach ($iterator as $cCtr => $tComSpec) {
                    $comName = $tComSpec['comName'];
                    $srcGateName = $tComSpec['srcGateName'];
                    $srcRawGateName = $tComSpec['srcRawGateName'];
                    echo "post-processor: $comName<br>LINE: " . __LINE__;

                    $dSpec = $_SESSION[$cCode][$srcGateName];
                    $tmpOutParams = array();
                    if (isset($tComSpec['loop'])) {
                        foreach ($tComSpec['loop'] as $key => $value) {

                            $realValue = makeValue($value, $_SESSION[$cCode][$srcGateName], $_SESSION[$cCode][$srcGateName], 0);
                            $tmpOutParams['loop'][$key] = $realValue;

                        }
                    }
                    if (isset($tComSpec['static'])) {
                        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[$this->jenisTr]['steps'][1]['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($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'];


                    }

                    //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__);
                    //cekHitam($this->db->last_query());

                }
            }
            else {

            }
            //endregion

            //cekHijau(":: HALLOOO ::");

            //region updater main transaksi rejection jurnal next step exist
            $mongUpdateList = array();
            if (isset($this->configCore[$this->jenisTr]['relativeComponets']) && $this->configCore[$this->jenisTr]['relativeComponets'] == true) {

                $tr->setFilters(array());
                $tr->addFilter("id='" . $_SESSION[$cCode]["main"]["referenceID"] . "'");
                $tempData = $tr->lookupAll()->result();
                $refMasterID = $tempData[0]->id_master;
                $refMasterJenis = $tempData[0]->jenis_master;
                $nextStepCode = $tempData[0]->next_step_code;
                $mainStepCode = $tempData[0]->jenis;
                $stepnum = $tempData[0]->step_number;
                $stepnumAvail = $tempData[0]->step_avail;
                if (($stepnumAvail - $stepnum) > 0) {
                    //                    matiHere("masukk".$nextStepCode);
                    $this->load->model("Coms/ComTransaksi_jurnal_revert");
                    $r = new ComTransaksi_jurnal_revert();
                    $outParams = array(
                        "refID" => $refMasterID,
                        "main_code" => $mainStepCode,
                        "next_code" => $nextStepCode,
                        "step_num" => $stepnum,
                    );
                    $r->pair($outParams) or die("Tidak berhasil memasang  values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);
                    $r->exec() or die("Gagal saat berusaha  exec values pada komponen: $comName/" . $this->jenisTr . "/" . __FUNCTION__ . "/" . __LINE__);

                    //marking main transaksi trash4
                    $udpate = array(
                        "trash_4" => "1",
                    );
                    $tr->setFilters(array());
                    //                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array(
                        //                "id" => $no,
                        "id" => $_SESSION[$cCode]["main"]["referenceID"],
                    ), $udpate) or die("Failed to update tr next-state!");
                    $mongUpdateList['update']['main'][] = array(
                        "where" => array("id" => $_SESSION[$cCode]["main"]["referenceID"]),
                        "value" => array(
                            "trash_4" => "1",
                        ),
                    );
                    cekHijau("UPDATE transaksi step sebelumnya...");
                    cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    //update validqty 0 supaya gak bisa difollowup
                    //                    $arrData_detail["valid_qty"] = 0;
                    $td = new MdlTransaksi();
                    $td->setFilters(array());
                    $rslt = $td->lookupJoinedByID($_SESSION[$cCode]["main"]["referenceID"])->result();
                    if (sizeof($rslt) > 0) {
                        foreach ($rslt as $rsltSpec) {
                            if (array_key_exists($rsltSpec->produk_id, $_SESSION[$cCode]["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'];
                                //                                }
                                $arrData_detail["valid_qty"] = 0;
                                $tr = new MdlTransaksi();
                                $tr->setFilters(array());
                                $tr->setTableName($tr->getTableNames()['detail']);
                                $dupState = $tr->updateData(array(
                                    "transaksi_id" => $_SESSION[$cCode]["main"]["referenceID"],
                                    "produk_id" => $rsltSpec->produk_id,
                                ), $arrData_detail) or die("Failed to update tr next-state!");
                                $mongUpdateList['update']['detail'][] = array(
                                    "where" => array(
                                        "transaksi_id" => $_SESSION[$cCode]["main"]["referenceID"],
                                        "produk_id" => $rsltSpec->produk_id,
                                    ),
                                    "value" => $arrData_detail,
                                );
                                cekKuning("UPDATE transaksi data...");
                                cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                            }
                        }
                    }

                    $dwsign = $tr->writeSignature($refMasterID, array(
                        "prev_id" => "",
                        "nomer" => "pembatalan jurnal",
                        "step_number" => "-" . $stepnum, // ini minus step number
                        "step_code" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['target'],
                        "step_name" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'],
                        "group_code" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['userGroup'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "keterangan" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'] . " oleh " . $this->session->login['nama'],
                        //            "transaksi_id" => $no,
                    )) or die("Failed to write signature");
                    $mongoList['sign'][] = $dwsign;
                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                    //                    matiHere();
                }
                else {

                    //marking main transaksi trash4
                    $udpate = array(
                        "trash_4" => "1",
                    );
                    $tr->setFilters(array());
                    //                    $tr = new MdlTransaksi();
                    $dupState = $tr->updateData(array(
                        //                "id" => $no,
                        "id" => $_SESSION[$cCode]["main"]["referenceID"],
                    ), $udpate) or die("Failed to update tr next-state!");
                    cekHijau("UPDATE transaksi step sebelumnya...");
                    cekHijau($this->db->last_query() . " [" . $this->db->affected_rows() . "]");
                    $mongUpdateList['update']['main'][] = array(
                        "where" => array("id" => $_SESSION[$cCode]["main"]["referenceID"]),
                        "value" => array(
                            "trash_4" => "1",
                        ),
                    );

                    //update validqty 0 supaya gak bisa difollowup
                    $arrData_detail["valid_qty"] = $new_valid_qty;
                    $td = new MdlTransaksi();
                    $td->setFilters(array());
                    $rslt = $td->lookupJoinedByID($_SESSION[$cCode]["main"]["referenceID"])->result();
                    if (sizeof($rslt) > 0) {
                        foreach ($rslt as $rsltSpec) {
                            if (array_key_exists($rsltSpec->produk_id, $_SESSION[$cCode]["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'];
                                //                                }
                                $arrData_detail["valid_qty"] = 0;
                                $tr = new MdlTransaksi();
                                $tr->setFilters(array());
                                $tr->setTableName($tr->getTableNames()['detail']);
                                $dupState = $tr->updateData(array(
                                    "transaksi_id" => $_SESSION[$cCode]["main"]["referenceID"],
                                    "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() . "]");
                                $mongUpdateList['update']['detail'][] = array(
                                    "where" => array(
                                        "transaksi_id" => $_SESSION[$cCode]["main"]["referenceID"],
                                        "produk_id" => $rsltSpec->produk_id,
                                    ),
                                    "value" => $arrData_detail,
                                );
                            }
                        }
                    }

                    $dwsign = $tr->writeSignature($refMasterID, array(
                        "prev_id" => "",
                        "nomer" => "pembatalan jurnal",
                        "step_number" => "-" . $stepnum, // ini minus step number
                        "step_code" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['target'],
                        "step_name" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'],
                        "group_code" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['userGroup'],
                        "oleh_id" => $this->session->login['id'],
                        "oleh_nama" => $this->session->login['nama'],
                        "keterangan" => $this->configUi[$refMasterJenis]['steps'][abs($stepnum)]['label'] . " oleh " . $this->session->login['nama'],
                        //            "transaksi_id" => $no,
                    )) or die("Failed to write signature");
                    $mongoList['sign'][] = $dwsign;
                    cekKuning($this->db->last_query() . " [" . $this->db->affected_rows() . "]");

                    //                    matiHEre("uhuu");
                }
            }

            //endregion

            // region berlaku pembatalan transaksi bila ada config revertStep di model MdlRevertJurnal (true)
            if (isset($_SESSION[$cCode]['main']['pihakExternRevertStep']) && ($_SESSION[$cCode]['main']['pihakExternRevertStep'] == true)) {
                $referenceNextProp = (isset($_SESSION[$cCode]['main']['referenceNextProp']) && (sizeof($_SESSION[$cCode]['main']['referenceNextProp']) > 0)) ? $_SESSION[$cCode]['main']['referenceNextProp'] : array();
                if (sizeof($referenceNextProp) > 0) {
                    // update transaksi reference, step sebelumnya menjadi aktif lagi
                    $tr = new MdlTransaksi();
                    $tr->setFilters(array());
                    $dupState = $tr->updateData(array("id" => $referenceNextProp['trID']), array(
                        "next_step_code" => $referenceNextProp['code'],
                        "next_step_label" => $referenceNextProp['label'],
                        "next_group_code" => $referenceNextProp['groupID'],
                        "next_step_num" => $referenceNextProp['num'],
                        "step_current" => $referenceNextProp['step_num'],

                    )) or die("Failed to update tr next-state!");
                    cekHijau("BATAL :: " . $this->db->last_query() . " -- " . $this->db->affected_rows());
                    $mongUpdateList['update']['main'][] = array(
                        "where" => array("id" => $referenceNextProp['trID']),
                        "value" => array(
                            "next_step_code" => $referenceNextProp['code'],
                            "next_step_label" => $referenceNextProp['label'],
                            "next_group_code" => $referenceNextProp['groupID'],
                            "next_step_num" => $referenceNextProp['num'],
                            "step_current" => $referenceNextProp['step_num'],
                        ),
                    );


                    // update transaksi data reference, step sebelumnya menjadi aktif lagi
                    $tr = new MdlTransaksi();
                    $tr->setFilters(array());
                    $tr->addFilter("trash='0'");
                    $tr->addFilter("transaksi_id='" . $referenceNextProp['trID'] . "'");
                    $tr->setTableName($tr->getTableNames()['detail']);
                    $detailTmp = $tr->lookupAll()->result();
                    $detailData = array();
                    foreach ($detailTmp as $dTmpSpec) {
                        $detailData[$dTmpSpec->produk_id] = array(
                            "valid_qty" => $dTmpSpec->valid_qty,
                        );
                    }
                    cekOrange($referenceNextProp['detailGate']);
                    if (isset($_SESSION[$cCode][$referenceNextProp['detailGate']]) && ($_SESSION[$cCode][$referenceNextProp['detailGate']] != NULL)) {

                        foreach ($_SESSION[$cCode][$referenceNextProp['detailGate']] as $itemsSpec) {
                            //                        arrPrint($itemsSpec);
                            $valid_qty = isset($detailData[$itemsSpec['id']]['valid_qty']) ? $detailData[$itemsSpec['id']]['valid_qty'] : 0;
                            $valid_qty_new = $valid_qty + $itemsSpec['qty'];

                            $tr = new MdlTransaksi();
                            $tr->setFilters(array());
                            $tr->setTableName($tr->getTableNames()['detail']);
                            $ddupState = $tr->updateData(
                                array(
                                    "transaksi_id" => $referenceNextProp['trID'],
                                    "trash" => 0,
                                    "produk_id" => $itemsSpec['id'],
                                ), array(
                                "next_substep_code" => $referenceNextProp['code'],
                                "next_substep_label" => $referenceNextProp['label'],
                                "next_subgroup_code" => $referenceNextProp['groupID'],
                                "next_substep_num" => $referenceNextProp['num'],
                                "sub_step_current" => $referenceNextProp['step_num'],
                                "valid_qty" => $valid_qty_new,

                            )) or die("Failed to update tr next-state!");
                            cekHijau("BATAL :: " . $this->db->last_query() . " -- " . $this->db->affected_rows());
                            $mongUpdateList['update']['detail'][] = array(
                                "where" => array(
                                    "transaksi_id" => $referenceNextProp['trID'],
                                    "trash" => 0,
                                    "produk_id" => $itemsSpec['id'],
                                ),
                                "value" => array(
                                    "next_substep_code" => $referenceNextProp['code'],
                                    "next_substep_label" => $referenceNextProp['label'],
                                    "next_subgroup_code" => $referenceNextProp['groupID'],
                                    "next_substep_num" => $referenceNextProp['num'],
                                    "sub_step_current" => $referenceNextProp['step_num'],
                                    "valid_qty" => $valid_qty_new,
                                ),
                            );

                        }
                    }
                }
            }
            // endregion


            //
            //region nulis paymentSource
            $stepCode = $this->configUi[$this->jenisTr]['steps'][1]['target'];
            $paymentSources = $this->config->item("payment_source");
            if (array_key_exists($stepCode, $paymentSources)) {

                $payConfigs = $paymentSources[$stepCode];
                if (sizeof($payConfigs) > 0) {
                    foreach ($payConfigs[1] as $paymentSrcConfig) {
                        //					$paymentSrcConfig = $paymentSources[$stepCode];
                        $valueSrc = $paymentSrcConfig['valueSrc'];
                        $externSrc = $paymentSrcConfig['externSrc'];
                        $paymentMethod = isset($paymentSrcConfig['method']) ? $paymentSrcConfig['method'] : "insert";

                        if ($paymentMethod == "update") {
                            $filters = array(
                                "extern_id" => ""
                            );
                            //                            arrPrint($externSrc);
                            $tr->setFilters(array());
                            $tmpData = $tr->lookupPaymentSrcByJenis($paymentSrcConfig['jenisTarget'])->result();
                            if (sizeof($tmpData) > 0) {
                                //sudah ada update aja gak perlu insert
                                $prevID = $tmpData[0]->id;
                                $preValue = $tmpData[0]->sisa;
                                $currValue = isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0;
                                $newValue = $preValue + $currValue;
                                $where = array(
                                    "id" => $prevID,
                                    //                                    "transaksi_id" => $pSpec->transaksi_id,
                                );
                                $data = array(
                                    "tagihan" => $newValue,
                                    "sisa" => $newValue,
                                );
                                $tr->updatePaymentSrc($where, $data);
                                //                                cekHitam($this->db->last_query());
                            }
                            else {
                                //di insert baru
                                $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" => $_SESSION[$cCode]['main']['nomer'],
                                    "label" => $paymentSrcConfig['label'],
                                    "tagihan" => isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0,
                                    "terbayar" => 0,
                                    "sisa" => isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0,
                                    "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']] : 0,
                                    "tagihan_valas" => (isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']])) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : 0,
                                    "terbayar_valas" => (isset($externSrc['valasTerbayar']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTerbayar']])) ? $_SESSION[$cCode]['main'][$externSrc['valasTerbayar']] : 0,
                                    "sisa_valas" => (isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']])) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : 0,
                                    "extern_label2" => (isset($externSrc['extern_label2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_label2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_label2']] : "",
                                    "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : 0,
                                ));
                            }


                        }
                        else {
                            $arrDataPym = 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" => $_SESSION[$cCode]['main']['nomer'],
                                "label" => $paymentSrcConfig['label'],
                                "tagihan" => isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0,
                                "terbayar" => 0,
                                "sisa" => isset($_SESSION[$cCode]['main'][$valueSrc]) ? $_SESSION[$cCode]['main'][$valueSrc] : 0,
                                "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']] : 0,
                                "tagihan_valas" => (isset($externSrc['valasTagihan']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTagihan']])) ? $_SESSION[$cCode]['main'][$externSrc['valasTagihan']] : 0,
                                "terbayar_valas" => (isset($externSrc['valasTerbayar']) && isset($_SESSION[$cCode]['main'][$externSrc['valasTerbayar']])) ? $_SESSION[$cCode]['main'][$externSrc['valasTerbayar']] : 0,
                                "sisa_valas" => (isset($externSrc['valasSisa']) && isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']])) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : 0,
                                "extern_label2" => (isset($externSrc['extern_label2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_label2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_label2']] : "",
                                "extern_nilai2" => (isset($externSrc['extern_nilai2']) && ($_SESSION[$cCode]['main'][$externSrc['extern_nilai2']])) ? $_SESSION[$cCode]['main'][$externSrc['extern_nilai2']] : 0,
                                "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,
                                "extern2_id" => (isset($externSrc['extern2_id']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_id']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_id']] : 0,
                                "extern2_nama" => (isset($externSrc['extern2_nama']) && ($_SESSION[$cCode]['main'][$externSrc['extern2_nama']])) ? $_SESSION[$cCode]['main'][$externSrc['extern2_nama']] : 0,
                            );
                            arrPrintWebs($arrDataPym);
                            $tr->writePaymentSrc($insertID, $arrDataPym);
                        }

                        cekMerah($this->db->last_query());
                    }
                }


            }
            else {
                //cekMerah("TIDAK nulis paymentSrc");
            }
            //endregion


            //
            //region nulis paymentAntiSource
            $stepCode = $this->configUi[$this->jenisTr]['steps'][1]['target'];
            $paymentSources = $this->config->item("payment_antiSource") != null ? $this->config->item("payment_antiSource") : array();
            if (array_key_exists($stepCode, $paymentSources)) {
                cekHitam(":: 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" => $_SESSION[$cCode]['main']['nomer'],
                            "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" => isset($_SESSION[$cCode]['main'][$externSrc['valasTerbayar']]) ? $_SESSION[$cCode]['main'][$externSrc['valasTerbayar']] : '',
                            "sisa_valas" => isset($_SESSION[$cCode]['main'][$externSrc['valasSisa']]) ? $_SESSION[$cCode]['main'][$externSrc['valasSisa']] : '',

                        ));
                        //cekMerah($this->db->last_query());
                    }
                }


            }
            else {
                //cekMerah("TIDAK nulis paymentSrc");
            }
            //endregion


            //====registri value-gate
            if (isset($this->configCore[$this->jenisTr]['components'][$jenisTrTarget]) && sizeof($this->configCore[$this->jenisTr]['components'][$jenisTrTarget])) {
                $jurnalIndex = $this->configCore[$this->jenisTr]['components'][$jenisTrTarget];
            }
            else {
                if (isset($_SESSION[$cCode]["revert"]["jurnal"]) && sizeof($_SESSION[$cCode]["revert"]["jurnal"]) > 0) {
                    $jurnalIndex = $_SESSION[$cCode]["revert"]["jurnal"];
                }
                else {
                    $jurnalIndex = array();
                }
            }
            //---------------------------------------------------
            if (isset($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget]) && sizeof($this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget])) {
                $jurnalPostProc = $this->configCore[$this->jenisTr]['postProcessor'][$jenisTrTarget];
            }
            else {
                if (isset($_SESSION[$cCode]["revert"]["postProc"]) && sizeof($_SESSION[$cCode]["revert"]["postProc"]) > 0) {
                    $jurnalPostProc = $_SESSION[$cCode]["revert"]["postProc"];
                }
                else {
                    $jurnalPostProc = array();
                }
            }
            //---------------------------------------------------
            if (isset($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget]) && sizeof($this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget])) {
                $jurnalPreProc = $this->configCore[$this->jenisTr]['preProcessor'][$jenisTrTarget];
            }
            else {
                if (isset($_SESSION[$cCode]["revert"]["preProc"]) && sizeof($_SESSION[$cCode]["revert"]["preProc"]) > 0) {
                    $jurnalPreProc = $_SESSION[$cCode]["revert"]["preProc"];
                }
                else {
                    $jurnalPreProc = array();
                }
            }
            //---------------------------------------------------


            $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(),
                'rsltItems' => isset($_SESSION[$cCode]['rsltItems']) ? $_SESSION[$cCode]['rsltItems'] : array(),
                'rsltItems2' => isset($_SESSION[$cCode]['rsltItems2']) ? $_SESSION[$cCode]['rsltItems2'] : array(),
                'rsltItems3' => isset($_SESSION[$cCode]['rsltItems3']) ? $_SESSION[$cCode]['rsltItems3'] : array(),
                'tableIn_master' => isset($_SESSION[$cCode]['tableIn_master']) ? $_SESSION[$cCode]['tableIn_master'] : array(),
                'tableIn_detail' => isset($_SESSION[$cCode]['tableIn_detail']) ? $_SESSION[$cCode]['tableIn_detail'] : array(),
                'tableIn_detail2_sum' => isset($_SESSION[$cCode]['tableIn_detail2_sum']) ? $_SESSION[$cCode]['tableIn_detail2_sum'] : array(),
                'tableIn_detail_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems'] : array(),
                'tableIn_detail_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_rsltItems2'] : array(),
                'tableIn_master_values' => isset($_SESSION[$cCode]['tableIn_master_values']) ? $_SESSION[$cCode]['tableIn_master_values'] : array(),
                'tableIn_detail_values' => isset($_SESSION[$cCode]['tableIn_detail_values']) ? $_SESSION[$cCode]['tableIn_detail_values'] : array(),
                'tableIn_detail_values_rsltItems' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems'] : array(),
                'tableIn_detail_values_rsltItems2' => isset($_SESSION[$cCode]['tableIn_detail_values_rsltItems2']) ? $_SESSION[$cCode]['tableIn_detail_values_rsltItems2'] : array(),
                'tableIn_detail_values2_sum' => isset($_SESSION[$cCode]['tableIn_detail_values2_sum']) ? $_SESSION[$cCode]['tableIn_detail_values2_sum'] : array(),
                'main_add_values' => isset($_SESSION[$cCode]['main_add_values']) ? $_SESSION[$cCode]['main_add_values'] : array(),
                'main_add_fields' => isset($_SESSION[$cCode]['main_add_fields']) ? $_SESSION[$cCode]['main_add_fields'] : array(),
                'main_elements' => isset($_SESSION[$cCode]['main_elements']) ? $_SESSION[$cCode]['main_elements'] : array(),
                'main_inputs' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                'main_inputs_orig' => isset($_SESSION[$cCode]['main_inputs']) ? $_SESSION[$cCode]['main_inputs'] : array(),
                "receiptDetailFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields'][1] : array(),
                "receiptSumFields" => isset($this->configLayout[$this->jenisTr]['receiptSumFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields'][1] : array(),
                "receiptDetailFields2" => isset($this->configLayout[$this->jenisTr]['receiptDetailFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailFields2'][1] : array(),
                "receiptDetailSrcFields" => isset($this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1]) ? $this->configLayout[$this->jenisTr]['receiptDetailSrcFields'][1] : array(),
                "receiptSumFields2" => isset($this->configLayout[$this->jenisTr]['receiptSumFields2'][1]) ? $this->configLayout[$this->jenisTr]['receiptSumFields2'][1] : array(),
                "jurnal_index" => $jurnalIndex,
                "postProcessor" => $jurnalPostProc,
                "preProcessor" => $jurnalPreProc,
                "revert" => isset($_SESSION[$cCode]['revert']) ? $_SESSION[$cCode]['revert'] : array(),
                "items_komposisi" => isset($_SESSION[$cCode]['items_komposisi']) ? $_SESSION[$cCode]['items_komposisi'] : array(),
                "items_noapprove" => isset($_SESSION[$cCode]['items_noapprove']) ? $_SESSION[$cCode]['items_noapprove'] : array(),
                "jurnalItems" => isset($_SESSION[$cCode]['jurnalItems']) ? $_SESSION[$cCode]['jurnalItems'] : array(),
                "componentsBuilder" => isset($_SESSION[$cCode]['componentsBuilder']) ? $_SESSION[$cCode]['componentsBuilder'] : array(),
            );
            $doWriteReg = $tr->writeDataRegistries($insertID, $baseRegistries) or die(lgShowError("Ada kesalahan", "Gagal saat berusaha  write base params into registries"));
            $mongRegID = $doWriteReg;
            //            cekHitam($this->db->last_query());

            //========extended steps (if any)
            //region extended steps
            if (isset($_SESSION[$cCode]['main_inputs']) && sizeof($_SESSION[$cCode]['main_inputs']) > 0) {
                foreach ($_SESSION[$cCode]['main_inputs'] as $iKey => $iVal) {
                    if ($iVal > 0) {

                        cekbiru("evaluating $iKey ($iVal) for paymentSrc..");
                        $stepCode = $this->jenisTr . "_";
                        $paymentSources = $this->config->item("payment_source");


                        if (array_key_exists($stepCode, $paymentSources)) {
                            $payConfigs = $paymentSources[$stepCode];
                            cekbiru("$stepCode registered");


                            //===kalau melibatkan payment-source
                            if (sizeof($payConfigs) > 0) {
                                foreach ($payConfigs as $paymentSrcConfig) {
                                    if ($paymentSrcConfig['valueSrc'] == $iKey) {
                                        cekhijau($paymentSrcConfig['valueSrc'] . "/$iKey akan dieksekusi");
                                        $valueSrc = $paymentSrcConfig['valueSrc'];
                                        $externSrc = $paymentSrcConfig['externSrc'];
                                        if ($tr->paymentSrcExistsInMaster($insertID, $stepCode, $paymentSrcConfig['label'])) {
                                            cekhijau($paymentSrcConfig['label'] . " pada $stepCode $insertID sudah ada, tidak perlu ditulis");
                                        }
                                        else {
                                            cekhijau($paymentSrcConfig['label'] . " pada $stepCode $insertID BELUM ada, ditulis sekarang");
                                            $tr->writePaymentSrc($insertID, array(
                                                "_key" => $iKey,
                                                "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" => $_SESSION[$cCode]['main']['nomer'],
                                                "label" => $paymentSrcConfig['label'],
                                                "tagihan" => $_SESSION[$cCode]['main_inputs'][$valueSrc],
                                                "terbayar" => 0,
                                                "sisa" => $_SESSION[$cCode]['main_inputs'][$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("paySrc: ".$this->db->last_query());

                                    }
                                    else {
                                        cekmerah($paymentSrcConfig['valueSrc'] . "/$iKey tidak untuk dieksekusi");
                                    }
                                }
                            }

                        }
                        else {
                            cekbiru("$stepCode NOT registered");
                        }


                        //==periksa apakah mainInput memerlukan auth
                        if (array_key_exists($iKey, $inputAuthConfigs)) {
                            $gID = $inputAuthConfigs[$iKey];
                            if (strlen($gID) > 0) {
                                cekhijau("input $iKey bernilai $iVal memerlukan auth dari $gID");
                                $trA = new MdlTransaksi();
                                if ($trA->extStepExistsInMaster($insertID, $iKey)) {
                                    cekhijau("extStep SUDAH terdaftar, sekarang nggak akan ditulis");
                                }
                                else {
                                    cekhijau("extStep belum terdaftar, sekarang hendak ditulis");
                                    $insertNew = $trA->writeExtStep($insertID, array(
                                        "master_id" => $insertID,
                                        "transaksi_id" => $insertID,
                                        "_key" => $iKey,
                                        "_label" => $inputLabels[$iKey],
                                        "_value" => $iVal,
                                        "group_id" => $gID,
                                        "state" => "0",
                                        "proposed_by" => $this->session->login['id'],
                                        "proposed_dtime" => date("Y-m-d H:i:s"),
                                        "done_by",
                                        "done_dtime",
                                    ));
                                    $mongoList['extras'][] = $insertNew;
                                    cekhijau($this->db->last_query());
                                }
                            }

                        }
                    }

                }
            }
            //endregion


            //==================================================================================================
            //==MENULIS LOCKER TRANSAKSI ACTIVE=================================================================
            // bila step lebih dari 1
            if ($nextProp['num'] > 1) {
                $this->load->model("Mdls/MdlLockerTransaksi");
                $lt = New MdlLockerTransaksi();
                $lt->execLocker($_SESSION[$cCode]['main'], $nextProp['num'], NULL, $insertID);
            }

            //==========================================================================================================

            $masterID = $insertID;




            //region writelog
            $this->load->model("Mdls/" . "MdlActivityLog");
            $hTmp = new MdlActivityLog();
            $tmpHData = array(
                "title" => $_SESSION[$cCode]['main']['jenisTrName'],
                "sub_title" => "Saving new transaction",
                "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


//            cekKuning(":: mulai cek rek besar dan rek pembantu");
//            $cabangID_validate = $this->session->login['cabang_id'];
//            validateBalancesComparison($cabangID_validate, $componentGate, $componentConfig, "master", $insertID, $tmpNomorNota);
//            validateJurnal($insertID, $componentConfig);
//            validateAllBalances();


//            mati_disini("LINE: " . __LINE__ . " under maintenance, tunggu beberapa saat lagi yaa.., TRID: $insertID");

//            $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");

            $pakai_ini = 0;
            if($pakai_ini == 1){
                if (isset($_SESSION[$cCode])) {
                    unset($_SESSION[$cCode]);
                }

                if (isset($oldCode)) {
                    if (isset($_SESSION[$oldCode])) {
                        unset($_SESSION[$oldCode]);
                    }
                }

            }


            return $insertID;
        }
        else {
            die("the gate index you want to debug has not been formed yet!");
        }
    }

    //--------------------
    public function eksekutor()
    {

        $autoValue = $this->uri->segment(8);
        $fromStepNumber = $this->uri->segment(7);
        $nextStepNumber = $this->uri->segment(6);
        $transaksiID = $this->uri->segment(5);
        $arrStep = $this->configUi[$this->jenisTr]['steps'];

//        cekHere("fromStepNumber: " . $fromStepNumber);
//        cekHere("nextStepNumber: " . $nextStepNumber);
//        cekHere("autoValue: " . $autoValue);
//        arrprint($arrStep);

        $arrExcution = array();

        foreach ($arrStep as $step => $spec) {
            $paramStep = "step_$step";
            $paramAutoStep = "auto_step_$step";
            $$paramStep = $step;
            $$paramAutoStep = isset($spec['autoStep']) ? $spec['autoStep'] : 0;

            if($step==$nextStepNumber){
//                cekHijau("$paramAutoStep: " . $$paramAutoStep);
                if($$paramAutoStep*1>0 && $arrStep[$step+1]){
//                    arrPrintWebs($arrStep[$step+1]);
                    //jalankan auto selanjutnya
                    $arrExcution[] = $arrStep[$step+1];
                }
                else{
                    //tidak menjalankan auto step
//                    arrPrint($arrStep);
                    $arrExcution = array();
                }
            }
        }

//        cekHere("arrExcution");
//        arrPrintWebs($arrExcution);

        $this->db->trans_start();

        if(!empty($arrExcution)){
            $this->followupPrePreviewAuto($transaksiID, $nextStepNumber, $fromStepNumber);
            $arrToNextStep = $this->doFollowup_auto($transaksiID, $nextStepNumber, $fromStepNumber);
            if(!empty($arrToNextStep)){
                if($arrToNextStep["autostep"]==1){
                    $transaksiID = $arrToNextStep['transaksi_id'];
                    $nextStepNumber = $arrToNextStep['nextStepNumber'];
                    $fromStepNumber = $arrToNextStep['fromStepNumber'];
                    $this->followupPrePreviewAuto($transaksiID, $nextStepNumber, $fromStepNumber);
                    $this->doFollowup_auto($transaksiID, $nextStepNumber, $fromStepNumber);
                }
            }
            else{
                //tidak ada next step
            }
        }
        else{
            $this->followupPrePreviewAuto($transaksiID, $nextStepNumber, $fromStepNumber);
            $arrToNextStep = $this->doFollowup_auto($transaksiID, $nextStepNumber, $fromStepNumber);
        }

//        mati_disini("MATI DISINI:::: ". __FUNCTION__ . " ::: " . __LINE__);

        $this->db->trans_complete() or die("Gagal saat berusaha  commit transaction!");

        if (isset($_SESSION[$this->cCode])) {
            unset($_SESSION[$this->cCode]);
        }

        $arrAlert = array(
            "type" => "success",
            "title" => "Transaction updated",
            "html" => $this->session->errMsg,
            "timer" => "1500",
            "showConfirmButton" => false,
            "allowOutsideClick" => false,
        );
        echo swalAlert($arrAlert);
        echo topReload();

    }
}
