database))); $lprefix = preg_match('/(lsg\.php|lhk.php)$/', $this->baseURL) ? 'l' : ''; // dump old db -> jsondecode -> get file contents ~/Dropbox/olddb...... [TBD] // get Netsuite_Accounts from SG and HK and merge // // review the "View Financial Report" to see how it's pulling // the Balances for the internal accounting accounts // // // DB_DataObject::debugLevel(1); $db = DB_DataObject::factory('accnt'); $db->selectAdd(); $db->selectAdd("accnt_number, accnt_descrip, currtocurr( baseCurrId(), getcurrid('HKD' ) , COALESCE((SELECT SUM(gltrans_amount) FROM gltrans WHERE gltrans_accnt_id=accnt_id),0), NOW()::date ) as balance"); // $db->whereAdd('accnt_curr_id NOT IN ( 9,6) '); // THB, TWD - not conversion rates avail.. $db->find(); $xdb =array(); while($db->fetch()) { $row = $db->toArray(FALSE, TRUE); $xtd[$row['accnt_number']] = $row; } //ksort($xtd); if ($sd != 'HK') { // we only report on HK data.. echo json_encode($xtd); exit; } $hkdata = $xtd; $xtd = (array) json_decode(file_get_contents("http://localhost/xtuple/{$lprefix}sg.php/Xtuple/VerifyAccounts")); $sgdata = array(); foreach($xtd as $k=> $v) { $sgdata[(int)$k] = $v; } //print_R($sgdata);exit; // echo '
';var_dump( $sgdata );exit;
        // at this point we
        $old = $this->oldParse('HK');
        
        
        foreach($this->oldParse('SG') as $k =>$v) {
            $old[$k] = $v;
        }
        
        
        
        foreach($hkdata as $k=>$v) {
            $k = (int)$k;
            if (isset($old[$k])) {
                continue;
            }
            $v = (object)$v;
            $old[$k] = array(
                'description' => $v->accnt_descrip,
                'id' =>  $v->accnt_number,
                
            );
        }
        foreach($sgdata as $k=>$v) {
            $k = (int)$k;
            if (isset($old[$k])) {
                continue;
            }
            $v = (object)$v;
            $old[$k] = array(
                'description' => $v->accnt_descrip,
                'id' =>  $v->accnt_number,
                 
            );
        }
        //echo '
';
        //var_dump($old);
       //(int) print_r(array_keys($sgdata));
       // print_r(array_keys($old));
        foreach($old as $k=>$xx) {
            
            //var_dump(array($k, $sgdata[(string)$k]));
            
            $old[$k]['hkbalance']  = 0;
            $old[$k]['sgbalance']  = 0;
            if (isset($hkdata[(int)$k])) {
                $v =(object)($hkdata[(int)$k]);
                //print_R($v);
                $old[(int)$k]['hkbalance'] = $v->balance;
            }
            if (isset($sgdata[(string)$k])) {
                //echo "GOT SG? $k
"; $v =(object) ($sgdata[(int)$k]); $old[(int)$k]['sgbalance'] = $v->balance; } } //die("GOT THIS FAR?"); //exit; header('Content-type: text/csv'); header( 'Content-Disposition: attachment;filename=test.csv'); $fh = fopen('php://output','w'); fputcsv($fh, array("ID", "type", "Description", "NETSUITE", "HK", "SG", "difference")); foreach($old as $k=>$ar) { $ar = (object)$ar; $ar->netsuite_balance = isset( $ar->netsuite_balance) ? $ar->netsuite_balance : 0; $ar->acctType = empty($ar->acctType) ? '' : $ar->acctType; if ($ar->acctType == '_expense') { $ar->netsuite_balance = -1 * $ar->netsuite_balance ; } if (!(1 * $ar->netsuite_balance ) && !(1 *$ar->hkbalance) && !(1 * $ar->sgbalance)) { continue; } if ( abs(abs($ar->hkbalance + $ar->sgbalance) - abs($ar->netsuite_balance)) < 100.0) { continue; } fputcsv($fh, array( $ar->id, $ar->acctType, $ar->description, $ar->netsuite_balance, $ar->hkbalance, $ar->sgbalance, abs($ar->hkbalance + $ar->sgbalance) - abs($ar->netsuite_balance))); } exit; // we now have all the data... echo '
';
        print_R($old);
        exit;
        
        
        
        
        
        
        
        
        
        
        
    }
    function oldParse($cn)
    {
        
        
        $har = explode('/', realpath(__FILE__));
        $home = '/home/'. $har[2];
        $fn = "$home/Dropbox/xtuple_working/old_database_snapshot/$cn/Netsuite_Account.sql.json.all";
        $ar = file($fn);
        $ret = array();
        foreach($ar as $i=>$l) {
            if (!$i) continue;
            $line = json_decode($l);
         
            $ret[$line->id] =   array(
                    'id' => $line->id ,
                    'description' => $line->description,
                    'netsuite_balance' => $line->balance,
                    'acctType' => $line->acctType,
                    'is_old' => 1
                );
        }
        return $ret;
         

        
    }
    function addEndOfDay($accnt_id , $data, $bbal, $bal, $last_exchange)
    {
        $ac = DB_DataObject::factory('accnt');
        $ac->get($accnt_id);
        $num = $ac->accnt_number;
        
        
        $sd = strtoupper(substr(HTML_FlexyFramework::get()->database,-2));
        
        $base = $sd == 'SG' ? 'SGD' : 'HKD';
        
        $file = "/home/alan/netsuite_accounts/{$sd}-Account-". $num . '.csv';
        
        $last_exchange = false;
        
        // fill in dragon data..
        
        
        foreach($data as $i=>$row) {
            
            // if the exchange rate changes..
            // then the balance will get adjusted...
            // EG. old rate is 5
            // NEW rate is 10
            // balance = [oldbalance] / 5 * 10
            if ($last_exchange !== false && $last_exchange != $row['gltrans_curr_rate']) {
                $bal = ($bal / $last_exchange) * $row['gltrans_curr_rate'];
            }
            $last_exchange = $row['gltrans_curr_rate'];
            
            
            
            
            $bal += $row['gltrans_amount_normal'];
            $data[$i]['gltrans_balance'] = $bal;
            $bbal += $row['gltrans_base_normal'];
            $data[$i]['gltrans_base_balance'] = $bbal;
            
            
            $data[$i]['gltrans_nsbalance'] = '';
            $data[$i]['gltrans_nsbalance_diff'] = '';
            
            
        }
        
        
        if (!file_exists($file)) {
            //var_dump($file);exit;
            $bal = 0;
            $bbal = 0;
           
             
            return $data;
        }
        // find the end of day totals
         
        
        $fh = fopen($file ,'r');
        if (!$fh) {
            die("failed to open $file\n");
        }
        
        $head = false;
        $daybal = array();
        $daybal_fc = array();
        $last_date = '';
        $last_balance = 0;
        $bal = 0.0;
        
        $fcbal = 0.0;
        $fc = false;
        
        
        $daybal_base = array();
        $basebal = 0.0;
        
        
        
        while (false !== ($row = fgetcsv($fh, 4000))) {
            
            if ($head == false) {
                //if (trim($row[0]) != 'Date') {
                //    continue;
                //}
                
                $head = array();
                foreach($row as $v) {
                    $head[] = trim($v);
                }
                continue;
            }
            
            //echo '
';print_r($head);print_r($row);exit;
           // print_R($head);exit;
            $line = array();
            
            foreach($head as $i=>$k) {
                if ($k == 'Date') {
                    $line[$k] = date('Y-m-d', strtotime(implode('-', array_reverse(explode('/', $row[$i])))));
                    continue;
                }
                if ($k == 'Amount') {
                    $line[$k] =$row[$i];
            
                    continue;
                    
                }
                if (($k == 'Currency') || ($k == 'Amount (Foreign Currency)') || ($k == 'Number') ||  ($k == 'Posting')) {
                    $line[$k] =$row[$i];
                }
                // do not care about other data!?! at present.
                continue;
                
            }
            if ($line['Posting'] == 'No') {
                continue;
            }
            if ($line['Number'] == 'Memorized') {
                continue;
            }
            
            $bal += 1.0*$line['Amount'];
            $line['Balance'] = $bal ; //$neg . preg_replace('#[^0-9.-]#','', $row[$i]);
            
            
           
            
            if ($fc === false) {
                //echo "FC SET TO :". $line['Currency'];
                $fc = $line['Currency'];
            } else if ($fc === '') {
                
            } else if ($fc != $line['Currency']) {
                $fc = '';
            }
             
            $am = preg_replace('/[^0-9.]+/', '', $line['Amount (Foreign Currency)']);
            if ($line['Amount'] < 0) {
                $am *= -1.0;
            }
            
            
            $basebal += $this->currtobase($line['Currency'] , $base, $am , $line['Date']);
            $daybal_base[$line['Date']] = $basebal;
             
            if ($fc) {
                
                $fcbal += $am;
                $daybal_fc[$line['Date']] = $fcbal;
            }
             
            
            if (($last_date != $line['Date']) && !empty($last_date)) {
                $daybal[$last_date] = $last_balance;
                
            }
            $last_balance = $line['Balance'];
            $last_date = $line['Date'];
            
        }
        //echo '
';print_R($daybal); exit;
        // now let's add them to the return values..
        $last_date = '';
        $last_diff = 0;
        $lastbase_balance = 0.0;
        $bal = 0;
        $bbal = 0;
        foreach($data as $i=>$row) {
            
            if (($last_date != $row['gltrans_date']) && !empty($last_date)) {
                 // new day..
                if (!$fc) {
                    $data[$i-1]['gltrans_nsbalance'] = isset($daybal[$last_date]) ? $daybal[$last_date] : 0;
                    $data[$i-1]['gltrans_nsbalance_diff'] = sprintf("%0.2f", $data[$i-1]['gltrans_nsbalance']  - $data[$i-1]['gltrans_balance'] );
                    if ($last_diff != $data[$i-1]['gltrans_nsbalance_diff']) {
                        $bad_days[] = $last_date;
                    }
                    $last_diff = $data[$i-1]['gltrans_nsbalance_diff'];
                } else {
                    $data[$i-1]['gltrans_nsbalance'] = isset($daybal_fc[$last_date]) ? $daybal_fc[$last_date] : 0;
                    $data[$i-1]['gltrans_nsbalance_diff'] = sprintf("%0.2f", $data[$i-1]['gltrans_nsbalance']  - $data[$i-1]['gltrans_balance'] );
                    
                }
                
                $data[$i-1]['gltrans_nsbalance_base'] = isset($daybal_base[$last_date]) ? $daybal_base[$last_date] : $lastbase_balance;
                
                $data[$i-1]['gltrans_nsbalance_base_diff'] = sprintf("%0.2f", $data[$i-1]['gltrans_nsbalance_base']  - $data[$i-1]['gltrans_base_balance'] );
                $lastbase_balance = $data[$i-1]['gltrans_nsbalance_base'];
                
            }
            $last_date =  $row['gltrans_date'];
            
            
            $data[$i]['gltrans_nsbalance'] = '';
            $data[$i]['gltrans_nsbalance_diff'] = '';
             
        }
        return $data;
    /*
        $final = array();
        foreach($data as $row) {
            if (!in_array($row['gltrans_date'], $bad_days)) {
                continue;
            }
            $final[] = $row;
        }
        
        
        
        
        //echo '
';print_R($data); exit;
        return $final;
        */
          
    }
    
    function currtobase($from , $to, $amt , $date)
    {
        if ($from == $to) {
            return $amt;
        }
        $do = DB_DataObject::factory('curr_symbol');
        $do->query("select currtobase(getcurrid('{$from}'), {$amt}, '{$date}') as result");
        $do->fetch();
        return $do->result;
        
        
    }
    
}