=1) { $id_=$row["id"]; //megnezem, hogy mar benne van az adatbazisban vagy sem? $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=2;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } //Alkalmazott adatainak visszateritese function getHrData($id) { $query = "SELECT * FROM `hr` WHERE `id` ='$id' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); return $result; } //Felhasznalo letiltasa function blockUser( $username, $password, $ip) { $query = "UPDATE `users` SET `active`= 0 WHERE `username`='$username' OR `upassword`=PASSWORD('$password') OR `ip`='$ip'"; $result = mysql_query( $query ) or die(mysql_error()); } //load versions function loadVersion() { $now = date('Y-m-d'); $query = "SELECT * FROM `versions` WHERE `date` <= '$now' order by `date` DESC LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); $versionsResult = mysql_fetch_array( $result ); $versions["actual"]["number"] = $versionsResult["version"].'.'.$versionsResult["versionbid"]; $versions["actual"]["update"] = substr($versionsResult["date"],0,10); $version["actual"]["id"] = $versionsResult["id"]; return $versions; } //Verzio kovetes, betolti a valtozasokat (link valtozasok) function loadVersionDifference($date,$linkname) { $query = "SELECT * FROM `versions` WHERE `date` <= '$date' order by `date` DESC LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); $versionsResult = mysql_fetch_array( $result ); $versions[$date]["number"] = $versionsResult["version"].'.'.$versionsResult["versionbid"]; $versions[$date]["update"] = substr($versionsResult["date"],0,10); $version[$date]["id"] = $versionsResult["id"]; $queryItems = "SELECT * FROM `version_items` WHERE `version_id` <= '".$version[$date]["id"]."' and `oldFileLink` = '".$linkname."' order by `date` DESC;"; $resultItems = mysql_query( $queryItems ); $versionsItemsResult = mysql_fetch_array( $resultItems ); $difference=$versionsItemsResult["newFileLink"]; return $difference; } //Beszurja a userHistory tablaba barmilyen tevekenyseget ami a rendszerben van //history functions function insertHistory($userid, $menuNumber, $link, $mod, $showform, $xaction, $observation, $toLook, $toQuest, $ip, $domain,$text="") { $historyQuery = "INSERT INTO `usersHistory` (`datetime` ,`userid` ,`menuNumber` ,`link` ,`mod` ,`showform` ,`xaction` ,`observation` ,`toLook` ,`toQuest` , `ipHistory`, `ipToDomain`,`text`) VALUES (NOW(), '$userid', '$menuNumber', '$link', '$mod', '$showform', '$xaction', '$observation', '$toLook', '$toQuest','$ip','$domain','$text');"; $historyResult = mysql_query($historyQuery) or die(mysql_error()); if($historyResult) return 1; else return 0; } //Megnezzuk van e mgftdgdfgdfai napra valos kurzusunk a currency.managenet.ro rol //currency calculating function mail_nocurrency( $_ip , $params , $propertyCompanyName,$propertyCompanyEmail) { $mail_content=' '.getTraducere("Formular Contact",$_SESSION["settings"]["default_lang"]).'
'; $mail_content.='
'.$plusText.' '.getTraducere("Nu avem curs valid",$_SESSION["settings"]["default_lang"]).'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'.$_ip.'
'; $mail_content.=""; $subject=getTraducere("Problema cu curs valutar",$_SESSION["settings"]["default_lang"]); $fdestemail="office@managenet.ro"; $send_params['recipients'] = array('office@managenet.ro'); // The recipients (can be multiple) $send_params['headers'] = array('Content-type: text/html; charset=iso-8859-1', 'From: '.$propertyCompanyName.' ', // Headers '\nReturn-Path: office@managenet.ro\nContent-Transfer-Encoding: 16bit\nTo: '.$fdestemail, 'Subject: '.$subject,'\nReturn-Path: office@sigma-net.ro\nContent-Transfer-Encoding: 16bit\n'); $send_params['from'] = $propertyCompanyEmail; // This is used as in the MAIL FROM: cmd // It should end up as the Return-Path: header $send_params['body'] = $mail_content; // The body of the email if(is_object($smtp = smtp::connect($params)) AND $smtp->send($send_params)) { $eredmeny=1; }else { $eredmeny=0; } return $eredmeny; } function weHaveCurs($y, $m, $d, $h , $currency,$currencyLink) { $eurValue = GetCurs($y,$m,$d,"EUR",$currencyLink); //sajat currency olvaso $usdValue = GetCurs($y,$m,$d,"USD",$currencyLink); //sajat currency olvaso $dobValue = GetCurs($y,$m,$d,"DOB",$currencyLink); //sajat currency olvaso if($currency=="EUR") return $eurValue; if($currency=="USD") return $usdValue; if($currency=="DOB") return $dobValue; } function GetCurs($y, $m, $d, $currency,$currencyLink) { $link = $currencyLink."?currency=".$currency."&y=".$y."&m=".$m."&d=".$d; $curs = file_get_contents($link); if($curs=='') return -1; return $curs; } function GetAverageCurs($y, $m, $currency,$currencyLink) { $link = $currencyLink."?currency=".$currency."&y=".$y."&m=".$m."&average=1"; $curs = file_get_contents($link); if($curs=='') return -1; return $curs; } function GenerateCurrency($currencyLink) { $y=date("Y"); $m=date("m"); $d=date("d"); $weHaveCursEur = weHaveCurs($y, $m, $d, $h, "EUR",$currencyLink); $weHaveCursUsd = weHaveCurs($y, $m, $d, $h, "USD",$currencyLink); $weHaveCursDob = weHaveCurs($y, $m, $d, $h, "DOB",$currencyLink); $currency["EUR"] = $weHaveCursEur; $currency["USD"] = $weHaveCursUsd; $currency["DOB"]=$weHaveCursDob; $currency["DATE"] = $y.'-'.$m.'-'.$d; $currency["ERROR1"]=$currencyLink."?currency=EUR&y=".$y."&m=".$m."&d=".$d; $currency["ERROR2"]=$currencyLink."?currency=USD&y=".$y."&m=".$m."&d=".$d; return $currency; } function avertizare_notInAvertizare( $id , $type ) { //TODO le kell ellenoriznem az idot is, mert lehet mar benne van a megrendeles, de nem volt leellenorizve, //es kitorolve, es igy nem teszi be //insertTime //tehat mai nap -15 nap kisebb kell legyen mint az inserttime akkor true $nowDate = date("Y-m-d"); $prevTwoWeek = time() - (2 * 7 * 24 * 60 * 59); $fromDateprevTwoWeek = date("Y-m-d",$prevTwoWeek); $query = "SELECT * FROM `avertizare_avertizariItems` WHERE `avertizare_id`='$id' AND `mod_id`='$type' AND `insertTime` > '$fromDateprevTwoWeek' order by `id` DESC"; $result = mysql_query( $query ) or die(mysql_error()); $num = mysql_num_rows( $result ); $row=mysql_fetch_array($result); if($row["remainder"]!=0) { $reminderDate = mktime(0, 0, 0, substr($row["remainderFrom"],5,2) , substr($row["remainderFrom"],8,2)+$row["remainder"], substr($row["remainderFrom"],0,4)); $reminderDate = date("Y-m-d",$reminderDate); $nowDate = date("Y-m-d"); if(subtract_dates($nowDate,$reminderDate)<=0) { return true; } } if( $num ) return false; else return true; } function avertizare_notInAvertizareCar( $id , $type, $typename ) { $nowDate = date("Y-m-d"); $prevTwoWeek = time() - (2 * 7 * 24 * 60 * 59); $fromDateprevTwoWeek = date("Y-m-d",$prevTwoWeek); $today=date("Y-m-d"); $query = "SELECT * FROM `avertizare_avertizariItems` WHERE `avertizare_id`='$id' AND `mod_id`='$type' AND `avertizare_name`='$typename' AND `insertTime` > '$fromDateprevTwoWeek' "; $result = mysql_query( $query ) or die(mysql_error()); $num = mysql_num_rows( $result ); $row=mysql_fetch_array($result); if($row["remainder"]!=0) { $reminderDate = mktime(0, 0, 0, substr($row["remainderFrom"],5,2) , substr($row["remainderFrom"],8,2)+$row["remainder"], substr($row["remainderFrom"],0,4)); $reminderDate = date("Y-m-d",$reminderDate); $nowDate = date("Y-m-d"); if(subtract_dates($nowDate,$reminderDate)<=0) { return true; } } if( $num ) return false; else return true; } function avertizare_addAvertizare( $id , $type , $typename , $mailSettings) { $today = date("Y-m-d"); $now = date("Y-m-d H:i:s"); $query = "INSERT INTO `avertizare_avertizariItems`(`id`, `mod_id`, `avertizare_id`, `avertizare_name`, `current_date`, `insertTime`) VALUES( NULL, '$type', '$id', '$typename', '$today', '$now' ) "; $result = mysql_query( $query ) or die(mysql_error()); $returnId = mysql_insert_id(); avert_emailSending($returnId, $mailSettings); } function avertizare_insertverified( $id, $userid ) { $query="insert into avertizare_avertizariVerificari values(null, $id, $userid, NOW())"; mysql_query( $query ) or die(mysql_error()); } function avertizare_insertrezolvat( $id, $userid ) { $query="UPDATE avertizare_avertizariItems SET `rezolvatDe`='$userid', `rezolvatLaData`=NOW() WHERE `id`='$id' "; mysql_query($query) or die(mysql_error()); } function avertizare_insertremainder( $id, $userid, $rem ) { $today=date("Y-m-d"); $query="UPDATE avertizare_avertizariItems SET `rezolvatDe`='$userid',`remainder`='$rem', `remainderFrom`='$today' WHERE `id`='$id' "; mysql_query( $query ) or die(mysql_error()); } function avertizare_updateControlat($id) { $query="UPDATE avertizare_avertizariItems SET `controlat`=1 WHERE `id`='$id' "; mysql_query($query) or die(mysql_error()); } function avertizare_isVerifiedAvertizari( $id ) { $query="SELECT * FROM avertizare_avertizariVerificari WHERE `averizareItemId`='$id'"; $result = mysql_query($query) or die(mysql_error()); $rows=mysql_num_rows( $result ); if($rows>0) return 1; return 0; } function avertizare_VerifiedAvertizari( $id ) { $query="SELECT * FROM avertizare_avertizariVerificari WHERE `averizareItemId`='$id'"; $result = mysql_query($query) or die(mysql_error()); $rows=mysql_fetch_array( $result ); return $rows; } function avertizare_VerifiedAvertizariUser( $id ) { $query="SELECT * FROM avertizare_avertizariVerificari WHERE `averizareItemId`='$id'"; $result = mysql_query($query) or die(mysql_error()); $rows=mysql_fetch_array( $result ); $user=$rows["userId"]; $query2="SELECT * FROM users WHERE `id`='$user'"; $result2 = mysql_query( $query2 ) or die(mysql_error()); $rows2=mysql_fetch_array( $result2 ); return $rows2; } function avertizare_getAvertizari($page=0,$usrid="",$mod="") { $from = $page * 5; $howmany = 5; $today=date("Y-m-d"); if($_SESSION["user"]["access"]=="administrare"&&($usrid==""||$usrid=="toate")) { $query="SELECT * FROM `avertizare_avertizariItems` WHERE `rezolvatDe`=0"; if($mod!=""&&$mod!="all") $query.=" AND `mod_id`='$mod' "; $query.=" order by id DESC LIMIT $from,$howmany"; } else { if($usrid=="") $usrid=$_SESSION["user"]["id"]; $query="SELECT * FROM `avertizare_avertizariItems` WHERE `rezolvatDe`=0 AND ( CASE `mod_id` WHEN 2 THEN ( `avertizare_id` IN(SELECT `hrid` as idd FROM `contractAngajat` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='2') ) )) WHEN 3 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `facturi` WHERE `userid` = '$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='3') ) )) WHEN 6 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='6') ) )) WHEN 8 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='8') ) )) WHEN 15 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='15') ) )) WHEN 16 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='16') ) )) WHEN 17 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='17') ) )) WHEN 18 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='18') ) )) WHEN 19 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='19') ) )) WHEN 20 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='20') ) )) WHEN 9 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `comandaForClientAdv` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='9') ) )) WHEN 11 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `comandaForClientAdv` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='11') ) )) WHEN 5 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `partners` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='5') ) )) WHEN 14 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `partners` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='14') ) )) WHEN 7 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `fisaZilnicadeLucru` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='7') ) )) WHEN 1 THEN ( `avertizare_id` IN(SELECT `itemid` as idd FROM `stock_items` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='1') ) )) WHEN 10 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `expenses` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='10') ) )) WHEN 12 THEN ( `avertizare_id` IN(SELECT `id` FROM `crm_events` WHERE `asignedTo`= (SELECT `id` FROM `hr` WHERE `userid`= '$usrid') OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='12') ) )) WHEN 13 THEN ( `avertizare_id` IN(SELECT `id` FROM `crm_events` WHERE `asignedTo`= (SELECT `id` FROM `hr` WHERE `userid`= '$usrid') OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='13') ) )) END ) "; if($mod!=""&&$mod!="all") $query.=" AND `mod_id`='$mod' "; $query.=" order by id DESC LIMIT $from,$howmany "; } $result=mysql_query($query) or die(mysql_error()); return $result; } function avertizare_getAvertizare($id) { $query="SELECT * FROM `avertizare_avertizariItems` WHERE `id`='$id'"; $result=mysql_query($query) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } function avertizare_getAvertizariAll($page) { if($page==NULL) $page=0; $from = $page * 15; $howmany = 15; $today=date("Y-m-d"); $query="SELECT * FROM `avertizare_avertizariItems` WHERE `controlat`=0 order by id DESC LIMIT $from,$howmany "; $result=mysql_query($query) or die(mysql_error()); return $result; } function avertizare_getAvertizariNumber($usrid,$mod="") { $today=date("Y-m-d"); if($_SESSION["user"]["access"]=="administrare"&&($usrid==""||$usrid=="toate")) { $query="SELECT * FROM `avertizare_avertizariItems` WHERE `rezolvatDe`=0"; if($mod!=""&&$mod!="all") $query.=" AND `mod_id`='$mod' "; $query.=" order by id DESC"; } else { if($usrid=="") $usrid=$_SESSION["user"]["id"]; $query="SELECT * FROM `avertizare_avertizariItems` WHERE `rezolvatDe`=0 AND ( CASE `mod_id` WHEN 2 THEN ( `avertizare_id` IN(SELECT `hrid` as idd FROM `contractAngajat` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='2') ) )) WHEN 3 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `facturi` WHERE `userid` = '$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='3') ) )) WHEN 6 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='6') ) )) WHEN 8 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='8') ) )) WHEN 15 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='15') ) )) WHEN 16 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='16') ) )) WHEN 17 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='17') ) )) WHEN 18 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='18') ) )) WHEN 19 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='19') ) )) WHEN 20 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='20') ) )) WHEN 9 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `comandaForClientAdv` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='9') ) )) WHEN 11 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `comandaForClientAdv` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='11') ) )) WHEN 5 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `partners` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='5') ) )) WHEN 14 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `partners` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='14') ) )) WHEN 7 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `fisaZilnicadeLucru` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='7') ) )) WHEN 1 THEN ( `avertizare_id` IN(SELECT `itemid` as idd FROM `stock_items` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='1') ) )) WHEN 10 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `expenses` WHERE `userid`='$usrid' OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='10') ) )) WHEN 12 THEN ( `avertizare_id` IN(SELECT `id` FROM `crm_events` WHERE `asignedTo`= (SELECT `id` FROM `hr` WHERE `userid`= '$usrid') OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='12') ) )) WHEN 13 THEN ( `avertizare_id` IN(SELECT `id` FROM `crm_events` WHERE `asignedTo`= (SELECT `id` FROM `hr` WHERE `userid`= '$usrid') OR '$usrid' IN (SELECT `userid` FROM `hr` WHERE `id` IN (SELECT `hrid` FROM `avertizare_hrs` WHERE `mod_id`='13') ) )) END )"; if($mod!=""&&$mod!="all") $query.=" AND `mod_id`='$mod' "; $query.=" order by id DESC"; } $result=mysql_query($query) or die(mysql_error()); return mysql_num_rows($result); } function query_countQueryResults( $query ) { $newQuery = str_replace( "*" , "COUNT(*) as rowCount" , $query ); $limitIndex = strpos( $newQuery , "LIMIT" ); $newQuery = substr( $newQuery , 0 , $limitIndex ); $result = mysql_query( $newQuery ); if($result); return mysql_result( $result , 0 , 0 ); } function avertizare_getAvertizareData($id, $mod_id) { if($mod_id==1) $query = "SELECT * FROM `container` WHERE `id`='$id'"; if($mod_id==2) $query = "SELECT distinct ca.perioada, ca.id, h.forname, h.lastname, h.cnp FROM `contractAngajat` ca, `hr` h where h.id=ca.hrid AND `ca`.`id`='$id';"; if($mod_id==3) $query="SELECT * FROM `facturi` WHERE `id`='$id'"; if($mod_id==5) $query="SELECT * FROM `partners` WHERE `id`='$id'"; if($mod_id==6 || $mod_id==8 || $mod_id==15 || $mod_id==16 || $mod_id==17 || $mod_id==18 || $mod_id==19 || $mod_id==20) $query="SELECT * FROM `cars` WHERE `id`='$id'"; if($mod_id==7) $query="SELECT * FROM `fisaZilnicadeLucru` WHERE `id`='$id'"; if($mod_id==9) { $query="SELECT `c`.userid, `c`.id as comandaId, `c`.secondserial as comandasecondserial, `c`.clientid as comandaClientId, `ci`.*, `f`.*, `fi`.`factid`,`fi`.endDate as facturaendDate FROM `comandaForClientAdv` c, `comandaForClientAdvItems` ci, `facturi` f, `facturi_items` fi WHERE `c`.`id`='$id' AND `c`.`id` = `ci`.`comandaid` AND `c`.`id`=`f`.`fromActAdvId` AND `fi`.`factid`=`f`.`id` ORDER BY `fi`.endDate DESC LIMIT 0 , 1"; $testResult=mysql_query( $query ) or die(mysql_error()); $testRow=mysql_fetch_array($testResult); if(mysql_num_rows($testResult)==0) $query="SELECT `c`.userid, `c`.id as comandaId, `c`.secondserial as comandasecondserial, `c`.clientid as comandaClientId, `ci`.`id`, `ci`.`comandaid`, `ci`.`startDate` as comandaStartDate FROM `comandaForClientAdv` c, `comandaForClientAdvItems` ci WHERE `c`.`id`='$id' AND `c`.`id` = `ci`.`comandaid` GROUP BY `c`.`id`"; } if($mod_id==10) $query="SELECT * FROM `expenses` WHERE `id`='$id'"; if($mod_id==11) { $query="SELECT `c`.userid,`c`.id as comandaId, `c`.secondserial as comandasecondserial, `c`.clientid as comandaClientId, `ci`.*, `f`.*, `fi`.`factid`,`fi`.endDate as facturaendDate FROM `comandaForClientAdv` c, `comandaForClientAdvItems` ci, `facturi` f, `facturi_items` fi WHERE `c`.`id`='$id' AND `c`.`id` = `ci`.`comandaid` AND `c`.`id`=`f`.`fromActAdvId` AND `fi`.`factid`=`f`.`id` ORDER BY `fi`.endDate DESC LIMIT 0 , 1"; $testResult=mysql_query( $query ) or die(mysql_error()); $testRow=mysql_fetch_array($testResult); if(mysql_num_rows($testResult)==0) $query="SELECT `c`.userid,`c`.id as comandaId, `c`.secondserial as comandasecondserial, `c`.clientid as comandaClientId, `ci`.`id`, `ci`.`comandaid`, `ci`.`startDate` as comandaStartDate FROM `comandaForClientAdv` c, `comandaForClientAdvItems` ci WHERE `c`.`id`='$id' AND `c`.`id` = `ci`.`comandaid` GROUP BY `c`.`id`"; } if($mod_id==12) $query="SELECT * FROM `crm_events` WHERE `id`='$id'"; if($mod_id==13) $query="SELECT * FROM `crm_events` WHERE `id`='$id'"; if($mod_id==14) $query="SELECT * FROM `partners` WHERE `id`='$id'"; $result=mysql_query($query) or die(mysql_error()); if($result) $row=mysql_fetch_array($result); return $row; } //exist functions function model_modelExists( $name ) { $query = "SELECT * FROM `models` WHERE `name`='$name' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows(); } function model_modelCsExists( $csName ) { $query = "SELECT * FROM `models_cs` WHERE `name`='$csName' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows(); } function model_modelCsValueExists( $modelCsId , $csValName) { $query = "SELECT * FROM `models_cs_values` WHERE `name`='$csValName' AND `modelcsid`='$modelCsId' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows(); } //create delete rename functions function model_createModel( $name ) { if( model_modelExists( $name ) == 0 ) { $query = "INSERT INTO `models` ( `id` , `name` ,`ondate`) VALUES (NULL , '$name',NOW());"; mysql_query( $query ) or die(mysql_error()); $_SESSION["msg_stat"] = "Model ".$name."created !"; return true; } else $_SESSION["msg_err"] = getTraducere("Model name already exists",$_SESSION["settings"]["default_lang"])." !"; return false; } function model_renameModel( $id , $newname ) { if( model_modelExists( $newname ) == 0 ) { $query = "UPDATE `models` SET `name`='$newname' WHERE `id`='$id' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); $_SESSION["msg_stat"] = "Model renamed to ".$newname."!"; return true; } else $_SESSION["msg_err"] = getTraducere("Model name already exists",$_SESSION["settings"]["default_lang"])." !"; return false; } function model_renameModelCs( $id , $oldname , $newname , $newtype ) { if( model_modelCsExists( $newname ) == 0 || $oldname == $newname ) { $query = "UPDATE `models_cs` SET `name`='$newname' , `type`='$newtype' WHERE `id`='$id' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); $_SESSION["msg_stat"] = "Model Cs renamed to ".$newname."!"; return true; } else $_SESSION["msg_err"] = getTraducere("Model Cs name already exists",$_SESSION["settings"]["default_lang"])." !"; return false; } function model_createModelCs( $csName , $csType , $lang='') { if( model_modelCsExists( $csName ) == 0 ) { $query = "INSERT INTO `models_cs` ( `id` , `name` , `type`, `lang` ) VALUES ( NULL , '$csName', '$csType', '$lang');"; $result = mysql_query( $query ) or die(mysql_error()); $_SESSION["msg_stat"] = "Model CS ".$csName."created !"; return mysql_insert_id(); } else $_SESSION["msg_err"] = getTraducere("Model CS name already exists",$_SESSION["settings"]["default_lang"])." !"; return -1; } function model_createModelCsValue( $modelCsId , $csVal ) { if( model_modelCsValueExists( $modelCsId , $csVal ) == 0 ) { $query = "INSERT INTO `models_cs_values` ( `id` , `modelcsid` , `name` ) VALUES ( NULL , '$modelCsId', '$csVal' );"; $result = mysql_query( $query ) or die(mysql_error()); $_SESSION["msg_stat"] = "Model CS Value ".$csVal."created !"; return true; } else $_SESSION["msg_err"] = getTraducere("Model CS Value name already exists",$_SESSION["settings"]["default_lang"])." !"; return false; } function model_deleteModel($modelId ) { $query = "DELETE FROM `models` WHERE `id`='$modelId' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } function model_deleteModelCs( $modelCsId ) { $csValues = model_getModelCsValues( $modelCsId ); if( $csValues ) foreach( $csValues as $key => $value ) { model_deleteModelCsValue( $modelCsId , $value["name"] ); } $query = "DELETE FROM `models_cs` WHERE `id`='$modelCsId' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } function model_deleteModelCsValue( $modelCsId , $csVal ) { $query = "DELETE FROM `models_cs_values` WHERE `modelcsid`='$modelCsId' AND `name`='$csVal' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } //get functions function model_getModel( $modelId ) { $query = "SELECT * FROM `models` WHERE `id`='$modelId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $model = mysql_fetch_array( $result ); $model["cs"] = model_getAssignedCss( $model ); return $model; } function model_getModel2( $modelId ) { $query = "SELECT * FROM `models` WHERE `id`='$modelId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $model = mysql_fetch_array( $result ); $model["cs"] = model_getAssignedCss2( $model ); return $model; } function modifyModel($modelid,$name,$desc,$cs){ if (count($cs)>0){ $query="UPDATE `models` set `name`='$name',`description`='$desc',"; for($i=1;$i<21;$i++){ if (isset($cs[$i])) $query.="`cs$i`='$cs[$i]',"; else $query.="`cs$i`=NULL,"; } $query=substr($query,0,strlen($query)-1); $query.=" WHERE `id`='$modelid'"; return mysql_query($query) or die($query."
".mysql_error()); } return null; } function models_insert_subcat($modelId,$modelcs_id,$v,$k,$lang, $aktive,$type,$id){ if ($k!='new'){ $query="UPDATE `models_subcat` set `value`='$v', `active`='$aktive',`type`='$type' WHERE `id`='$id'"; return mysql_query($query) or die ($query."
".mysql_error()); }else{ $query="INSERT INTO `models_subcat` (`modelid`,`modelcs_id`,`lang`,`value`,`ondate`,`active`,`type`) VALUES ('$modelId','$modelcs_id','$lang','$v',NOW(),'$aktive','$type')"; return mysql_query($query) or die ($query."
".mysql_error()); } } function models_get_subcat($modelid,$modelcs_id){ $query="SELECT * FROM `models_subcat` WHERE `modelid`='$modelid' AND `modelcs_id`='$modelcs_id'"; $result=mysql_query($query) or die($query."
".mysql_error()); $lista=array(); while($row=mysql_fetch_array($result)){ $lista[]=$row; } return $lista; } function models_get_subcatById($id){ $query="SELECT * FROM `models_subcat` WHERE `id`='$id'"; $result=mysql_query($query) or die($query."
".mysql_error()); return mysql_fetch_array($result); } function models_delete_subcat($modelId,$modelcs_id,$language){ $query="DELETE FROM `models_subcat` WHERE `modelid`='$modelId' AND `modelcs_id`='$modelcs_id' AND `lang`='$language'"; $result=mysql_query($query) or die($query."
".mysql_error()); } function models_delete_subcatById($id){ $query="DELETE FROM `models_subcat` WHERE `id`='$id'"; $result=mysql_query($query) or die($query."
".mysql_error()); } function entry_delete_propertiesBySubcatId($subcatid){ $query="DELETE FROM `container_rel` WHERE `prop_id` IN (SELECT `id` FROM `container_properties` WHERE `model_subcat_id`='$subcatid')"; $result=mysql_query($query) or die($query."
".mysql_error()); $query="DELETE FROM `container_properties` WHERE `model_subcat_id`='$subcatid'"; $result=mysql_query($query) or die($query."
".mysql_error()); } function getModelCsByModelid($modelid,$lang){ $q="select * from `models` where `id`='$modelid'"; $result=mysql_query($q) or die ($q."
".mysql_error()); if (mysql_affected_rows()>0){ $row=mysql_fetch_array($result); $array='('; for ($i=1;$i<21;$i++) if ($row['cs'.$i]!=null) $array.=$row['cs'.$i].','; if ($array!='(') $array=substr($array,0,strlen($array)-1).")"; else $array.="'0')"; $query = "SELECT * FROM `models_cs` WHERE `lang`='$lang' AND `id` NOT IN $array"; $result = mysql_query( $query ) or die($query."
".mysql_error()); $lista=array(); while ( $row = mysql_fetch_array( $result )){ $lista[$row['id']]=$row; } return $lista; }else return null; } function getModelCsByLang($lang){ $query = "SELECT * FROM `models_cs` WHERE `lang`='$lang' "; $result = mysql_query( $query ) or die($query."
".mysql_error()); $lista=array(); while ( $row = mysql_fetch_array( $result )){ $lista[$row['id']]=$row; } return $lista; } function model_getModelCs( $modelCsId ) { $query = "SELECT * FROM `models_cs` WHERE `id`='$modelCsId'"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $modelCs = mysql_fetch_array( $result ); return $modelCs; } function model_getModels($viewall,$userid) { if($viewall!="1") { $viewquery= " WHERE (`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid')))) "; } $query = "SELECT * FROM `models`".$viewquery." ORDER BY `id`"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $models[ $row["id"] ] = $row; return $models; } function model_getModelCssName($cssid, $modelid) { $query = "SELECT * FROM `models_cs_values` WHERE `modelcsid`='$modelid' AND `id`='$cssid'"; $result = mysql_query( $query ) or die(mysql_error()); $modelCs = mysql_fetch_array( $result ); return $modelCs; } function model_getModelCss() { $query = "SELECT * FROM `models_cs`"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCss[ $row["id"] ] = $row; return $modelCss; } function model_getModelCsstype() { $query = "SELECT * FROM `models_cs` WHERE `type`='2'"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCss[ $row["id"] ] = $row; return $modelCss; } function model_getModelCsValues( $modelCs ) { $query = "SELECT * FROM `models_cs_values` WHERE `modelcsid`='$modelCs' ORDER BY `name` "; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCsValues[ $row["id"] ] = $row; return $modelCsValues; } function model_getModelCsValueName( $modelCsId ) { $query = "SELECT * FROM `models_cs_values` WHERE `id`='$modelCsId'"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCsValues[ $row["id"] ] = $row; return $modelCsValues; } function model_getModelCsValueName2( $modelCsId ) { $query = "SELECT * FROM `models_cs_values` WHERE `modelcsid`='$modelCsId'"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCsValues[ $row["id"] ] = $row; return $modelCsValues; } function model_assignCs( $modelId , $modelCsId ) { for( $i = 1 ; $i <= 20 ; $i ++ ) { $query = "SELECT `cs$i` FROM `models` WHERE `id`='$modelId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); $model = mysql_fetch_array( $result ); if( $model["cs".$i] == $modelCsId )return false; if( $model["cs".$i] == NULL )break; } $query = "UPDATE `models` SET `cs$i`='$modelCsId' WHERE `id`='$modelId' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } function model_unAssignCs( $modelId , $csIndex ) { $shiftPart = ""; for( $i = $csIndex ; $i < 20 ; $i++ ) $shiftPart .= "`cs$i` = `cs".($i+1)."`,"; $shiftPart[ strlen( $shiftPart ) - 1 ] = ' '; $shiftQuery = "UPDATE `models` SET".$shiftPart." WHERE `id`='$modelId' LIMIT 1;"; mysql_query( $shiftQuery ) or die(mysql_error()); entry_modiyEntrySturcture( $modelId , $csIndex ); } function model_getAssignedCss( $modelData ) { for( $i = 1 ; $i <= 20 ; $i ++ ) { if( $modelData["cs".$i] == NULL )break; $cs[ $modelData["cs".$i] ] = $modelData["cs".$i]; } return $cs; } function model_getAssignedCss2( $modelData ) { for( $i = 1 ; $i <= 20 ; $i ++ ) { if( $modelData["cs".$i] == NULL )break; $cs[ $i ] = $modelData["cs".$i]; } return $cs; } function getTableColumns( $tableName ) { $query = "SHOW COLUMNS FROM $tableName"; $result = mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) { $fields[ $row["Field"] ] = $row["Field"]; } return $fields; } function events_getServiceEventByDate($date) { $query="SELECT * FROM `events` WHERE `kat`=5 AND `date` BETWEEN '$date' AND '$date'"; $result=mysql_query( $query ) or die($query." ".mysql_error()); if($result) $row=mysql_fetch_array($result); return $row; } function events_updateEventList( $eventid, $commandid, $serviceid, $servicename ) { $query="UPDATE `eventsList` SET `commandid`='$commandid',`serviceid`='$serviceid',`servicename`='$servicename' WHERE `eventid`='$eventid'"; $result=mysql_query( $query ) or die(mysql_error()); return $result; } function events_addServiceEvent( $date ) { $user=$_SESSION["user"]["id"]; $query="INSERT INTO `events` VALUES(NULL,'Service','$date','','$user',5)"; $result=mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function events_addEventList( $eventid,$commandid, $serviceid, $servicename ) { $query="INSERT INTO `eventsList` VALUES(NULL,'$eventid','$commandid','$serviceid','$servicename')"; $result=mysql_query( $query ) or die(mysql_error()); return $result; } // Kivesszuk a kulcsszavakat egy termekbol function entry_getKeywords ($prodid) { $query="SELECT * FROM `keywords` WHERE `prodid` =".$prodid; $add=mysql_query( $query ) or die(mysql_error()); if ($add) { while ($listAll=mysql_fetch_array($add)) { $result[$listAll["id"]]=$listAll; } } return $result; } function entry_getProductPropertieValue($entryid,$model_subcat_id){ if ($entryid){ $toltelek=''; if (is_array($entryid)){ $entrys=""; for ($i=0;$i0) $toltelek="`cr`.`prod_id` IN ($entrys) AND"; }else if ($entryid) $toltelek="`cr`.`prod_id`='$entryid' AND"; $query="SELECT `cp`.*,`cr`.`id` as `relation` FROM `container_properties`as `cp`, `container_rel` as `cr` WHERE $toltelek `cr`.`prop_id`=`cp`.`id` AND `cp`.`model_subcat_id`='$model_subcat_id'"; $result=mysql_query( $query ) or die($query."
".mysql_error()); $lista=array(); while($row=mysql_fetch_array($result)){ $lista[]=$row; } return $lista; }else return null; } function entry_getProperties($modelid,$model_subcat_id){ $query="SELECT * FROM `container_properties` WHERE `modelid`='$modelid' AND `model_subcat_id`='$model_subcat_id'"; $result=mysql_query( $query ) or die($query."
".mysql_error()); $lista=array(); while($row=mysql_fetch_array($result)){ $lista[]=$row; } return $lista; } function entry_insertProperties($modelid,$subcatid,$value,$type){ if ($type=='2'){ $query="SELECT * FROM `container_properties` WHERE `modelid`='$modelid' AND `model_subcat_id`='$subcatid' AND `value`='$value'"; $result=mysql_query( $query ) or die($query."
".mysql_error()); if (mysql_affected_rows()<1){ $query="INSERT INTO `container_properties` (`ondate`,`modelid`,`model_subcat_id`,`value`) VALUES (NOW(),'$modelid','$subcatid','$value')"; mysql_query($query) or die($query."
".mysql_error()); return mysql_insert_id(); } $row=mysql_fetch_array($result); return $row['id']; }else{ $query="INSERT INTO `container_properties` (`ondate`,`modelid`,`model_subcat_id`,`value`) VALUES (NOW(),'$modelid','$subcatid','$value')"; mysql_query($query) or die($query."
".mysql_error()); return mysql_insert_id(); } } function entry_updateProperties($modelid,$id,$subcatid,$value){ $query="UPDATE `container_properties` set `value`='$value' WHERE `modelid`='$modelid' AND `model_subcat_id`='$subcatid' AND `id`='$id'"; $result=mysql_query( $query ) or die($query."
".mysql_error()); } function getProductByPropertie($properties){ $tsz=count($properties); $tulajd=''; for ($i=0;$i<$tsz;$i++){ $tulajd.=$tsz[$i].","; } $tulajd=substr($tulajd,0,strlen($tulajd)-1); $query="select * from container where container.id in( SELECT q1.prod_id from container_rel as q1 where q1.prop_id in ($tulajd) group by q1.prod_id having count(q1.prop_id) >= $tsz)"; $result=mysql_query( $query ) or die($query."
".mysql_error()); $lista=array(); while($row=mysql_fetch_array($result)){ $lista[]=$row; } return $lista; } // Hozzaadjuk a kulcsszavakat egy termekhez function entry_addKeywords ($keywords, $prodid) { $query="SELECT * FROM `keywords` WHERE `prodid` =".$prodid; $add=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($add)) { $result[$listAll["id"]]=$listAll; } if($result) { $query1='UPDATE `keywords` SET `keywords` = "'.$keywords.'" WHERE `prodid` ='.$prodid; $add=mysql_query($query1); } else { $query2='INSERT INTO `keywords` ( `id` , `prodid` , `keywords` ) VALUES ( NULL , "'.$prodid.'", "'.$keywords.'" );'; $add=mysql_query( $query2 ) or die(mysql_error()); } } function entry_addProperties($modelid,$entryid,$array){ if ($array['properties']){ foreach ($array['properties'] as $key=>$value){ foreach ($value as $k=>$v){ if ($v!=''){ $subcat=models_get_subcatById($key); if (strpos($k,'new')===false){ if ($subcat['type']=='1'){ entry_updateProperties($modelid,$k,$key,$v); }else if ($subcat['type']=='2'){ entry_updateRel($v,$array['relation'][$key][$k]); } }else if ($subcat['type']=='1'){ $valueid= entry_insertProperties($modelid,$key,$v,1); entry_insertRel($entryid,$valueid); }else if ($subcat['type']=='2'){ entry_insertRel($entryid,$v); } } } } } } function entry_insertEntry( $modelid , $array ,$desc) { $query = "INSERT INTO `container` ( `id` , `modelid` , `ondate` , `active` , `code_copy`, `name`,`code`,`code_produs`,`desc`,`price`,`pret_promo`,`pret_partner`,`pret_furnizor`,`monytype`,`minQuantity` ,`lang`,`um`) VALUES ( NULL , '$modelid', NOW( ) , '0', '0', '".$array["name"]."','".$array["code"]."','".$array["code_produs"]."','".$desc."','".$array["price"]."','".$array["pret_promo"]."','".$array["pricep"]."','".$array["pricef"]."','".$array["monytype"]."','".$array["minQuantity"]."','".$array["lang"]."','".$array["um"]."');"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function entry_addEntry( $modelid , $array ,$desc) { //cs query generator $myModel = model_getModel( $modelid ); $csVal = ""; $csQuery = ""; $index = 1; if($myModel["cs"]) foreach( $myModel["cs"] as $key => $value ) { $csQuery .= ",`cs$index`"; $csVal .= ",' ".$array["cs".$index].";'"; $index ++; } $query = "INSERT INTO `container` ( `id` , `modelid` , `ondate` , `active` , `code_copy`, `name`,`code`,`code_produs`,`desc`,`price`,`pret_promo`,`pret_partner`,`pret_furnizor`,`monytype`,`minQuantity` $csQuery ,`lang`,`um`) VALUES ( NULL , '$modelid', NOW( ) , '0', '0', '".$array["name"]."','".$array["code"]."','".$array["code_produs"]."','".$desc."','".$array["price"]."','".$array["pret_promo"]."','".$array["pricep"]."','".$array["pricef"]."','".$array["monytype"]."','".$array["minQuantity"]."'".$csVal.",'".$array["lang"]."','".$array["um"]."');"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function entry_addEntryCOPY( $modelid , $array ,$desc) { //cs query generator $myModel = model_getModel( $modelid ); $csVal = ""; $csQuery = ""; $index = 1; if($myModel["cs"]) foreach( $myModel["cs"] as $key => $value ) { $csQuery .= ",`cs$index`"; $csVal .=",'".$array["cs".$index]."'"; $index ++; } $query = "INSERT INTO `container` ( `id` , `modelid` , `ondate` , `active` , `code_copy`, `name`,`code`,`code_produs`,`desc`,`price`,`pret_promo`,`monytype`,`minQuantity` $csQuery , `um`) VALUES ( NULL , '$modelid', NOW( ) , '0', '1','".$array["name"]."','".$array["code"]."','".$array["code_produs"]."','".$desc."','".$array["price"]."','".$array["pret_promo"]."','".$array["monytype"]."','".$array["minQuantity"]."'".$csVal.",'".$array["um"]."' );"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } //container entry //container table function entry_getConEntries () { $query = " SELECT c.* ,m.name as modelname FROM `container` c , `models` m WHERE c.modelid = m.id ORDER BY `c`.modelid"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $entries[ $row["id"] ] = $row; return $entries; } else return NULL; } function entry_getConEntries1 () { $query = " SELECT c.* ,m.name as modelname FROM `container` c , `models` m WHERE c.modelid = m.id AND c.active=1 ORDER BY `c`.modelid"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $entries[ $row["id"] ] = $row; return $entries; } else return NULL; } function entry_getConEntry( $entryid ) { $query = "SELECT c.*, m.`name` as modelname FROM `container` c,`models` m WHERE c.`id`='$entryid' and c.`modelid`=m.`id` LIMIT 1 ;"; $result = mysql_query( $query ) or die(mysql_error()); return ( $entry = mysql_fetch_array( $result )); } function entry_insertRel($entryid,$propid){ $query="INSERT INTO `container_rel` (`prod_id`,`prop_id`) VALUES ('$entryid','$propid')"; $result = mysql_query( $query ) or die(mysql_error()); } function entry_updateRel($propid,$id){ $query="update `container_rel` set `prop_id`='$propid' WHERE `id`='$id'"; $result = mysql_query( $query ) or die(mysql_error()); } function entry_updateEntry($entryid,$modelid,$array,$text){ echo $query = "UPDATE `container` SET `modelid` = '".$array["modelid"]."', `name` = '".$array["name"]."', `code`='".$array["code"]."', `ondate`= NOW(), `desc` = '".$text."', `price`='".$array["price"]."', `pret_promo`='".$array["pret_promo"]."', `pret_partner`='".$array["pricep"]."', `pret_furnizor`='".$array["pricef"]."', `monytype` = '".$array["monytype"]."', `um` = '".$array["um"]."', `minQuantity` = '".$array["minQuantity"]."' WHERE `container`.`id` =$entryid LIMIT 1 ;"; mysql_query( $query ) or die(mysql_error()); if ($array['properties']){ foreach ($array['properties'] as $key=>$value){ foreach ($value as $k=>$v){ if ($v!=''){ $subcat=models_get_subcatById($key); if (strpos($k,'new')===false){ if ($subcat['type']=='1'){ entry_updateProperties($modelid,$k,$key,$v); }else if ($subcat['type']=='2'){ entry_updateRel($v,$array['relation'][$key][$k]); } }else if ($subcat['type']=='1'){ $valueid= entry_insertProperties($modelid,$key,$v,1); entry_insertRel($entryid,$valueid); }else if ($subcat['type']=='2'){ entry_insertRel($entryid,$v); } } } } } } function entry_editConEntry( $entryid , $modelid , $array , $desc ) { $myModel = model_getModel( $modelid ); $csVal = ""; $csQuery = ""; $index = 1; if($myModel["cs"]) foreach( $myModel["cs"] as $key => $value ) { $csQuery .= ",`cs$index`=' ".$array["cs".$index].";"; $entrycsindex="cs".$index; $result2=getcsssupliment2( $entryid ); while( $row=mysql_fetch_array($result2) ) { $suplimentcsindex=$row["cs"]; if ($entrycsindex==$suplimentcsindex) { $j = $row["id"]; $cssspecid = htmlspecialchars($array["cssupliment$j"]); $csQuery .=" ".$cssspecid.";"; } } $csQuery .="' "; $index ++; } $query = "UPDATE `container` SET `modelid` = '".$array["modelid"]."', `name` = '".$array["name"]."', `code`='".$array["code"]."', `ondate`= NOW(), `desc` = '".$desc."', `price`='".$array["price"]."', `pret_promo`='".$array["pret_promo"]."', `pret_partner`='".$array["pricep"]."', `pret_furnizor`='".$array["pricef"]."', `monytype` = '".$array["monytype"]."', `um` = '".$array["um"]."', `minQuantity` = '".$array["minQuantity"]."' $csQuery WHERE `container`.`id` =$entryid LIMIT 1 ;"; mysql_query( $query ) or die(mysql_error()); } function entry_modiyEntrySturcture( $modelid , $csIndex ) { $shiftPart = ""; for( $i = $csIndex ; $i < 20 ; $i++ ) $shiftPart .= "`cs$i` = `cs".($i+1)."`,"; $shiftPart[ strlen( $shiftPart ) -1 ] =" "; $query = "UPDATE `container` SET $shiftPart WHERE `modelid`='$modelid'"; mysql_query( $query ) or die(mysql_error()); } //searches an entry MODEL - ENTRY - ITEM function entry_searchEntry( $keyword , $type,$viewall,$userid ) { if( $type == "all" ) $query = "SELECT * FROM `container` WHERE `name` LIKE '%$keyword%' OR `code` LIKE '%$keyword%' OR `desc` LIKE '%$keyword%'"; else if( $type == "code" ) $query = "SELECT * FROM `container` WHERE `code`='$keyword' LIMIT 1;"; else if( $type == "name") $query = "SELECT * FROM `container` WHERE `name` LIKE '%$keyword%'"; else if( $type == "desc") $query = "SELECT * FROM `container` WHERE `desc` LIKE '%$keyword%'"; if($viewall!="1") { $viewquery= " AND (`modelid` IN(`SELECT `id` FROM `models` WHERE `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid') )"; } $query.= $viewquery; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $products[ $row["id"] ] = $row; return $products; } else return NULL; } //stock function stock_createStock( $name , $locid ) { $query = "INSERT INTO `stocks` ( `id` , `name` , `ondate` ,`locid` ) VALUES ( NULL , '$name', NOW( ) ,'$locid' );"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function stock_getStocks() { $query = "SELECT * FROM `stocks` order by `locid`"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $stocks[ $row["id"] ] = $row; return $stocks; } else return NULL; } function stock_getStockFromLocation( $location ) { $query = "SELECT * FROM `stocks` WHERE `locid`= '$location' order by `id`"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $stocks[ $row["id"] ] = $row; return $stocks; } else return NULL; } function stock_LipsaProdus() { $query="SELECT * FROM `container`"; $result=mysql_query($query) or die(mysql_error()); $i=0; while($row=mysql_fetch_array($result)) { if($row["minQuantity"]!=NULL && $row["minQuantity"]!=0) { $min = $row["minQuantity"]; $id = $row["id"]; $query2 = "SELECT * FROM `stock_items` WHERE `itemid`='$id'"; $result2 = mysql_query($query2) or die(mysql_error()); $rows = mysql_num_rows($result2); if($rows <= $min) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=3;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function stock_getStock( $stockid ) { $query = "SELECT * FROM `stocks` WHERE `id`= $stockid LIMIT 1;"; $result = mysql_query( $query ) or die($query." ".mysql_error()); if( $result ) { return $stock = mysql_fetch_array( $result ); } else return NULL; } function stock_containsItem( $stockId , $itemId ) { $query = "SELECT * FROM `stock_items` WHERE `stockid`='$stockId' AND `itemid`='$itemId' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() == 0 )return -1; $row = mysql_fetch_array( $result ); return $row["quantity"]; } function stock_containsItemGeneral( $stockId , $itemId ) { if ($stockId) $stock="`stockid`='$stockId' AND"; else $stock=''; $query = "SELECT * FROM `stock_items` WHERE $stock `itemid`='$itemId' and `arrived`='1'"; $result = mysql_query( $query ); if( mysql_affected_rows() == 0 )return 0; $totalQuantity=0; while($row = mysql_fetch_array( $result )) { $totalQuantity+=$row["quantity"]; } return $totalQuantity; } function stock_containsItemGeneralStock( $itemId ) { $query = "SELECT * FROM `stock_items` WHERE `itemid`='$itemId' and `arrived`='1'"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() == 0 )return 0; while($row = mysql_fetch_array( $result )) { $totalQuantity+=$row["quantity"]; } return $totalQuantity; } //fifo //lifo //cmp modszer function stock_addItem( $userid , $provid , $itemid , $stockid , $code , $quantity , $price , $src , $arrived , $code , $quantityType, $moneytype, $seria, $date, $locid=0) { if ($date=='') $date2="NOW()"; else $date2="DATE_ADD('".$date."', INTERVAL 1 SECOND)"; $natPrice = $price; if($quantity>0) { if( $src == 1 && $arrvied == 1 && $code == 1 ) $price = convertNumber( $price + $price * $_SESSION["settings"]["inadaos"] ); $query = "INSERT INTO `stock_items` ( `id` , `ondate` , `userid` ,`provid`, `stockid` , `itemid` , `code` , `quantity` , `price`,`natprice`,`src`,`arrived`,`transfercode`,`quantityType`,`moneyType`,`punctDeLucruID`,`serialNumber`) VALUES ( NULL ,$date2 , '$userid', '$provid' , '$stockid', '$itemid', '$code', '$quantity','$price','$natPrice','$src','$arrived','$code','$quantityType','$moneytype','$locid','$seria' );"; $result = mysql_query( $query ) or die($query." ".mysql_error()); if($result) insert_stock_items_in ( $userid , $provid, $stockid , $itemid, $quantity , $price, '-1' , $quantityType, $date); return mysql_insert_id(); } else { //ebben az esetben kivesszuk a betett elemet $query = "SELECT * FROM `stock_items` WHERE `itemid`='$itemid' AND `price`='$price' AND `quantityType`='$quantityType' AND `moneyType`='$moneytype' AND `provid`='$provid' AND `stockid`='$stockid';"; $result = mysql_query( $query ) or die(mysql_error()); if($result) { $row = mysql_fetch_array($result); factura_remFromStockDirect($row["id"],$quantity*(-1),''); } } } function stock_getStockItemById( $id ) { $query="SELECT * FROM `stock_items` WHERE `id`='$id'"; $result=mysql_query($query) or die(mysql_error()); $row = mysql_fetch_array($result); return $row; } function stockitem_Getmodel($id) { $query="SELECT * FROM container WHERE `id`='$id'"; $result=mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array($result); return $row; } function stock_modItem( $itemid , $array ) { $updateQ = "UPDATE `stock_items` SET `price` = ".$array["price"].",`moneyType` = ".$array["moneyType"]." WHERE `id`='$itemid' LIMIT 1;"; mysql_query( $updateQ ) or die(mysql_error()); } function stock_getPendingStockItems( $stockid ) { $query = "SELECT `s`.* , `c`.name as itemname FROM `stocks` sl, `stock_items` s, `container` c WHERE `s`.`stockid`=`sl`.`id` AND `sl`.`locid`='$stockid' AND `s`.itemid=`c`.id AND `arrived`=0"; $result = mysql_query( $query ) or die(mysql_error()); if( count( $result ) ) { while( $row = mysql_fetch_array( $result ) ) $items[ $row["id"] ] = $row; return $items; } else return NULL; } function stock_getOnRouteItems( $stockid ) { $query = "SELECT `s`.* , `c`.name as itemname FROM `stock_items` s, `container` c WHERE `s`.provid=$stockid AND `s`.itemid=`c`.id AND `arrived`=0"; $result = mysql_query( $query ) or die(mysql_error()); if( count( $result ) ) { while( $row = mysql_fetch_array( $result ) ) $items[ $row["id"] ] = $row; return $items; } else return NULL; } function stock_getStockItems( $stockid ) { $query = "SELECT `s`.* , `c`.name as itemname ,`c`.code as modcode, `c`.modelid as modelid FROM `stock_items` s, `container` c WHERE `s`.stockid=$stockid AND `s`.itemid=`c`.id AND `arrived`=1"; $result = mysql_query( $query ) or die(mysql_error()); if( count( $result ) ) { while( $row = mysql_fetch_array( $result ) ) $items[ $row["id"] ] = $row; return $items; } else return NULL; } function stock_getStockItem( $entryid ) { $query = "SELECT `s`.* , `c`.name as itemname , `c`.code as prodcode FROM `stock_items` s, `container` c WHERE `s`.id=$entryid AND `s`.itemid=`c`.id AND `arrived`=1"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { return ( $item = mysql_fetch_array( $result )); } else return NULL; } function stock_getStockItem2( $entryid ) { $query = "SELECT `s`.* , `c`.name as itemname , `c`.code as prodcode, `m`.name as modelname FROM `stock_items` s, `container` c, `models` m WHERE `s`.id=$entryid AND `s`.itemid=`c`.id AND `c`.`modelid`=`m`.`id` AND `arrived`=1"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { return ( $item = mysql_fetch_array( $result )); } else return NULL; } function stock_getStockItemsInDateInterval( $stockid , $from , $to ) { $to = mysql_nextDay( $to ); $query = "SELECT * FROM stock_items WHERE `stockid` = '$stockid' AND `ondate` BETWEEN '$from' AND '$to'"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $items[ $row[ "id" ] ] = $row; return $items; } return NULL; } function stock_transferStockItem( $userid , $stockItemId , $srcStockId , $destStockId , $quantity , $code ) { $srcQuery = "SELECT * FROM `stock_items` WHERE `id`='$stockItemId' LIMIT 1"; $srcResult = mysql_query( $srcQuery ); if( $srcResult ) { $row = mysql_fetch_array( $srcResult ); $srcStockQuantity = $row["quantity"]; $srcStockQuantityType = $row["quantityType"]; $srcStockValue = $row["price"]; if( $quantity > $srcStockQuantity )return NULL; if( $quantity == $srcStockQuantity ) {//all items have been taken out $delQuery = "DELETE FROM `stock_items` WHERE `id`='$stockItemId' LIMIT 1"; mysql_query( $delQuery ) or die(mysql_error()); } else {//not all items have been taken out $updateQuery = "UPDATE `stock_items` SET `quantity`=ROUND(".($srcStockQuantity - $quantity).",4) WHERE `id`='$stockItemId' LIMIT 1"; mysql_query( $updateQuery ) or die(mysql_error()); } insert_stock_items_out ($userid, /*provid*/$row["provid"], /*stockid*/$srcStockId, $stockItemId, $quantity, /*price*/$srcStockValue, /*"src*/$row["src"] , $srcStockQuantityType,$srcStockValue,''); //add to dest stock stock_addItem( $userid , $srcStockId , $row["itemid"] , $destStockId ,"code" , $quantity , $srcStockValue , 0 , 1 , $code , $srcStockQuantityType,"RON","",$destStockId,""); stock_registerTransfer( $srcStockId , $destStockId , $stockItemId , $quantity , $srcStockQuantityType); return true; } else return false; } function stock_unlockTransfer( $unlockcode ) { $updater = "UPDATE `stock_items` SET `arrived`='1' WHERE `transfercode`='$unlockcode'"; mysql_query( $updater ) or die(mysql_error()); } function stock_registerTransfer( $srcId , $destId , $itemId , $quantity , $quantityType ) { $query = "INSERT INTO `ios` ( `id` , `srcid` , `destid` , `itemid` , `quantity` , `ondate` , `quantityType`) VALUES ( NULL , '$srcId', '$destId', '$itemId', '$quantity', NOW( ) , '$quantityType' );"; mysql_query( $query ) or die(mysql_error()); } function stock_getServices( $orderby, $ordermode, $category , $pagetoshow = -1,$viewall="0",$userid="0",$filteractive="" ) { if($category) $categoryFilter=" AND `modelid`='$category' "; else $categoryFilter=""; if($filteractive!=="") $activefilter=" AND `s`.`active`='$filteractive' "; if($viewall!="1") { $viewquery= " AND ( `sm`.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid')))) "; } $query = "SELECT s.id AS id, s.name, `s`.`active`, sm.type, s.ondate , s.price, s.dbmod, s.durata, s.moneyType FROM service_models sm, services s WHERE sm.id = s.modelid ".$categoryFilter.$viewquery.$activefilter." ORDER BY $orderby $ordermode"; if ($pagetoshow != -1) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pagetoshow - 1) * $count; $query .= " LIMIT $from, $count"; } $result = mysql_query ($query) or die(mysql_error()); //echo $query; while ($row = mysql_fetch_array ($result)) $list [$row ["id"]] = $row; return $list; } function service_getService( $serviceid ) { $query = "SELECT * FROM `services` WHERE `id`= '$serviceid' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { return $stock = mysql_fetch_array( $result ); } else return NULL; } function stock_getServiceModels($viewall,$userid) { if($viewall!="1") { $viewquery= " WHERE ( `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid')))) "; } $selectQ = "SELECT * FROM `service_models` $viewquery"; $result = mysql_query( $selectQ ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; } return NULL; } function stock_getServiceModelsFromKeyword($keyword,$viewall,$userid) { if($viewall!="1") { $viewquery= " AND ( `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid')))) "; } $selectQ = "SELECT * FROM `service_models` where `type` LIKE '%$keyword' $viewquery"; //echo $selectQ; $result = mysql_query( $selectQ ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; } return NULL; } function stock_addServiceModel( $array ) { if( $array["desc"] == NULL )$array["desc"] = "-"; $insertQ = "INSERT INTO `service_models` (`id`,`type`,`desc`,`departament`) VALUES(NULL,'".$array["type"]."','".$array["desc"]."','".$array["departament"]."')"; mysql_query( $insertQ ) or die(mysql_error()); return mysql_insert_id(); } function stock_addService( $array ) { $insertQ = "INSERT INTO `services` (`id`,`name`,`ondate`,`price`,`moneyType`,`modelid`,`durata`,`dbmod`) VALUES( NULL ,'".$array["name"]."',NOW(),'".$array["price"]."','".$array["cursValutar"]."','".$array["modelid"]."','".$array["durata"]."','".$array["dbmod"]."')"; mysql_query( $insertQ ) or die(mysql_error()); return mysql_insert_id(); } function stock_modService( $array,$serviceid ) { $modQ ="UPDATE `services` SET `name` = '".$array["name"]."', `ondate` = NOW(), `price` = '".$array["price"]."', `moneyType` = '".$array["cursValutar"]."', `modelid` = '".$array["modelid"]."', `durata` = '".$array["durata"]."', `dbmod` = '".$array["dbmod"]."' WHERE `services`.`id` =$serviceid LIMIT 1 ;"; mysql_query( $modQ ) or die(mysql_error()); } function stock_delService( $serviceId ) { $query = "DELETE FROM `services` WHERE `id`='$serviceId' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } function stock_delServiceModel( $serviceModelId ) { $query = "DELETE FROM `service_models` WHERE `id`='$serviceModelId' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } //date speciale function stock_getdateSpeciale( $orderby, $ordermode, $pagetoshow , $search) { if($search!=NULL) $searchQuery = "AND sm.type = '$search'"; else $searchQuery = ""; $query = "SELECT s.id AS id, s.name, sm.type, s.ondate, s.price, s.rate, s.finalClientPrice FROM date_speciale_models sm, date_speciale s WHERE sm.id = s.modelid ".$searchQuery." ORDER BY $orderby $ordermode"; if ($pagetoshow != -1) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pagetoshow - 1) * $count; $query .= " LIMIT $from, $count"; } $result = mysql_query ($query) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $list [$row ["id"]] = $row; return $list; } function stock_getdateSpecialeCount( $orderby, $ordermode, $pagetoshow , $search) { if($search!=NULL) $searchQuery = "AND sm.type = '$search'"; else $searchQuery = ""; $query = "SELECT s.id AS id, s.name, sm.type, s.ondate, s.price, s.rate, s.finalClientPrice FROM date_speciale_models sm, date_speciale s WHERE sm.id = s.modelid ".$searchQuery." ORDER BY $orderby $ordermode"; $result = mysql_query ($query) or die(mysql_error()); $count = mysql_num_rows ( $result ); return $count; } function getDateSpecialeEntry ($id) { $query = "SELECT * FROM date_speciale WHERE id = '$id' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); if($result) $entry = mysql_fetch_array ($result); return $entry; } function stock_getdateSpecialeModels() { $selectQ = "SELECT * FROM `date_speciale_models`"; $result = mysql_query( $selectQ ); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; } return NULL; } function stock_adddateSpecialeModel( $array ) { if( $array["desc"] == NULL ) $array["desc"] = "-"; $insertQ = "INSERT INTO `date_speciale_models` (`id`,`type`,`desc`) VALUES(NULL,'".$array["type"]."','".$array["desc"]."')"; mysql_query( $insertQ ) or die(mysql_error()); return mysql_insert_id(); } function stock_adddateSpeciale( $array ) { $insertQ = "INSERT INTO `date_speciale` (`id`,`name`,`ondate`,`modelid`,`price`,`rate`,`finalClientPrice`) VALUES( NULL ,'".$array["name"]."',NOW(),'".$array["modelid"]."','".$array["price"]."','".$array["rate"]."','".$array["finalClientPrice"]."')"; mysql_query( $insertQ ) or die(mysql_error()); return mysql_insert_id(); } function stock_moddateSpeciale( $servid , $array ) { $query = "UPDATE `date_speciale` SET `name` = '".$array["name"]."', `modelid` = '".$array["modelid"]."', `price` = '".$array["price"]."', `finalClientPrice` = '".$array["finalClientPrice"]."', `rate` = '".$array["rate"]."' WHERE `date_speciale`.`id` =$servid LIMIT 1 ;"; mysql_query( $query ) or die(mysql_error()); } function stock_deldateSpeciale( $serviceId ) { $query = "DELETE FROM `date_speciale` WHERE `id`='$serviceId' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } function stock_deldateSpecialeModel( $serviceModelId ) { $query = "DELETE FROM `date_speciale_models` WHERE `id`='$serviceModelId' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } //end function transfer_validateItemAdd( $transfer , $itemid , $itemcount ) { $dbstat = stock_getStockItem( $itemid ); if( $dbstat["quantity"] < $itemcount )return false; if( $transfer["itemCount"] > 0 ) foreach( $transfer["items"] as $key => $value ) if( $value["destitemid"] == $itemid ) { if( ( $value["destquantity"] + $itemcount ) > $dbstat["quantity"])return false; } return true; } //search in each stock function stock_globalSearchGenerateQuery( $keyword , $type , $orderby , $ordermode , $skipStock , $page ) { if( !isset( $page ) )$page = 1; $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; if( strlen( $keyword ) > 0 ) { if( $type == "code" ) $query = "SELECT `s`.* ,`c`.name as itemname , `c`.code as prodcode FROM `stock_items` s, `container` c, `stocks` st WHERE `c`.id=`s`.itemid AND `c`.code ='$keyword' AND `s`.arrived = 1 AND `st`.locid != $skipStock AND `st`.`id`=`s`.`stockid` ORDER BY `c`.$orderby $ordermode LIMIT $from,$howmany"; else $query = "SELECT `s`.* ,`c`.name as itemname , `c`.code as prodcode FROM `stock_items` s, `container` c, `stocks` st WHERE `c`.id=`s`.itemid AND ( `c`.name LIKE '%$keyword%' OR `c`.desc LIKE '%$keyword%' ) AND `s`.arrived = 1 AND `st`.locid != $skipStock AND `st`.`id`=`s`.`stockid` ORDER BY `s`.$orderby $ordermode LIMIT $from,$howmany"; } else $query = "SELECT `s`.* ,`c`.name as itemname , `c`.code as prodcode FROM `stock_items` s, `container` c, `stocks` st WHERE `c`.id=`s`.itemid AND `s`.arrived = 1 AND `st`.locid != $skipStock AND `st`.`id`=`s`.`stockid` ORDER BY `s`.$orderby $ordermode LIMIT $from,$howmany"; return $query; } function stock_globalSearch( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( $result == NULL )return $result; while( $row = mysql_fetch_array( $result ) ) $found[ $row["id"] ] = $row; return $found; } function stock_searchGenerateQuery( $keyword , $type , $stockid , $page , $order , $ordermode, $id,$viewall,$userid ) { if( !isset( $page ) )$page = 1; $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; $locid = $_SESSION["user"]["defstock"]; if($stockid==-1) $stockQuery = ""; else { if($stockid!=NULL) $stockQuery = "AND `s`.stockid = $stockid"; else $stockQuery = "AND `sc`.locid = '$locid' and `sc`.`id`=`s`.`stockid`"; } if($viewall!="1") { $viewquery= " AND ( c.modelid IN (SELECT `id` FROM `models` WHERE `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid')))) ) "; } if( strlen( $keyword ) > 0 ) { if( $type == "code" ) $query = "SELECT `s`.* ,`c`.name as itemname , `c`.id as conid, `c`.code as prodcode FROM `stock_items` s, `container` c, `stocks` sc WHERE `c`.id=`s`.itemid AND `c`.code LIKE '%$keyword%' $stockQuery AND `s`.arrived = 1 $viewquery GROUP BY `s`.`id` ORDER BY $order $ordermode LIMIT $from,$howmany"; else $query = "SELECT `s`.* ,`c`.name as itemname , `c`.id as conid,`c`.code as prodcode FROM `stock_items` s, `container` c , `models` m, `stocks` sc WHERE `c`.modelid = `m`.id AND `c`.id=`s`.itemid AND ( `c`.name LIKE '%$keyword%' OR `c`.desc LIKE '%$keyword%' OR `c`.code LIKE '%$keyword%' OR `c`.name LIKE '%$keyword%' OR `m`.name LIKE '%$keyword%') $stockQuery AND `s`.arrived = 1 $viewquery GROUP BY `s`.`id` ORDER BY $order $ordermode LIMIT $from,$howmany"; } else { if($type=="id") { $query = "SELECT `s`.* ,`c`.name as itemname , `c`.id as conid, `c`.code as prodcode FROM `stock_items` s, `container` c, `stocks` sc WHERE `c`.id=`s`.itemid $stockQuery AND `s`.`id` = '$id' $viewquery GROUP BY `s`.`id` ORDER BY `c`.$order $ordermode LIMIT $from,$howmany"; } else { $orderby = ($order == "name" ? "c.name" : "s.$order"); $query = "SELECT `s`.* ,`c`.name as itemname , `c`.id as conid, `c`.code as prodcode FROM `stock_items` s, `container` c, `stocks` sc WHERE `c`.id=`s`.itemid $stockQuery AND `s`.arrived = 1 $viewquery GROUP BY `s`.`id` ORDER BY $order $ordermode LIMIT $from,$howmany"; } } return $query; } function stock_searchGenerateQueryForXls( $stockid , $toDate ) { //if( !isset( $page ) )$page = 1; //$from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; //$howmany = $_SESSION["settings"]["searchcount"]; $locid = $_SESSION["user"]["defstock"]; if($stockid==-1) $stockQuery = ""; else { if($stockid!=NULL) $stockQuery = "AND `s`.stockid = $stockid"; else $stockQuery = "AND `sc`.locid = '$locid' and `sc`.`id`=`s`.`stockid`"; } if($toDate=='') {$toDate=substr(date("Y-m-d G:i:s"),0,10); $dateFilter = "AND `s`.`ondate` <= '$toDate"." 23:59:59"."'";} else $dateFilter = "AND `s`.`ondate` <= '$toDate"." 23:59:59"."'"; $query = "SELECT `s`.* ,`c`.name as itemname , `c`.id as conid, `c`.code as prodcode FROM `stock_items` s, `container` c, `stocks` sc WHERE `c`.id=`s`.itemid $stockQuery AND `s`.arrived = 1 ".$dateFilter." GROUP BY `s`.`id` ORDER BY `s`.`ondate` ASC"; return $query; } function stock_getCategoryName($id) { $query="select m.name from container c, models m where c.modelid=m.id and c.id='$id';"; $result=mysql_query($query) or die(mysql_error()); $r= mysql_fetch_array($result); return $r["name"]; } function stock_SearchCount( $query ) { if (strlen($query)>0){ $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows(); } return null; } function stock_Search( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( $result == NULL )return $result; while( $row = mysql_fetch_array( $result ) ) $found[ $row["id"] ] = $row; return $found; } //partners function factura_getPartnerFacturi( $clientid, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `facturi` WHERE `clientid`=$clientid AND `active` ='1' AND `type`='1' ORDER BY ondate $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function partner_getPartnerbyId($partnerid) { $query = "SELECT * FROM `partners` WHERE `id`='$partnerid'"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { return mysql_fetch_array($result); }else return NULL; } function partner_getProviders() { $query = "SELECT * FROM `partners` WHERE `ispartner`='1' ORDER BY `name`"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; }else return NULL; } function partner_getProvidersUser($userid) { $userInfo = users_getUser( $userid ); if($userInfo["clientView"]==0) $clientViewFilter=" AND `userid`='$userid'"; else $clientViewFilter=""; $query = "SELECT * FROM `partners` WHERE `ispartner`='1' ".$clientViewFilter." ORDER BY `name`"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; }else return NULL; } function partner_getAllClients() { $query = "SELECT * FROM `partners` WHERE `clientstate`='1' ORDER BY `name`"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; }else return NULL; } function getProdusFromFactura($factid) { $query="SELECT * FROM facturi_items WHERE `factid`='$factid' AND `product_type` NOT LIKE ''"; $result=mysql_query($query) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; }else return NULL; } function factura_ExpiredFacturas() { $query = "SELECT * FROM `facturi` where `active`='1' AND ( (`type`='0' AND `generatedFiscala`='0') OR `type`='1')"; $result = mysql_query($query) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { $testDate=$row["termenDePlata"]; if($testDate=="0000-00-00") $testDate=$row["dataExecutiei"]; if($testDate!="0000-00-00") { $date=$testDate; $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareNePlataFactura"] * 24 * 60 * 59); $todayDate = date("Y-m-d",$nextWeek); $day=subtract_dates($date, $todayDate); $balance = partner_getBalance($row["clientid"]); //tehat lejart a szamla, megnezzuk van e tartozas rajta $facturaValueval=0; $paidValue=0; if($row["onValuta"]!="RON") { $facturaValueval=convertNumber($row["value"]); $paidValue=factura_getPaidValueValuta($row["id"]); } $paidValueRon = convertNumber(factura_getPaidValue($row["id"])); $facturaValue = convertNumber($row["value"]*$row["cursValue"]); //s megnezzuk, ha nem volt fizetve, akkor stornoja van-e? $existsStornedFactura=factura_getStornedFactura( $row["id"] ); if($day>=-3 && $facturaValue>$paidValueRon && ($existsStornedFactura==0 || $existsStornedFactura==NULL) && $balance>0 ) { } if( $day>=-3 && $facturaValue>$paidValueRon && ($existsStornedFactura==0 || $existsStornedFactura==NULL) && $balance>0 ) { if($facturaValueval==0||($facturaValueval!=0&&$facturaValueval<$paidValue)) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=3;"; $result2=mysql_query($query2) or die(mysql_error()); if($result2) { $remdatefrom=""; while($r=mysql_fetch_array($result2)) { //itt valami gond van if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } else { $remdatefrom=""; } } if($remdatefrom!="") { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else { $list[$i++]=$row; } } } } } } return $list; } function expenses_ExpiredExpenses() { $query = "SELECT * FROM `expenses`"; $result = mysql_query($query) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { $testDate=$row["lastdayofpay"]; if($testDate!="0000-00-00") { $date=$testDate; $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareExpiredCheltuiala"] * 24 * 60 * 59); $todayDate = date("Y-m-d",$nextWeek); $day=subtract_dates($date, $todayDate); //tehat lejart a szamla, megnezzuk van e tartozas rajta $paidValueRon = convertNumber(expens_getPaid($row["id"])); $expensValue = convertNumber(($row["value"]+$row["tva"])*$row["cursValue"]); if($day>=-3 && $expensValue>$paidValueRon ) { } if($day>=-3 && $expensValue>$paidValueRon) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`='10';"; $remdatefrom=""; $result2=mysql_query($query2) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } else { $remdatefrom=""; } } if($remdatefrom!=NULL) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else { $list[$i++]=$row; } } } } return $list; } function factura_delete( $facturaId ) { $query = "DELETE FROM `facturi` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function bon_delete( $facturaId ) { $query = "DELETE FROM `bonConsum` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function factura_deleteBillFromFactura( $factid ) { $query = "DELETE FROM `bills` WHERE `factid`='$factid' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } function factura_rollbackSerialNumber( $facturaId ) { $factura = factura_getFactura( $facturaId ); $serial = $factura["serial"]; $serialNumber = $factura["number"]; $lockQ = "LOCK TABLES `serials` WRITE"; $result = mysql_query( $lockQ ) or die(mysql_error()); $selectQ = "SELECT * FROM `serials` WHERE `serial`='$serial' LIMIT 1;"; $result = mysql_query( $selectQ ); $row = mysql_fetch_array( $result ); $lastSerialNumber = $row["current"]; if( $lastSerialNumber == $serialNumber + 1 ) { $updateQ = "UPDATE `serials` SET `current` = '$serialNumber' WHERE `serial`='$serial' LIMIT 1"; mysql_query( $updateQ ); } $unlockQ = "UNLOCK TABLES;"; mysql_query( $unlockQ ); } function partners_addUsers($array , $web_client_id, $email) { $insertQ = "INSERT INTO `users_website` ( `id` , `username` , `upassworld` , `clientid` , `email` , `active` ) VALUES ( NULL,'".$array["username"]."', PASSWORD('".$array["passworld"]."'), '$web_client_id' , '".$email."', '0');"; mysql_query( $insertQ ) or die(mysql_error()); return mysql_insert_id(); } function partners_addPartnerPerson( $array , $userid, $stockid,$depid) { if( $array["facturalasuta"] == NULL) $array["facturalasuta"]=100; $query = "INSERT INTO `partners` ( `id` , `name` , `contactperson` , `country` , `state`,`city` , `address` , `orcnumber` , `bank` , `iban` , `cui` , `phone` , `fax` , `mobile` , `xemail` , `web` , `active` , `forname` , `lastname` , `cnp` , `birthdate` ,`seriebi`,`nrbi`,`eliberatde`,`dataelib`,`sold`,`avanssold`,`soldeur`,`avanssoldeur`,`soldusd`,`avanssoldusd`,`limit`,`newsletter`,`codpostal`,`stateid`,`clientstate`,`partnersType`,`partnersDomain`,`ondate`,`userid`,`stockid`,`tags`,`partnersIsPartner`,`departament`,`venitf`,`facturalasuta`) VALUES ( NULL , '".$array["lastname"]." ".$array["forname"]."' , NULL , '".$array["country"]."', '".$array["state"]."','".$array["city"]."', '".$array["address"]."', NULL , NULL , NULL , NULL , NULL , NULL , '".$array["mobile"]."', '".$array["xemail"]."', NULL, NULL , '".$array["forname"]."', '".$array["lastname"]."', '".$array["cnp"]."', '".$array["year"]."-".$array["month"]."-".$array["day"]."','".$array["seriebi"]."','".$array["nrbi"]."','".$array["eliberatde"]."','".$array["dataelib"]."','".$array["sold"]."','".$array["avanssold"]."','".$array["soldeur"]."','".$array["avanssoldeur"]."','".$array["soldusd"]."','".$array["avanssoldusd"]."','".$array["limit"]."','".$array["abonez"]."','".$array["codpostal"]."','".$array["stateid"]."','".$array["clientstate"]."','".$array["partnersType"]."','".$array["partnersDomain"]."',NOW(),'".$userid."','".$stockid."','".$array["tags"]."','".$array["partnersIsPartner"]."','$depid','".$array["venitf"]."','".$array["facturalasuta"]."' ); "; mysql_query( $query ) or die(mysql_error()); $_SESSION["xemail_web"]=$array["xemail"]; return mysql_insert_id(); } function partners_updatePartnerPerson( $partnerId , $array ) { if( $array["facturalasuta"] == NULL) $array["facturalasuta"]=100; $query ="UPDATE `partners` SET `name` = '".$array["lastname"]." ".$array["forname"]."', `country` = '".$array["country"]."', `state` = '".$array["state"]."', `stateid` = '".$array["stateid"]."', `city` = '".$array["city"]."', `address` = '".$array["address"]."', `mobile` = '".$array["mobile"]."', `xemail` = '".$array["xemail"]."', `forname` = '".$array["forname"]."', `lastname` = '".$array["lastname"]."', `cnp` = '".$array["cnp"]."', `birthdate` = '".$array["year"]."-".$array["month"]."-".$array["day"]."', `seriebi` = '".$array["seriebi"]."', `nrbi` = '".$array["nrbi"]."', `eliberatde` = '".$array["eliberatde"]."', `dataelib` = '".$array["dataelib"]."', `sold`='".$array["sold"]."', `avanssold` = '".$array["avanssold"]."', `soldeur`='".$array["soldeur"]."', `avanssoldeur` = '".$array["avanssoldeur"]."', `soldusd`='".$array["soldusd"]."', `avanssoldusd` = '".$array["avanssoldusd"]."', `limit` = '".$array["limit"]."', `tags` = '".$array["tags"]."', `partnersIsPartner` = '".$array["partnersIsPartner"]."', `venitf` = '".$array["venitf"]."', `clientstate` = '".$array["clientstate"]."', `facturalasuta` = '".$array["facturalasuta"]."', `codpostal` = '".$array["codpostal"]."' WHERE `partners`.`id` =$partnerId LIMIT 1 ;"; mysql_query( $query ) or die(mysql_error()); } function partners_addPartnerCompany( $array , $userid, $stocki,$depid) { if( $array["sold"] == NULL )$array["sold"] = 0; if( $array["facturalasuta"] == NULL) $array["facturalasuta"]=100; /*if($array["country"]=="ROM") { $array["stateid"]=$array["state"]; $judetDate=counties_getCounty($array["stateid"]); $array["state"]=$judetDate["name"]; } else { $array["stateid"]=0; //$judetDate=counties_getCounty($array["stateid"]); $array["state"]=$array["plusstate"]; $array["city"]=$array["pluscity"]; $array["codpostal"]=$array["pluscodpostal"]; }*/ $array["name"] = htmlspecialchars($array["name"]); $array["person"] = htmlspecialchars($array["person"]); $array["address"] = htmlspecialchars($array["address"]); $array["orcnumber"] = htmlspecialchars($array["orcnumber"]); $array["phone"] = htmlspecialchars($array["phone"]); $array["fax"] = htmlspecialchars($array["fax"]); $array["mobile"] = htmlspecialchars($array["mobile"]); $array["xemail"] = htmlspecialchars($array["xemail"]); $array["web"] = htmlspecialchars($array["web"]); $array["forname"] = htmlspecialchars($array["forname"]); $array["lastname"] = htmlspecialchars($array["lastname"]); $array["cnp"] = htmlspecialchars($array["cnp"]); $array["codpostal"] = htmlspecialchars($array["codpostal"]); $query = "INSERT INTO `partners` ( `id` , `name` , `contactperson` , `country` ,`state`, `city` , `address` , `orcnumber` , `bank` , `iban` , `cui` , `phone` , `fax` , `mobile` , `xemail` , `web` , `active` , `forname` , `lastname` , `cnp` , `birthdate` ,`ispartner`,`sold`,`avanssold`,`soldeur`,`avanssoldeur`,`soldusd`,`avanssoldusd`,`limit`,`newsletter`,`codpostal`,`stateid`,`clientstate`,`partnersType`,`partnersDomain`,`ondate`,`userid`,`stockid`,`prezentare`,`nrAngajati`,`departament`,`facturalasuta`,`tags`) VALUES ( NULL , '".$array["name"]."', '".$array["person"]."', '".$array["country"]."', '".$array["state"]."','".$array["city"]."', '".$array["address"]."', '".$array["orcnumber"]."', '".$array["bank"]."', '".$array["iban"]."', '".$array["cui"]."', '".$array["phone"]."', '".$array["fax"]."', '".$array["mobile"]."', '".$array["xemail"]."' , '".$array["web"]."', NULL , NULL , NULL , NULL , NULL ,'".$array["ispartner"]."','".$array["sold"]."','".$array["avanssold"]."','".$array["soldeur"]."','".$array["avanssoldeur"]."','".$array["soldusd"]."','".$array["avanssoldusd"]."','".$array["limit"]."','".$array["abonez"]."','".$array["codpostal"]."','".$array["stateid"]."','".$array["clientstate"]."','".$array["partnersType"]."','".$array["partnersDomain"]."',NOW(),'".$userid."','".$stockid."','".$array["prezentare"]."','".$array["nrAngajati"]."','$depid','".$array["facturalasuta"]."','".$array["tags"]."' );"; mysql_query( $query ) or die(mysql_error());; $_SESSION["xemail_web"]=$array["xemail"]; $clid=mysql_insert_id(); if($array["hrType"]!=""&&$array["person"]!="") { partner_addPartnerContact($clid,$userid,$stockid,$array); } return $clid; } function partners_addPartnerPunctedeLucruSediu( $clientid , $array) { $array["stateid"]=$array["state"]; $judetDate=counties_getCounty($array["state"]); $judetnev=$judetDate["name"]; $array["state"]=$judetnev; $query = "INSERT INTO `partners_punctDeLucru` ( `id` , `clientid`, `number` , `tara` , `judet` ,`oras`,`codpostal`, `adresa`,`sediu`,`contactPerson`,`judetid`) VALUES ( NULL , '$clientid',0, '".$array["country"]."', '".$array["state"]."', '".$array["city"]."','".$array["codpostal"]."','".$array["address"]."','1','".$array["person"]."','".$array["stateid"]."');"; mysql_query( $query ) or die(mysql_error()); } // TODO punct de lucru update function partners_addPartnerPunctedeLucru( $clientid ,$array) { $query2="SELECT * FROM `partners_punctDeLucru` WHERE `clientid`='$clientid' order by id"; $result2=mysql_query($query2) or die(mysql_error()); $i=-1; while( $row = mysql_fetch_array($result2) ) { $punctid = $row["id"]; if($i==-1) { $query = "UPDATE `partners_punctDeLucru` SET `number`=0 , `tara`='".$array["country"]."' , `judet`='".$array["state"]."' ,`oras`='".$array["city"]."',`codpostal`='".$array["codpostal"]."', `adresa`='".$array["address"]."', `judetid`='".$array["stateid"]."',`sediu`='1', `contactPerson`='".$array["person"]."' WHERE `clientid`='$clientid' AND `id`='$punctid'"; mysql_query($query) or die(mysql_error()); } else { $j=$i+1; if($array["newstatep_$j"]!=""&&$array["countryp_$j"]!="ROM") { $array["statep_$j"]=counties_insertCounty( $array["newstatep_$j"] , $array["countryp_$j"]); } if($array["countryp_$j"]!="ROM"&&$array["pluscityp_$j"]!="") { $array["city"]=cities_insertCity($array["statep_$j"],$array["pluscityp_$j"],$array["countryp_$j"]); } $tara = htmlspecialchars($array["countryp_$j"]); $judetDate=counties_getCounty($array["statep_$j"]); $judetnev=$judetDate["name"]; $state = htmlspecialchars($judetnev); $city = htmlspecialchars($array["cityp_$j"]); $address = htmlspecialchars($array["addressp_$j"]); $person = htmlspecialchars($array["personp_$j"]); $judetid = htmlspecialchars($array["statep_$j"]); $codpostal=""; if($array["countryp_$j"]!="ROM") $codpostal=$array["pluscodpostalp_$j"]; else $codpostal=$array["codpostalp_$j"]; $k=$i+2; $query1 = "UPDATE `partners_punctDeLucru` SET `number`='$k' , `tara`='".$tara."' , `judet`='".$state."' ,`oras`='".$city."', `codpostal`='".$codpostal."', `adresa`='".$address."',`sediu`='0',`contactPerson`='".$person."',`judetid`='".$judetid."' WHERE `clientid`='$clientid' AND `id`='$punctid' "; mysql_query( $query1 ) or die(mysql_error()); } $i++; } } function partners_addPartnerPunctedeLucru1( $clientid ) { $query = "INSERT INTO `partners_punctDeLucru` ( `id` , `clientid`,`sediu`) VALUES (NULL , '$clientid',0);"; mysql_query( $query ) or die(mysql_error()); } function partners_addPartnerEmail( $clientid) { $query = "INSERT INTO `partners_email` VALUES (NULL , '$clientid','');"; mysql_query( $query ) or die(mysql_error()); } function partners_addPartnerEmailDirect( $clientid , $email) { $query = "INSERT INTO `partners_email` VALUES (NULL , '$clientid','$email');"; if($email!='') mysql_query( $query ) or die(mysql_error()); } function partners_updatePartnerEmail( $clientid , $array) { $query2="SELECT * FROM `partners_email` WHERE `clientid`='$clientid' order by id"; $result2=mysql_query($query2) or die(mysql_error()); $j=0; while( $row=mysql_fetch_array($result2) ) { $post_email = htmlspecialchars($array["xemail$j"]); $mailid = $row["id"]; $query = "UPDATE `partners_email` SET `email`='$post_email' WHERE `clientid`='$clientid' AND `id`='$mailid'"; mysql_query( $query ) or die(mysql_error()); $j++; } } function partners_getpunctedelucru($clientid) { $query="SELECT * FROM `partners_punctDeLucru` WHERE `clientid`='$clientid' AND `sediu`='0'"; $result=mysql_query($query) or die(mysql_error()); return $result; } function partners_getsediu($clientid) { $query="SELECT * FROM `partners_punctDeLucru` WHERE `clientid`='$clientid' AND `sediu`='1'"; $result=mysql_query($query) or die(mysql_error()); return $result; } function partners_getemail($clientid) { $query="SELECT * FROM `partners_email` WHERE `clientid`='$clientid' AND `email`!=''"; $result=mysql_query($query) or die(mysql_error()); return $result; } function partners_getemailAddForm($clientid) { $query="SELECT * FROM `partners_email` WHERE `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); return $result; } function partners_getemailContacts($clientid) { $query="SELECT * FROM `partners_contact` WHERE `clientid`='$clientid' AND `email`!=''"; $result=mysql_query($query) or die(mysql_error()); return $result; } function partners_getpunctedelucru_id($punctid) { $query="SELECT * FROM `partners_punctDeLucru` WHERE `id`='$punctid'"; $result=mysql_query($query) or die(mysql_error()); return $result; } // TODO update partner function partners_updatePartnerCompany( $partnerId , $array) { $array["name"] = htmlspecialchars($array["name"]); $array["person"] = htmlspecialchars($array["person"]); $array["address"] = htmlspecialchars($array["address"]); $array["city"] = htmlspecialchars($array["city"]); $array["orcnumber"] = htmlspecialchars($array["orcnumber"]); $array["phone"] = htmlspecialchars($array["phone"]); $array["fax"] = htmlspecialchars($array["fax"]); $array["mobile"] = htmlspecialchars($array["mobile"]); $array["xemail"] = htmlspecialchars($array["xemail"]); $array["web"] = htmlspecialchars($array["web"]); $array["forname"] = htmlspecialchars($array["forname"]); $array["lastname"] = htmlspecialchars($array["lastname"]); $array["cnp"] = htmlspecialchars($array["cnp"]); $array["cui"] = htmlspecialchars($array["cui"]); $array["limit"] = htmlspecialchars($array["limit"]); if( $array["facturalasuta"] == NULL) $array["facturalasuta"]=100; $query = "UPDATE `partners` SET `name` = '".$array["name"]."', `contactperson` = '".$array["person"]."', `country` = '".$array["country"]."', `state` = '".$array["state"]."', `stateid` = '".$array["stateid"]."', `city` = '".$array["city"]."', `address` = '".$array["address"]."', `orcnumber` = '".$array["orcnumber"]."', `bank` = '".$array["bank_1"]."', `iban` = '".$array["iban_1"]."', `cui` = '".$array["cui"]."', `phone` = '".$array["phone"]."', `fax` = '".$array["fax"]."', `mobile` = '".$array["mobile"]."', `xemail` = '".$array["xemail"]."', `web` = '".$array["web"]."', `ispartner` = '".$array["ispartner"]."', `sold`='".$array["sold"]."', `avanssold` = '".$array["avanssold"]."', `soldeur`='".$array["soldeur"]."', `avanssoldeur` = '".$array["avanssoldeur"]."', `soldusd`='".$array["soldusd"]."', `avanssoldusd` = '".$array["avanssoldusd"]."', `limit` = '".$array["limit"]."', `codpostal` = '".$array["codpostal"]."', `partnersType` = '".$array["partnersType"]."', `partnersDomain` = '".$array["partnersDomain"]."', `clientstate` = '".$array["clientstate"]."', `userid` = '".$array["userid"]."', `partnersIsPartner` = '".$array["partnersIsPartner"]."', `tags` = '".$array["tags"]."', `nrAngajati` = '".$array["nrAngajati"]."', `facturalasuta` = '".$array["facturalasuta"]."', `prezentare` = '".$array["prezentare"]."' WHERE `partners`.`id` =$partnerId LIMIT 1 ;"; mysql_query( $query ) or die(mysql_error()); partners_addPartnerPunctedeLucru( $partnerId ,$array); partners_updatePartnerEmail( $partnerId , $array); crm_updatePartnerContacts( $partnerId , $array); } function partners_addBankAccount( $compid , $bank, $iban ) { $query = "INSERT INTO `bankaccounts` ( `id` , `compid` , `bank` , `iban` ) VALUES ( NULL , '$compid', '$bank', '$iban');"; mysql_query( $query ) or die(mysql_error()); } function partners_getPartnerBankAccount($compid) { $query="SELECT * FROM `bankaccounts` WHERE `compid`='$compid' order by id"; $result=mysql_query($query) or die(mysql_error()); return $result; } // TODO bank update function partners_updatePartnerBankAccount( $compid , $array ) { $result2=partners_getPartnerBankAccount( $compid ); $j=1; while( $row=mysql_fetch_array($result2) ) { $bank = htmlspecialchars($array["bank_$j"]); $iban = htmlspecialchars($array["iban_$j"]); $bankid = $row["id"]; $query = "UPDATE `bankaccounts` SET `bank`='$bank', `iban`='$iban' WHERE `compid`='$compid' AND `id`='$bankid'"; mysql_query( $query ) or die(mysql_error()); $j++; } } function partners_getPartnerEmail($id) { $query="select * from `partners_email` where `clientid`='$id'"; $result=mysql_query($query) or die(mysql_error()); return $result; } function partners_getBankAccounts( $compid ) { if($compid=='-1') { $query = "SELECT id,bank,iban FROM `companies`"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); $list[ -1 ] = $row; } $query = "SELECT * FROM `bankaccounts` WHERE `compid`='$compid'"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) { $list[ $row["id"] ] = $row; } } return $list; } function partner_getBankAccount( $accountid ) { if($accountid!=-1) { $query = "SELECT * FROM `bankaccounts` WHERE `id`='$accountid' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); } else { $query = "SELECT id,bank,iban FROM `companies`"; $result = mysql_query( $query ) or die(mysql_error()); } return mysql_fetch_array( $result ); } function partners_delBankAccount( $accountid ) { //lekerdezem, hogy van-e mozgas a bankfiokon $keres="SELECT * FROM `op` WHERE `type`='$accountid'"; mysql_query($keres) or die(mysql_error()); if (mysql_affected_rows()==0){ $keres2="SELECT * FROM `pais` WHERE `type`='$accountid'"; mysql_query($keres2); if (mysql_affected_rows()==0){ $query = "DELETE FROM `bankaccounts` WHERE `id`='$accountid' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); return true; }else return false; } return false; } // Beolvassa az aktualis partnereket, amik az adott factura-hoz tartoznak (asszem) function partners_getPartners( $type = 0 ) { $query = "SELECT * FROM `partners` WHERE `ispartner`='$type' ORDER BY name"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $providers[ $row["id"] ] = $row; return $providers; } function partners_getPartnersWithEmails( $type = 0 ) { $query = "SELECT `p`.`id`, `p`.`xemail`,`p`.`name`,`p`.`forname` FROM `partners` p WHERE (`p`.`xemail`!='' AND `p`.`xemail` is not NULL) ORDER BY `p`.`name`"; $counter=1; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $providers[$counter]["id"] = $row["id"]; $providers[$counter]["name"] = $row["name"]; $providers[$counter]["forname"] = $row["forname"]; $providers[$counter]["lastname"] = $row["lastname"]; $providers[$counter]["email"] = $row["xemail"]; $counter++; } $row=""; $query = "SELECT `e`.`clientid`,`p`.`id`,`p`.`name`,`p`.`forname`, `e`.`email` FROM `partners` p, `partners_email` e WHERE (`e`.`email`!='' AND `e`.`email` is not NULL) AND `p`.`id` = `e`.`clientid` ORDER BY `p`.`name`"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $providers[$counter]["id"] = $row["clientid"]; $providers[$counter]["name"] = $row["name"]; $providers[$counter]["forname"] = $row["forname"]; $providers[$counter]["lastname"] = $row["lastname"]; $providers[$counter]["email"] = $row["email"]; $counter++; } $row=""; $query = "SELECT `c`.`clientid`,`p`.`name`,`p`.`forname`, `c`.`email` FROM `partners` p, `partners_contact` c WHERE (`c`.`email`!='' AND `c`.`email` is not NULL) AND `p`.`id` = `c`.`clientid` ORDER BY `p`.`name`"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $providers[$counter]["id"] = $row["clientid"]; $providers[$counter]["name"] = $row["name"]; $providers[$counter]["forname"] = $row["forname"]; $providers[$counter]["lastname"] = $row["lastname"]; $providers[$counter]["email"] = $row["email"]; $counter++; } usort($providers,"cmp"); return $providers; } function partners_getPartnerFromEmail( $partnerEmail ) { $query = "SELECT * FROM `partners` WHERE `xemail`='$partnerEmail'"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 ) { $query = "SELECT * FROM `partners_email` WHERE `email`='$partnerEmail'"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 ) { $query = "SELECT * FROM `partners_contact` WHERE `email`='$partnerEmail'"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 ) { } else { return NULL; } } } return ( $partner = mysql_fetch_array( $result ) ); } function partners_getPartnersAll( $type = 0 ) { $query = "SELECT * FROM `partners` WHERE `clientstate`='1' ORDER BY `name`"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $providers[ $row["id"] ] = $row; return $providers; } function partners_getPartnersOrder( $type , $by) { $query = "SELECT * FROM `partners` WHERE `ispartner`='$type' ORDER BY $by"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $providers[ $row["id"] ] = $row; return $providers; } function partners_getPartner( $partnerId ) { $query = "SELECT * FROM `partners` WHERE `id`='$partnerId'"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $partner = mysql_fetch_array( $result ) ); } function partners_delPartner( $partnerid ) { $query = "DELETE FROM partners WHERE id = $partnerid"; mysql_query ($query) or die(mysql_error()); $query = "delete FROM `users_website` WHERE `clientid`='$partnerId'"; mysql_query( $query ) or die(mysql_error()); } function partners_searchPartnerGenerateQuery( $searchval , $iscomp , $page , $orderby , $ordermode , $ispartner , $clientstate, $partnersType, $partnersDomain, $classification, $classificationmin, $userid,$plateste) { $userInfo = users_getUser( $userid ); if($userInfo["clientView"]==0) $clientViewFilter=" AND `userid`='$userid'"; else $clientViewFilter=""; $viewall=$userInfo["partnerall"]; if($viewall!="1") { $viewquery= " AND ( p.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR p.`userid`='$userid') "; } if($clientstate==0 && $clientstate!=-1) $clientStateFilter=" AND `p`.`clientstate`='0'"; else $clientStateFilter=""; if($plateste!="") $platestefilter=" AND `p`.`facturalasuta`='$plateste'"; if($partnersType!=0) $partnersTypeFilter=" AND `p`.`partnersType`='$partnersType'"; else $partnersTypeFilter=""; if($partnersDomain!=0) { $partnersDomainFilter=" AND `p`.`partnersDomain`='$partnersDomain'"; } else { $partnersDomainFilter=""; } if($classification!=0 && $classificationmin) { $classificationSelect=",`c`.`categoryId`,`c`.`value`,`c`.`clientid`"; $classificationSelect2=", `crm_partnerClassification` c"; $classificationFilter=" AND `c`.`categoryId`='$classification' AND `c`.`value`>='$classificationmin' AND `p`.`id`=`c`.`clientid`"; } else { $classificationSelect=""; $classificationSelect2=""; $classificationFilter=""; } if($page!=-1) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; } else { $count = 10000000; $from=0; } if( $iscomp == 0 ) $query = "SELECT `p`.*".$classificationSelect." FROM `partners` p".$classificationSelect2." WHERE `p`.`cnp` is not NULL AND (`p`.`name` LIKE '%$searchval%' OR `p`.`tags` LIKE '%$searchval%' OR `p`.`forname` LIKE '%$searchval%' OR `p`.`lastname` LIKE '%$searchval%') ".$clientViewFilter.$clientStateFilter.$partnersTypeFilter.$partnersDomainFilter.$platestefilter.$classificationFilter.$viewquery." ORDER BY $orderby $ordermode LIMIT $from , $count"; else if( $iscomp == 1 ) $query = "SELECT `p`.*".$classificationSelect." FROM `partners` p".$classificationSelect2." WHERE `p`.`cnp` is NULL AND `p`.`ispartner`='$ispartner' AND (`p`.`name` LIKE '%$searchval%' OR `p`.`tags` LIKE '%$searchval%' OR `p`.`forname` LIKE '%$searchval%' OR `p`.`lastname` LIKE '%$searchval%' OR `p`.`cui` LIKE '%$searchval%') ".$clientViewFilter.$clientStateFilter.$partnersTypeFilter.$platestefilter.$partnersDomainFilter.$classificationFilter.$viewquery." ORDER BY $orderby $ordermode LIMIT $from , $count"; else if( $iscomp == 2 ) $query = "SELECT `p`.*".$classificationSelect." FROM `partners` p".$classificationSelect2." WHERE `p`.`cnp` is NULL AND `p`.`ispartner`='1' AND (`p`.`name` LIKE '%$searchval%' OR `p`.`tags` LIKE '%$searchval%' OR `p`.`forname` LIKE '%$searchval%' OR `p`.`lastname` LIKE '%$searchval%' OR `p`.`cui` LIKE '%$searchval%') ".$clientViewFilter.$clientStateFilter.$partnersTypeFilter.$platestefilter.$partnersDomainFilter.$classificationFilter.$viewquery." ORDER BY $orderby $ordermode LIMIT $from , $count"; else if( $iscomp == 3 ) $query = "SELECT `p`.*".$classificationSelect." FROM `partners` p".$classificationSelect2." WHERE `p`.`cnp` is NULL AND (`p`.`name` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `p`.`tags` LIKE '%$searchval%' OR `p`.`forname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `p`.`lastname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `p`.`cui` LIKE '%$searchval%') ".$clientViewFilter.$clientStateFilter.$partnersTypeFilter.$platestefilter.$partnersDomainFilter.$classificationFilter.$viewquery." ORDER BY $orderby $ordermode".$limitQuery; return $query; } function notcontains_contractForClient($clientid) { $query="SELECT * FROM `contractForClient` where `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); $rows=mysql_num_rows($result); if($rows==0) return true; else return false; } function notcontains_comandaForClient($clientid) { $query="SELECT * FROM `comandaForClient` where `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); $rows=mysql_num_rows($result); if($rows==0) return true; else return false; } function notcontains_comandaForClientAdv($clientid) { $query="SELECT * FROM `comandaForClientAdv` where `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); $rows=mysql_num_rows($result); if($rows==0) return true; else return false; } function notcontains_facturi($clientid) { $query="SELECT * FROM `facturi` where `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); $rows=mysql_num_rows($result); if($rows==0) return true; else return false; } function notcontains_dispozitie($clientid) { $query="SELECT * FROM `dispozitie` where `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); $rows=mysql_num_rows($result); if($rows==0) return true; else return false; } function notcontains_expences($clientid) { $query="SELECT * FROM `expenses` where `provider`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); $rows=mysql_num_rows($result); if($rows==0) return true; else return false; } function notcontains_comandaForClientFazaItemsHr($carid) { $query="SELECT * FROM `comandaForClientFazaItemsHr` where `carid`='$carid'"; $result=mysql_query($query) or die(mysql_error()); $rows=mysql_num_rows($result); if($rows==0) return true; else return false; } function notcontains_comandaForClientFazaItemsProvider($carid) { $query="SELECT * FROM `comandaForClientFazaItemsProviders` where `carid`='$carid'"; $result=mysql_query($query) or die(mysql_error()); $rows=mysql_num_rows($result); if($rows==0) return true; else return false; } function notcontains_OrdinDeplasare($carid) { $query="SELECT * FROM `ordinDeplasare` where `carid`='$carid'"; $result=mysql_query($query) or die(mysql_error()); $rows=mysql_num_rows($result); if($rows==0) return true; else return false; } function global_getQueryResults( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_num_rows($result); } function partners_seachPartner($query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $partners[ $row["id"] ] = $row; return $partners; } function partner_isPartnerMarked( $partnerid ) { $query = "SELECT * FROM marked_partners WHERE marked_partners.partnerid = $partnerid"; mysql_query( $query ) or die(mysql_error()); if (mysql_affected_rows () == 1) return true; else return false; } function partner_markPartner( $userid, $partnerid ) { $query = "SELECT * FROM marked_partners WHERE marked_partners.partnerid = $partnerid"; $result = mysql_query( $query ) or die(mysql_error()); if (partner_isPartnerMarked ($partnerid) == false) { $query = "INSERT INTO marked_partners VALUES (NULL, $partnerid, $userid, NOW())"; $result = mysql_query( $query ) or die(mysql_error()); if (mysql_affected_rows () == 1) return true; } return false; } function partner_unmarkPartner( $userid, $partnerid ) { if (partner_isPartnerMarked ($partnerid) == true) { $query = "DELETE FROM marked_partners WHERE marked_partners.partnerid = $partnerid"; $result = mysql_query( $query ) or die(mysql_error()); return true; } return false; } function partner_getBalance( $clientid , $toDate="") { if($toDate=="") $toDate=date("Y-m-d",time()+(24*60*60)); //facturi $facturiQ = "SELECT sum(`value` * `cursValue`) as totalFact FROM `facturi` WHERE `clientid`='$clientid' AND `active`='1' AND `type`='1' AND `ondate`<='$toDate'"; $facturiR = mysql_query( $facturiQ ) or die(mysql_error()); $factValue = mysql_result( $facturiR , 0 , 0 ); //bills $billQ = "SELECT sum(`value`) as totalBill FROM `bills` WHERE `clientid`='$clientid' AND `active`=1 AND `ondate`<='$toDate'"; $billR = mysql_query( $billQ ) or die(mysql_error()); $billValue = mysql_result( $billR , 0 , 0 ); //ops $opQ = "SELECT sum(`op`.`value` * `op`.`cursValue`) as totalOp FROM `op` op, `facturi` fact WHERE `op`.`clientid`='$clientid' AND `op`.`factid`=`fact`.`id` AND `fact`.`active`='1' AND `fact`.`type`='1' AND `fact`.`ondate`<='$toDate' AND `op`.`ondate`<='$toDate'"; $opR = mysql_query( $opQ ) or die(mysql_error()); $opValue = mysql_result( $opR , 0 , 0 ); //beleszamoljuk a koltseg szamlakat is (partnerek) $expensQ = "SELECT sum( (`value`+`tva`) * `cursValue`) as totalExpens FROM `expenses` WHERE `provider`='$clientid' AND `ondate`<='$toDate'"; $expensR = mysql_query( $expensQ ) or die(mysql_error()); $expensValue = mysql_result( $expensR , 0 , 0 ); $paisQ = "SELECT sum( `value` * `cursValue`) as totalPais FROM `pais` WHERE `partnerid`='$clientid' AND `ondate`<='$toDate'"; $paisR = mysql_query( $paisQ ) or die(mysql_error()); $paisValue = mysql_result( $paisR , 0 , 0 ); $difference = 0; $difference = (convertNumber($factValue) - convertNumber($billValue + $opValue)) - ( convertNumber($expensValue) - convertNumber($paisValue) ); return $difference; } function partner_isBadPayer( $partnerid ) { $query = "SELECT * FROM `marked_partners` WHERE `partnerid`='$partnerid' LIMIT 1"; mysql_query( $query ) or die(mysql_error()); return ( mysql_affected_rows() != 0 ); } function bc_setContent( $billid , $content ) { $updateQ = "UPDATE `bc` SET `content`='$content' WHERE `id`='$billid' LIMIT 1;"; mysql_query( $updateQ ); } function listCountries() { $selectQ = "SELECT `code` , `name` FROM `world_country` ORDER by `name`"; $selectR = mysql_query( $selectQ ); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $selectR ) ) $countries[ $row["code"] ] = $row; return $countries; } function getCountryNameByCode($code) { $query = "SELECT name FROM `world_country` WHERE `Code`='$code' ORDER by `name`"; $result = mysql_query( $query ) or die(mysql_error()); $r=mysql_fetch_row($result); return $r[0]; } function listCities($country) { $query = "SELECT * FROM `cities_new` WHERE `country`='$country' ORDER by `name` asc"; $result = mysql_query( $query ) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while( $row = mysql_fetch_array( $result ) ) $cities[ $row["id"] ] = $row; } $query = "SELECT * FROM `cities` WHERE `country`='$country' ORDER by `name` asc"; $result = mysql_query( $query ) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while( $row = mysql_fetch_array( $result ) ) $cities[ $row["id"] ] = $row; } return $cities; } function listCounties($country) { $query = "SELECT * FROM `cities_Counties` WHERE `country`='$country' ORDER by `name` asc"; $result = mysql_query( $query ) or die(mysql_error()); if($result&& mysql_num_rows($result) >0 ) { while( $row = mysql_fetch_array( $result ) ) $cities[ $row["id"] ] = $row; } return $cities; } function getVarosok() { $query="SELECT * FROM `cities` order by `id`"; $result = mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while( $row = mysql_fetch_array( $result ) ) { $list[ $row["id"] ] = $row; } } $query="SELECT * FROM `cities_new` order by `id`"; $result = mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while( $row = mysql_fetch_array( $result ) ) { $list[ $row["id"] ] = $row; } } return $list; } //adott id varos kivevese function getCityNameById($id) { if($id>10000) $query = "SELECT `name` FROM `cities_new` WHERE `id`='$id' ORDER by `id`"; else $query = "SELECT `name` FROM `cities` WHERE `id`='$id' ORDER by `id`"; $result = mysql_query( $query ) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $r=mysql_fetch_array($result); return $r['name']; } function generateCode($characters) { $possible = '23456789bcdfghjkmnpqrstvwxyz'; $code = ''; $i = 0; while ($i < $characters) { $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1); $i++; } return $code; } function bc_removeBc( $bcid ) { $deleteQ = "DELETE FROM `bc` WHERE `id`='$bcid' LIMIT 1;"; mysql_query( $deleteQ ); return mysql_affected_rows(); } function bc_addBc( $from , $to , $items ) { $query = "INSERT INTO `bc` ( `id` , `userid` , `srcid` , `destid` , `ondate` , `fulfilled` ) VALUES ( NULL , '".$_SESSION["user"]["id"]."', '$from', '$to', NOW(), '0' );"; mysql_query( $query ) or die(mysql_error()); $index = mysql_insert_id(); foreach( $items as $key => $value ) bc_addBcItem( $index , $key , $value["quantity"] , $value["modelid"] , $value["price"] ); return $index; } function bc_addBcItem( $bcid , $itemid , $quantity , $modelid , $price) { $query = "INSERT INTO `bc_items` ( `id` , `bcid` , `itemid` , `quantity` , `fulfilled` ,`modelid` ,`price`) VALUES ( NULL , '$bcid', '$itemid', '$quantity', '0','$modelid','$price' );"; mysql_query( $query ) or die(mysql_error()); } function bc_delBc( $bcid ) { $query = "DELETE FROM bc WHERE id = $bcid"; mysql_query ($query) or die(mysql_error()); } function aviz_addAviz( $from , $to , $items , $bcid , $content ) { $query = "INSERT INTO `aviz` ( `id` , `userid` , `srcid` , `destid` , `ondate` ,`bcid` , `content`) VALUES ( NULL , '".$_SESSION["user"]["id"]."', '$from', '$to', NOW(),'$bcid','$content' );"; mysql_query( $query ) or die(mysql_error()); $index = mysql_insert_id(); foreach( $items as $key => $value ) aviz_addAvizItem( $index , $key , $value["destquantity"] , $value["modelid"] , $value["price"] ); return $index; } function aviz_modAviz( $from , $to , $bcid , $content,$id ) { $query =" UPDATE `aviz` SET `content`='$content' WHERE `id`='$id'"; mysql_query( $query ) or die(mysql_error()); } function aviz_addAvizItem( $avizid , $itemid , $quantity , $modelid , $price ) { $query = "INSERT INTO `aviz_items` ( `id` , `avizid` , `itemid` , `quantity` , `modelid` ,`price`) VALUES ( NULL , '$avizid', '$itemid', '$quantity', '$modelid','$price' );"; mysql_query( $query ) or die(mysql_error()); } function bc_getBCs( $stockid , $status ) { $query = "SELECT `bc`.* FROM `bc`, `stocks` WHERE `srcid` in (SELECT `id` FROM `stocks` WHERE `locid`='$stockid') AND `fulfilled`='$status' order by `ondate` desc"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $bcs[ $row["id"] ] = $row; return $bcs; } function bc_getBC( $bcid ) { $query = "SELECT * FROM `bc` WHERE `id`=$bcid"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function bc_getBcItems( $bcid ) { $query = "SELECT * FROM `bc_items` WHERE `bcid`=$bcid"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $bcitems[ $row["id"] ] = $row; foreach( $bcitems as $key => $value ) { $query = "SELECT * FROM `stock_items` WHERE `id`=".$value["itemid"].""; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); $query = "SELECT * FROM `container` WHERE `id`=".$value["modelid"].""; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); $bcitems[ $key ]["itemname"] = $row["name"]; } return $bcitems; } function bc_fulFill( $bcid , $items ) { $query = "UPDATE `bc` SET `fulfilled`=1 WHERE `id`=$bcid LIMIT 1"; mysql_query( $query ) or die(mysql_error()); foreach( $items as $key => $value ) { $query = "UPDATE `bc_items` SET `fulfilled`=".$value["destquantity"]." WHERE `id`=".$value["bcitemid"]." LIMIT 1"; mysql_query( $query ) or die(mysql_error()); } } function bc_listBC ($pageNo = -1, $orderby = "DESC") { $query = "SELECT * FROM bc ORDER BY ondate $orderby"; if ($pageNo > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageNo - 1) * $count; $query = $query . " LIMIT $from, $count"; } $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $list [$row ["id"]] = $row; return $list; } /*function bc_listBC () { $query = "SELECT * FROM bc"; $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $bill_list [$row ["id"]] = $row; return $bill_list; }*/ // document functions function document_askCancelDoc( $docid , $doctype , $userid ) { $insertQ = "INSERT INTO `cancellings` ( `id` , `docid` , `doctype` , `userid` , `reqdate` , `dirid` , `stat` , `ondate` ) VALUES ( NULL , '$docid', '$doctype', '$userid', NOW( ) , '$dirid', 0, NULL ); "; mysql_query( $insertQ ); if( mysql_affected_rows() <= 0 )return NULL; return mysql_insert_id(); } function document_getCancelRequest( $doctype ) { $query = "SELECT * FROM `cancellings` WHERE `doctype`='$doctype'"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $dox[ $row["id"] ] = $row; return $dox; } return NULL; } function document_cancelDoc( $docid ) { $updateQ = "UPDATE `cancellings` SET `ondate` = NOW() , `dirid`=".$_SESSION["user"]["id"]." , `stat`=1 WHERE `id`='$docid' LIMIT 1"; mysql_query( $updateQ ) or die(mysql_error()); } // template functions function selectTemplate($typeId,$viewall,$userid) { if($viewall!="1") { $viewquery= " AND ( `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) ) "; } $result = mysql_query("select `id` from `documents_template` where type='$typeId' and active='1' $viewquery") or die(mysql_error()); if ($result) $row = mysql_fetch_array($result); $templateId = $row["id"]; return $templateId; } function listTemplate( $orderby, $ordermode, $pagetoshow = -1,$viewall="0",$userid="0" ) { if($viewall!="1") { $viewquery= " AND ( `d`.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) ) "; } $query = "SELECT `d`.*, `dt`.name as typeName FROM documents_template d, documents_template_type dt WHERE d.type = dt.id $viewquery ORDER BY `d`.$orderby $ordermode"; if ($pagetoshow != -1) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pagetoshow - 1) * $count; $query .= " LIMIT $from, $count"; } $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $list [$row ["id"]] = $row; return $list; } function listTemplateFilterTypes( $orderby, $ordermode, $pagetoshow = -1, $type,$viewall,$userid) { if($viewall!="1") { $viewquery= " AND ( `d`.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) ) "; } $query = "SELECT `d`.*, `dt`.name as typeName FROM documents_template d, documents_template_type dt WHERE d.type = dt.id and d.type = '$type' $viewquery ORDER BY `d`.$orderby $ordermode"; if ($pagetoshow != -1) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pagetoshow - 1) * $count; $query .= " LIMIT $from, $count"; } $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $list [$row ["id"]] = $row; return $list; } function listTemplateTypes( $orderby, $ordermode, $pagetoshow = -1 ) { $query = "SELECT `dt`.* FROM documents_template_type dt ORDER BY `dt`.$orderby $ordermode"; if ($pagetoshow != -1) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pagetoshow - 1) * $count; $query .= " LIMIT $from, $count"; } $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $list [$row ["id"]] = $row; return $list; } function modifyTemplate($id,$content,$name,$type,$keyword,$lang,$header,$footer,$watermark,$departament) { $query = "update `documents_template` set `content` = '$content', `name` = '$name', `type`='$type', `keyword`='$keyword', `lang`='$lang',`header`='$header',`footer`='$footer',`watermark`='$watermark', `departament`='$departament' where id = '$id'"; $result=mysql_query($query) or die(mysql_error()); if($result) { return true; } } function loadFullTemplate($templateId) { $query="select * from `documents_template` where id='$templateId'"; $result = mysql_query( $query ) or die(mysql_error()); if ($result) { $ertek=0; $row = mysql_fetch_array($result); $loadedTemplate=$row; return $loadedTemplate; } } function loadTemplate($templateId) { $result = mysql_query("select `content` from `documents_template` where id='$templateId'"); if ($result) { $ertek=0; $row = mysql_fetch_array($result); $loadedTemplate=$row["content"]; return $loadedTemplate; } } function imageReplaceToText($rootFolder,$loadedTemplate,$imageLink,$variable) { $documentLength = strlen($loadedTemplate); $posn=strpos($loadedTemplate,$imageLink); if($posn!==FALSE) { $pos1=strrpos(substr($loadedTemplate,0,$posn), "",$pos1); if(strpos($imageLink,"facturarii")!==FALSE) { } $loadedTemplate=str_replace(substr($loadedTemplate,$pos1,($pos2-$pos1)+2),$variable,$loadedTemplate); } return $loadedTemplate; } //factura function factura_addInvoice( $clientid , $serial , $number, $amount , $total , $paidby , $desc , $content ) { $content = addslashes ($content); $query = "INSERT INTO `invoices` ( `id` , `clientid` , `serial` , `number` , `amount` , `total` , `paidby` , `ondate` , `desc` , `userid` , `content` , `printed` ,`closed`,`active` ) VALUES ( NULL , '$clientid', '$serial', '$number', '$amount', '$total', '$paidby', NOW( ) , '$desc', '".$_SESSION["user"]["id"]."', '$content','0','0','1')"; mysql_query( $query ) or die(mysql_error()); $invoiceid = mysql_insert_id(); return $invoiceid; } function factura_UnpaidFacturaRestanta() { $query="SELECT * FROM `partners`"; $result=mysql_query( $query ) or die(mysql_error()); $i=0; while( $row=mysql_fetch_array($result) ) { $balance = partner_getBalance($row["id"]); if($balance>$row["limit"] && $row["limit"]!=0) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=2;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } return $list; } function partener_ExpiredBirthDay() { $query="SELECT * FROM `partners` WHERE `cnp` is not NULL "; $result=mysql_query( $query ) or die(mysql_error()); $i=0; while( $row=mysql_fetch_array($result) ) { if($row["birthdate"]!='' && $row["birthdate"]!=NULL && $row["birthdate"]!='0000-00-00') if(abs(subtract_dates(date("Y")."-".substr($row["birthdate"],5,5), date("Y-m-d")))<=$_SESSION["settings"]["avertizareBirthDay"]) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=14;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub>=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } return $list; } function factura_modInvoice( $invoiceid , $clientid , $serial , $number, $amount , $total , $paidby , $desc , $content ) { $query = "UPDATE `invoices` SET `clientid` = '$clientid', `serial` = '$serial', `number` = '$number', `amount` = '$amount', `total` = '$total', `paidby` = '$paidby', `ondate` = NOW(), `desc` = '$desc', `content` = '$content' WHERE `invoices`.`id` = $invoiceid LIMIT 1 ;"; mysql_query( $query ) or die(mysql_error()); } function factura_invoiceSetPrinted( $id , $value ) { $updateQ = "UPDATE `invoices` SET `printed` = '$value' WHERE `invoices`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ); } function factura_invoiceSetClosed( $id , $value ) { $updateQ = "UPDATE `invoices` SET `closed` = '$value' WHERE `invoices`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ); } function factura_invoiceSetActiveNess( $invoiceid , $state ) { $update = "UPDATE `invoices` SET `active`='$state' WHERE `id`='$invoiceid' LIMIT 1;"; mysql_query( $update ); } function factura_addFactura( $clientid , $userid , $stockid , $rawvalue , $value , $serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei, $onValuta , $cursValue, $commandId, $commandIdAdv, $fromActid, $punct,$fromActidAdv,$type,$hrId,$carId,$expeditia,$nrTemplate,$depid) { $content = addslashes ($content); $insertQ = "INSERT INTO `facturi` ( `id` , `clientid` , `userid` , `stockid` , `rawvalue` , `value` , `serial`,`number`,`content` , `printed` , `closed` ,`ondate`,`active`,`paymode`, `termenDePlata`, `dataExecutiei`, `onValuta` , `cursValue` , `fromActId` , `fromActAdvId`, `punctDeLucru`,`type`,`persoanaId`,`carId`,`transport`,`nrTemplate`,`departament`) VALUES ( NULL , '$clientid', '$userid', '$stockid', '$rawvalue', '$value', '$serial','$number','$content', '0', '0',NOW(),'1','$paymode' , '$termenDePlata', '$dataExecutiei' , '$onValuta' , '$cursValue' , '$fromActid' , '$fromActidAdv', '$punct','$type','$hrId','$carId','$expeditia','$nrTemplate','$depid'); "; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function factura_isOnFactura($commid, $prodid) { $query="select * from `facturi_items` fi, `facturi` f where fi.stockItem='$prodid' and fi.factid=f.id and f.fromActAdvId='$commid' and f.active='1' and f.type='1'; "; $result=mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)==0) return false; return true; } function aviz_isOnAviz($commid, $prodid) { $query="select * from `avizeOutItems` fi, `avizeOut` f where fi.stockItem='$prodid' and fi.factid=f.id and f.fromActAdvId='$commid' and f.active='1'; "; $result=mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)==0) return false; return true; } function bon_addFactura( $clientid , $userid , $stockid , $rawvalue , $value , $serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei, $onValuta , $cursValue, $commandId, $commandIntId,$commnadcontent, $date) { $u= users_getUser($userid); if ($date=='') $date="NOW()"; else $date="DATE_ADD('".$date."', INTERVAL 1 SECOND)"; $content = addslashes ($content); $insertQ = "INSERT INTO `bonConsum` ( `id` , `userid` , `stockid` , `rawvalue` , `value` , `number`,`content` , `printed` , `closed` ,`ondate`,`active`,`fromActAdvId`,`fromActComInt`,`comments`,`loc_id`) VALUES ( NULL , '$userid', '$stockid', '$rawvalue', '$value', '$number','$content', '0', '0',$date,'1','$commandId', '$commandIntId', '$commnadcontent','".$u['defstock']."'); "; mysql_query( $insertQ ) or die($insertQ." ".mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function factura_registerItems( $factid , $modelid , $price , $natprice , $quantity ,$um,$period,$priceWithoutTva,$tva,$editTva, $type, $rowName, $cursValue, $start, $end, $weeknr,$type_product , $stockItem) { $query = "INSERT INTO facturi_items VALUES (NULL, '$factid', '$modelid', '$price', '$natprice' , '$quantity', '$um','$period','$priceWithoutTva','$tva','$editTva', '$type' , '$rowName', NOW(), '$cursValue', '$start', '$end', '$weeknr', '$type_product','$stockItem');"; mysql_query( $query ) or die($query.mysql_error()); } function bon_registerItems( $factid , $modelid , $price , $natprice , $quantity , $type, $rowName , $quantityType , $stockid, $date ) { if ($date=='') $date="NOW()"; else $date="DATE_ADD('".$date."', INTERVAL 1 SECOND)"; $query = "INSERT INTO bonConsum_items VALUES (NULL, '$factid', '$modelid', '$price', '$natprice' , '$quantity', '$type' , '$rowName', $date , '' , '$quantityType','$stockid');"; mysql_query( $query ) or die($query." ".mysql_error()); } function factura_deactivateBills( $factid ) { $update = "UPDATE `bills` SET `active`=0 WHERE `factid`='$factid';"; mysql_query( $update ) or die(mysql_error()); } function factura_setActiveNess( $factid , $state ) { $update = "UPDATE `facturi` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ); if( $state == 0 )factura_deactivateBills( $factid ); } function bon_setActiveNess( $factid , $state ) { $update = "UPDATE `bonConsum` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ); //if( $state == 0 )factura_deactivateBills( $factid ); } function factura_setInvoiceActiveNess( $invid , $state ) { $update = "UPDATE `invoices` SET `active`='$state' WHERE `id`='$invid' LIMIT 1;"; mysql_query( $update ); } function factura_modFactura( $id , $clientid , $userid , $stockid , $rawvalue , $value ,$serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei , $onValuta , $cursValue,$hrId,$carId,$expeditia,$nrTemplate,$depid) { if($termenDePlata==NULL) $termenDePlata="0000-00-00"; if($dataExecutiei==NULL) $dataExecutiei="0000-00-00"; $content = addslashes ($content); $updateQ = "UPDATE `facturi` SET `clientid` = '$clientid', `userid` = '$userid', `stockid` = '$stockid', `rawvalue` = '$rawvalue', `value` = '$value', `serial` = '$serial', `number` = '$number', `paymode` = '$paymode', `termenDePlata` = '$termenDePlata', `dataExecutiei` = '$dataExecutiei', `onValuta` = '$onValuta', `persoanaId` = '$hrId', `carId` = '$carId', `transport` = '$expeditia', `cursValue` = '$cursValue', `nrTemplate` = '$nrTemplate', `departament` = '$depid', `content` = '$content' WHERE `facturi`.id ='$id' LIMIT 1;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function bon_modFactura( $id , $clientid , $userid , $stockid , $rawvalue , $value ,$serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei , $onValuta , $cursValue, $commandComments) { $content = addslashes ($content); $updateQ = "UPDATE `bonConsum` SET `userid` = '$userid', `stockid` = '$stockid', `rawvalue` = '$rawvalue', `value` = '$value', `number` = '$number', `comments` = '$commandComments', `content` = '$content' WHERE `bonConsum`.id ='$id' LIMIT 1;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function factura_setPrinted( $id , $value ) { $updateQ = "UPDATE `facturi` SET `printed` = '$value' WHERE `facturi`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function factura_setRemovedFromStock( $id , $value ) { $updateQ = "UPDATE `facturi` SET `removedFromStock` = '$value' WHERE `facturi`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die($updateQ.mysql_error()); } function bon_setPrinted( $id , $value ) { $updateQ = "UPDATE `bonConsum` SET `printed` = '$value' WHERE `bonConsum`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ); } function factura_setClosed( $id , $value ) { $updateQ = "UPDATE `facturi` SET `closed` = '$value' WHERE `facturi`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function bon_setClosed( $id , $value ) { $updateQ = "UPDATE `bonConsum` SET `closed` = '$value' WHERE `bonConsum`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function insertOP( $factid, $op, $value, $clientid, $userid, $onValuta, $cursValue, $dateTextField, $type, $cursDate) { $plusDate = " ".date("H:i:s"); $query = "INSERT INTO `op` VALUES( NULL, $op , $value, '$dateTextField$plusDate', $factid, $clientid, $userid, '$onValuta', $cursValue, $type, '$cursDate')"; $result = mysql_query( $query ) or die(mysql_error()); } function aviz_setPrinted( $id , $value ) { $updateQ = "UPDATE `aviz` SET `printed` = '$value' WHERE `aviz`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function aviz_setClosed( $id , $value ) { $updateQ = "UPDATE `aviz` SET `closed` = '$value' WHERE `aviz`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ); } function aviz_getAviz( $avizid ) { $query = "SELECT * FROM `aviz` WHERE `id`='$avizid' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() == NULL )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function factura_setSerial( $id , $serial ) { $update = "UPDATE `facturi` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ); } function factura_getFacturi() { $select = "SELECT * FROM `facturi`"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function bon_getFacturi() { $select = "SELECT * FROM `bonConsum`"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function factura_getFactura( $id ) { $select = "SELECT * FROM `facturi` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function bon_getFactura( $id ) { $select = "SELECT * FROM `bonConsum` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function factura_getInvoice( $id ) { $select = "SELECT * FROM `invoices` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function insert_stock_items_out ($userid, $provid, $stockid, $itemid, $quantity, $originalprice, $src , $quantityType, $price, $date) { if ($date=='') $date='NOW()'; else $date="DATE_ADD('".$date."', INTERVAL 1 SECOND)"; $query = "INSERT INTO stock_items_out VALUES (NULL, $date, '$userid', '$provid', '$itemid', '$quantity', '$price', '$src', '$stockid', '$quantityType','$originalprice')"; mysql_query ($query) or die($query." ".mysql_error()); } function insert_stock_items_in ($userid, $provid, $stockid, $itemid, $quantity, $price, $src , $quantityType, $date) { if ($date=='') $date='NOW()'; else $date="DATE_ADD('".$date."', INTERVAL 1 SECOND)"; $query = "INSERT INTO stock_items_in VALUES (NULL, $date, '$userid', '$provid', '$itemid', '$quantity', '$price', '$src', '$stockid', '$quantityType')"; mysql_query( $query ) or die($query." ".mysql_error()); } function factura_remFromStock( $prods , $quants, $inchiriere, $commandid, $punct , $price ) { foreach( $prods as $key => $value ) { $prodid=$prods[$key]; if( $inchiriere[$key]!="inchiriere" ) { $productsList = stock_getProdIdFifoWithoutReserving( $_SESSION["user"]["defstock"] , $prods[$key], $quants[$key] ); if($productsList) foreach( $productsList as $keyProds => $valueProds ) { $selectedProdid = $valueProds; $query = "SELECT * FROM stock_items WHERE id = '$selectedProdid'"; $result = mysql_query( $query ) or die($query.mysql_error()); $row = mysql_fetch_array( $result ); $stockQuantity = $row["quantity"]; $stockQuantityType = $row["quantityType"]; //megnezni mi van kiadva belole if($quants[$key]>$stockQuantity) { $quants[$key] = $quants[$key]-$stockQuantity; $quantityToMinus = $stockQuantity; } else { $quantityToMinus = $quants[$key]; } insert_stock_items_out ($row["userid"], $row["provid"], $row["stockid"], $row["itemid"], $quantityToMinus, $row["price"], $row["src"] , $stockQuantityType , $price[$key],'' ); if ( $quantityToMinus != $stockQuantity ) { $updateQuery = "UPDATE `stock_items` SET `quantity`=ROUND(quantity-".$quantityToMinus.",4) WHERE `id`='$selectedProdid' LIMIT 1"; mysql_query( $updateQuery ) or die($updateQuery.mysql_error()); } else { $deleteQuery = "DELETE FROM `stock_items` WHERE `id`='$selectedProdid' LIMIT 1"; mysql_query( $deleteQuery ) or die($deleteQuery.mysql_error()); } } } else { //uj inchiriere $productsList = stock_getProdIdFifoWithoutReserving( $_SESSION["user"]["defstock"] , $prods[$key], $quants[$key] ); if($productsList) foreach( $productsList as $keyProds => $valueProds ) { $selectedProdid = $valueProds; $query = "SELECT * FROM stock_items WHERE id = '$selectedProdid'"; $result = mysql_query( $query ) or die($query.mysql_error()); $row = mysql_fetch_array( $result ); $stockQuantity = $row["quantity"]; $stockQuantityType = $row["quantityType"]; //megnezni mi van kiadva belole if($quants[$key]>$stockQuantity) { $quants[$key] = $quants[$key]-$stockQuantity; $quantityToMinus = $stockQuantity; } else { $quantityToMinus = $quants[$key]; } //insert_stock_items_out ($row["userid"], $row["provid"], $row["stockid"], $row["itemid"], $quantityToMinus, $row["price"], $row["src"] , $stockQuantityType , $price[$key] ); $stockProdId = $row["itemid"]; if ( $quantityToMinus != $stockQuantity ) { $defStock = $_SESSION["user"]["defstock"]; $query2="INSERT INTO `inchirieri` VALUES('NULL','$stockProdId','$commandid','$punct','$quantityToMinus','$defStock','$selectedProdid')"; $result2=mysql_query( $query2 ) or die($query2.mysql_error()); } else { $defStock = $_SESSION["user"]["defstock"]; $query2="INSERT INTO `inchirieri` VALUES('NULL','$stockProdId','$commandid','$punct','$stockQuantity','$defStock','$selectedProdid')"; $result2=mysql_query( $query2 ) or die($query2.mysql_error()); } } //uj inchiriere vege } } } function factura_remFromStockDirect($key,$quantity, $date) { $query = "SELECT * FROM stock_items WHERE id = '$key'"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); $stockQuantity = $row["quantity"]; $stockQuantityType = $row["quantityType"]; //megnezni mi van kiadva belole if($quantity>$stockQuantity) { $quantity = $quantity-$stockQuantity; $quantityToMinus = $stockQuantity; } else { $quantityToMinus = $quantity; } insert_stock_items_out ($row["userid"], $row["provid"], $row["stockid"], $row["itemid"], $quantityToMinus, $row["price"], $row["src"] , $stockQuantityType , $row["price"], $date ); if ( $quantityToMinus != $stockQuantity ) { $updateQuery = "UPDATE `stock_items` SET `quantity`=ROUND(quantity-".$quantityToMinus.",4) WHERE `id`='$key' LIMIT 1"; mysql_query( $updateQuery ) or die(mysql_error()); } else { $deleteQuery = "DELETE FROM `stock_items` WHERE `id`='$key' LIMIT 1"; mysql_query( $deleteQuery ) or die(mysql_error()); } } function stock_getProdItemid( $prodid ) { $query="SELECT itemid FROM `stock_items` WHERE `id`='$prodid' "; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row["itemid"]; } function stock_getProdQuantity( $prodid ) { $query="SELECT quantity FROM `stock_items` WHERE `id`='$prodid' "; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row["quantity"]; } function stock_getProdQuantityFromItemGeneral( $prodid ) { $query="SELECT quantity FROM `stock_items` WHERE `itemid`='$prodid' and `arrived`='1'"; $result=mysql_query( $query ) or die(mysql_error()); while($row=mysql_fetch_array($result)) { $totalQuantity+=$row["quantity"]; } return $totalQuantity; } function stock_getProdQuantityFromItemStock( $stockid , $prodid ) { $query="SELECT quantity FROM `stock_items` WHERE `itemid`='$prodid' and `stockid`='$stockid' and `arrived`='1'"; $result=mysql_query( $query ) or die(mysql_error()); while($row=mysql_fetch_array($result)) { $totalQuantity+=$row["quantity"]; } return $totalQuantity; } function stock_getProdIdFifo( $stockid , $prodid, $quantity ) { $query="SELECT `si`.* FROM `stock_items` si, `stocks` s WHERE `s`.`locid`='$stockid' AND `s`.`id`=`si`.`stockid` AND `si`.`itemid`='$prodid' and `si`.`arrived`='1' order by `si`.`ondate` ASC"; $counter=1; $result=mysql_query( $query ) or die(mysql_error()); while($row=mysql_fetch_array($result)) { $stockId = $row["stockid"]; $stockIndivQuantity = stock_containsItemGeneral($stockId, $prodid ); $stockIndivInchiriatQuantity = inchirieri_getProdQuantity($stockId,$prodid); if( ($stockIndivQuantity - $stockIndivInchiriatQuantity ) > 0) if( $quantity > 0) { $products[$counter] = $row["id"]; $quantity = $quantity-$row["quantity"]; $counter++; } } if($products) return $products; else return NULL; } function stock_getProdIdFifoWithoutReserving( $stockid , $prodid, $quantity ) { if ($stockid) $stock="`si`.`stockid`='$stockid' AND"; else $stock=''; $query="SELECT `si`.* FROM `stock_items` si, `stocks` s WHERE $stock `s`.`id`=`si`.`stockid` AND `si`.`itemid`='$prodid' and `si`.`arrived`='1' order by `si`.`ondate` ASC"; $counter=1; $result=mysql_query( $query ) or die($query.mysql_error()); while($row=mysql_fetch_array($result)) { $stockId = $row["stockid"]; $stockIndivQuantity = stock_containsItemGeneral($stockid, $prodid ); $stockIndivInchiriatQuantity = inchirieri_getProdQuantity($stockid,$prodid); if( ($stockIndivQuantity ) > 0) if( $quantity > 0) { $products[] = $row["id"]; $quantity = $quantity-$row["quantity"]; $counter++; } } if($products) return $products; else return NULL; } function stock_getProdQuantity1( $id ) { //megkapom h egy kategorian belul hany termek van $query="SELECT * FROM `stock_items` WHERE `itemid`='$id' "; $result=mysql_query( $query ) or die(mysql_error()); $rownum=mysql_num_rows($result); return $rownum; } function inchirieri_getInchirieri($produsId,$comandaId,$punctDeLucruId,$stockid,$stockProdusId,$user_id,$ondate){ if ($produsId) $prod=" `produsId`='$produsId' "; else $prod='1'; if ($comandaId) $comand="AND `comandaId`='$comandaId' "; else $comand=''; if ($punctDeLucruId) $pl=" AND `punctDeLucruId`='$punctDeLucruId' "; else $pl=''; if ($stockid) $stok=" AND `stockid`='$dtockid' "; else $stok=''; if ($stockProdusId) $sp=" AND `stockProdusId`='$stockProdusId' "; else $sp=''; if ($user_id) $ui=" AND `user_id`='$user_id' "; else $ui=''; if ($ondate) $date=" AND `ondate`='$ondate' "; else $date=''; $query="SELECT * FROM `inchirieri` WHERE $prod $comand $pl $stok $sp $ui $ondate"; $result=mysql_query($query) or die(mysql_error()); $lista=array(); while($rows=mysql_fetch_array($result)){ $lista[]=$rows; } return $lista; } function inchirieri_getProdQuantity( $stockid, $id ) { if ($stockid) $stock="and `stockid`='$stockid'"; else $stock=''; $query="SELECT quantity FROM `inchirieri` WHERE `produsId` = '$id' $stock"; $result=mysql_query( $query ) or die(mysql_error()); $quan=0; while($row=mysql_fetch_array($result)) { $quan+=$row["quantity"]; } $query2="SELECT quantity FROM `rezervareProdus` WHERE `produsId` = '$id' and `stockid`='$stockid'"; $result2=mysql_query( $query2 ) or die(mysql_error()); while($row2=mysql_fetch_array($result2)) { $quan+=$row2["quantity"]; } return $quan; } function inchirieri_getProdQuantityLocation( $locid, $id ) { $query="SELECT quantity FROM `inchirieri` i, `stocks` s WHERE `i`.`produsId` = '$id' and `i`.`stockid`=`s`.`id` AND `s`.`locid`='$locid'"; $result=mysql_query( $query ) or die(mysql_error()); $quan=0; while($row=mysql_fetch_array($result)) { $quan+=$row["quantity"]; } $query2="SELECT quantity FROM `rezervareProdus` r, `stocks` s WHERE `r`.`produsId` = '$id' and `r`.`stockid`=`s`.`id` AND `s`.`locid`='$locid'"; $result2=mysql_query( $query2 ) or die(mysql_error()); while($row2=mysql_fetch_array($result2)) { $quan+=$row2["quantity"]; } return $quan; } function inchirieri_getProdQuantityExactStock( $stockid, $id , $stockitemid ) { $query="SELECT quantity FROM `inchirieri` WHERE `produsId` = '$id' and `stockid`='$stockid' and `stockProdusId`='$stockitemid'"; $result=mysql_query( $query ) or die(mysql_error()); $quan=0; while($row=mysql_fetch_array($result)) { $quan+=$row["quantity"]; } $query2="SELECT quantity FROM `rezervareProdus` WHERE `produsId` = '$id' and `stockid`='$stockid' and `stockProdusId`='$stockitemid'"; $result2=mysql_query( $query2 ) or die(mysql_error()); while($row2=mysql_fetch_array($result2)) { $quan+=$row2["quantity"]; } return $quan; } function inchirieri_remove_inchirieri($q){ if ($q){ $query="DELETE FROM `inchirieri` WHERE $q"; return mysql_query( $query ) or die(mysql_error()); }else return 0; } function inchirieri_modificare_inchirieri($id,$quantity,$hr){ $query="UPDATE `inchirieri` SET `quantity`='$quantity', `user_id`='$hr' WHERE `id`='$id'"; return mysql_query( $query ) or die(mysql_error()); } function inchirieri_insert_inchirieri($prodid,$punct,$quantity,$hr,$stock_id,$stock_item){ $query="INSERT INTO `inchirieri` (`produsID`,`punctDeLucruId`,`quantity`,`stockid`,`stockProdusId`,`user_id`,`ondate`) VALUES ('$prodid','$punct','$quantity','$stock_id','$stock_item','$hr',NOW())"; return $result=mysql_query( $query ) or die(mysql_error()); } function inchirieri_getProdQuantityExactStockWithoutStock( $id , $stockitemid ) { $query="SELECT `quantity` FROM `inchirieri` WHERE `produsId` = '$id' and `stockProdusId`='$stockitemid'"; $result=mysql_query( $query ) or die(mysql_error()); $quan=0; while($row=mysql_fetch_array($result)) { $quan+=$row["quantity"]; } $query2="SELECT quantity FROM `rezervareProdus` WHERE `produsId` = '$id' and `stockid`='$stockid' and `stockProdusId`='$stockitemid'"; $result2=mysql_query( $query2 ) or die(mysql_error()); while($row2=mysql_fetch_array($result2)) { $quan+=$row2["quantity"]; } return $quan; } function inchirieri_getProdQuantityFromItemGeneral( $id ) { $query="SELECT `i`.`quantity` FROM `inchirieri` i, `stock_items` s WHERE i.`produsId`='$id' and s.`itemid` = i.`produsId` and s.`arrived`='1' GROUP by i.`id`"; $result=mysql_query( $query ) or die(mysql_error()); $quan=0; while($row=mysql_fetch_array($result)) { $quan+=$row["quantity"]; } $query="SELECT `r`.`quantity` FROM `rezervareProdus` r, `stock_items` s WHERE r.`produsId`='$id' and s.`itemid` = r.`produsId` and s.`arrived`='1' GROUP by r.`id`"; $result=mysql_query( $query ) or die(mysql_error()); while($row=mysql_fetch_array($result)) { $quan+=$row["quantity"]; } return $quan; } function inchirieri_getProdQuantityFromItemStock( $stockid , $id ) { $query="SELECT `i`.`quantity` FROM `inchirieri` i, `stock_items` s WHERE s.`stockid`='$stockid' and i.`itemid`='$id' and s.`produsId` = i.`id` and s.`arrived`='1'"; $result=mysql_query( $query ) or die(mysql_error()); $quan=0; while($row=mysql_fetch_array($result)) { $quan+=$row["quantity"]; } return $quan; } function bon_remFromStock( $prods , $quants ) { foreach( $prods as $key => $value ) { $query = "SELECT `quantity`,`quantityType` FROM stock_items WHERE id = $key"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); $stockQuantity = $row["quantity"]; $stockQuantityType = $row["quantityType"]; if ( $quants[ $key ] < $stockQuantity ) { $updateQuery = "UPDATE `stock_items` SET `quantity`=ROUND(quantity-".$quants[ $key ].",4) WHERE `id`='$key' LIMIT 1"; mysql_query( $updateQuery ); } else /* $quants == $quant_curr */ { $deleteQuery = "DELETE FROM `stock_items` WHERE `id`='$key' LIMIT 1"; mysql_query( $deleteQuery ); } insert_stock_items_out ($value ["userid"], $value ["provid"], $value ["stockid"], $value ["itemid"], $quants[ $key ], $value ["price"], $value ["src"] , $stockQuantityType , $date); } } function factura_searchGenerateQuery( $searchval ,$servicename, $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $id,$punctdelucru_filter, $type,$viewall=1,$userid=0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($viewall!="1") { $viewquery= " AND ( f.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid') "; } if($servicename!="") $servicequery=" AND (f.`id` IN (SELECT `factid` FROM `facturi_items` WHERE `rowName` LIKE '%$servicename%' AND `quantity` !='0') )"; if($punctdelucru_filter!=NULL) { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`number` = '$searchval'"; else if ($searchcriteria == "serial_command" && $searchval!=NULL){ $q="SELECT * FROM `comandaForClientAdv` WHERE `firstserial`='0' AND `secondserial`='$searchval'"; $fact=mysql_fetch_array(mysql_query($q)); if ($fact) $plus_search="AND `f`.`fromActAdvId` LIKE '%".$fact['id'].", %' OR `f`.`fromActAdvId`='".$fact['id']."'"; else $plus_search=" AND (`f`.`fromActAdvId`='x')"; } else $plus_search=" AND (`p`.`name` LIKE '%$searchval%' OR `p`.`cui` LIKE '%$searchval%' OR `p`.`cnp` LIKE '%$searchval%') "; $query = "SELECT `c`.* FROM `comandaForClientAdv` c WHERE `locationId`='$punctdelucru_filter'"; $result = mysql_query($query) or die(mysql_error()); $punctdelucruQuery=""; while($row = mysql_fetch_array( $result )) { $punctdelucruQuery.=" OR `f`.fromActAdvId = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.fromActAdvId = '-1'".$punctdelucruQuery.") AND `f`.active = '1' ".$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu == "platite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`number` = '$searchval'"; else if ($searchcriteria == "serial_command" && $searchval!=NULL){ $q="SELECT * FROM `comandaForClientAdv` WHERE `firstserial`='0' AND `secondserial`='$searchval'"; $fact=mysql_fetch_array(mysql_query($q)); if ($fact) $plus_search="AND `f`.`fromActAdvId` LIKE '%".$fact['id'].", %' OR `f`.`fromActAdvId`='".$fact['id']."'"; else $plus_search=" AND (`f`.`fromActAdvId`='x') "; } else $plus_search=" AND (`p`.`name` LIKE '%$searchval%' OR `p`.`cui` LIKE '%$searchval%' OR `p`.`cnp` LIKE '%$searchval%') "; $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' AND `f`.`rawvalue`!='0' ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'".$viewquery.$servicequery." ORDER BY $orderby $ordermode"; $result = mysql_query($query) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { if(convertNumber($pais[ $row["id"] ]["paid"])==convertNumber($row["value"] * $row["cursValue"])||$pais[ $row["id"] ]["value"]==$row["value"]) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1'".$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu == "neplatite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`number` = '$searchval'"; else if ($searchcriteria == "serial_command" && $searchval!=NULL){ $q="SELECT * FROM `comandaForClientAdv` WHERE `firstserial`='0' AND `secondserial`='$searchval'"; $fact=mysql_fetch_array(mysql_query($q)); if ($fact) $plus_search="AND `f`.`fromActAdvId` LIKE '%".$fact['id'].", %' OR `f`.`fromActAdvId`='".$fact['id']."'"; else $plus_search=" AND (`p`.`name` LIKE '%$searchval%' OR `p`.`cui` LIKE '%$searchval%' OR `p`.`cnp` LIKE '%$searchval%') "; } else $plus_search=" AND (`p`.`name` LIKE '%$searchval%' OR `p`.`cui` LIKE '%$searchval%' OR `p`.`cnp` LIKE '%$searchval%') "; $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'".$viewquery.$servicequery." ORDER BY $orderby $ordermode"; $result = mysql_query($query) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { //fizetve if(convertNumber($pais[ $row["id"] ]["paid"])!=convertNumber($row["value"] * $row["cursValue"])&&$pais[ $row["id"] ]["value"]!=$row["value"]) if(factura_getStornedFactura($row["id"])!=1) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.`value`>='0' AND `f`.active = '1'".$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu == "expirate") { //$TotalMenuSql=" AND termenDePlata < NOW() "; //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`number` = '$searchval'"; else if ($searchcriteria == "serial_command" && $searchval!=NULL){ $q="SELECT * FROM `comandaForClientAdv` WHERE `firstserial`='0' AND `secondserial`='$searchval'"; $fact=mysql_fetch_array(mysql_query($q)); if ($fact) $plus_search="AND `f`.`fromActAdvId` LIKE '%".$fact['id'].", %' OR `f`.`fromActAdvId`='".$fact['id']."'"; else $plus_search=" AND (`f`.`fromActAdvId`='x') "; } else $plus_search=" AND (`p`.`name` LIKE '%$searchval%' OR `p`.`cui` LIKE '%$searchval%' OR `p`.`cnp` LIKE '%$searchval%') "; $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND `termenDePlata` <= NOW()".$viewquery.$servicequery." ORDER BY $orderby $ordermode"; $result = mysql_query($query) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { //fizetve if(convertNumber($pais[ $row["id"] ]["paid"])!=convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1'".$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu != "platite" && $filter_menu != "neplatite" && $filter_menu != "expirate" && $punctdelucru_filter==0) { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial" && $searchval!=NULL) { $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE `f`.`number` = '$searchval' AND `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql.$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } else if ($searchcriteria == "serial_command" && $searchval!=NULL){ $q="SELECT * FROM `comandaForClientAdv` WHERE `firstserial`='0' AND `secondserial`='$searchval'"; $fact=mysql_fetch_array(mysql_query($q)); if ($fact){ $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE (`f`.`fromActAdvId` LIKE '%".$fact['id'].", %' OR `f`.`fromActAdvId`='".$fact['id']."') AND `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql.$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; }else $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE `f`.`fromActAdvId`='x' AND `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql.$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } else if ( $searchcriteria == "id" ) { $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' AND `f`.`id`='$id'".$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } else $query = "SELECT `f`.*, `p`.`name`, `p`.`address` FROM `facturi` f, `partners` p WHERE (`p`.`name` LIKE '%$searchval%' OR `p`.`cui` LIKE '%$searchval%' OR `p`.`cnp` LIKE '%$searchval%') AND `p`.`id` = `f`.`clientid` AND `f`.`type` = '$type' AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql.$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } return $query; } function bon_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu != "platite" && $filter_menu != "neplatite" && $filter_menu != "expirate") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial" && $searchval!=NULL) $query = "SELECT `f`.* FROM `bonConsum` f WHERE `f`.`number` = '$searchval' AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; else $query = "SELECT `f`.* FROM `bonConsum` f WHERE `ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; } return $query; } function bon_searchGenerateQueryXls( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu != "platite" && $filter_menu != "neplatite" && $filter_menu != "expirate") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial" && $searchval!=NULL) $query = "SELECT `fi`.*, `fi`.`stock_id`,`f`.`number`,`f`.`printed`,`f`.`closed`,`f`.ondate as Date, `f`.`active`, `f`.`comments`, `f`.`fromActAdvId`,`f`.`fromActComInt`,`f`.`userid` FROM `bonConsum` f , `bonConsum_items` fi WHERE `f`.`number` = '$searchval' AND `fi`.`factid`=`f`.`id` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." GROUP BY `fi`.`id` ORDER BY `f`.$orderby $ordermode"; else $query = "SELECT `fi`.*, `fi`.`stock_id`,`f`.`number`,`f`.`printed`,`f`.`closed`,`f`.ondate as Date, `f`.`active`, `f`.`comments`, `f`.`fromActAdvId`,`f`.`fromActComInt`,`f`.`userid` FROM `bonConsum` f , `bonConsum_items` fi WHERE `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND `fi`.`factid`=`f`.`id` ".$filterMenuSql." GROUP BY `fi`.`id` ORDER BY `f`.$orderby $ordermode"; } return $query; } function invoice_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate ) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; //$fromDate = mysql_prevDay( $fromDate ); $toDate = mysql_nextDay( $toDate ); if ($searchcriteria == "serial") $query = "SELECT `f`.*, `p`.`name` FROM `invoices` f, `partners` p WHERE `f`.`number` = '$searchval' AND `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode LIMIT $from, $count"; else $query = "SELECT `f`.*, `p`.`name` FROM `invoices` f, `partners` p WHERE `p`.`name` LIKE '%$searchval%' AND `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode LIMIT $from, $count"; return $query; } function factura_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function bon_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function factura_searchFactura( $query ) { $result = mysql_query( $query ) or die($query.mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function bon_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function factura_searchInvoice( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows () < 1 )return NULL; while( $row = mysql_fetch_array ( $result ) ) { $invoices[ $row ["id"] ] = $row; } return $invoices; } function factura_setBillActiveNess( $billid , $state ) { $updateQ = "UPDATE `bills` SET `active`='$state' WHERE `id`='$billid' LIMIT 1;"; mysql_query( $updateQ ) or die(mysql_error()); } function factura_searchBill( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if (mysql_affected_rows () < 1) return NULL; while ($row = mysql_fetch_array ($result)) { $facturi [$row ["id"]] = $row; } return $facturi; } function factura_addChitanta( $clientid , $userid , $factid , $value , $svalue , $serial , $number , $content , $invoiceid,$onValuta,$cursValue,$depid,$dpid) { $content = addslashes ($content); $query = "INSERT INTO `bills` ( `id` , `clientid` , `userid` , `factid` , `value` , `svalue`,`onValuta`, `cursValue` , `serial`,`number`,`ondate` , `content` ,`printed`,`closed`,`active`,`invoiceid`,`fromdp`,`departament`) VALUES ( NULL , '$clientid', '$userid', '$factid', '$value', '$svalue','$onValuta','$cursValue','$serial','$number', NOW( ) , '$content','0','0','1' ,'$invoiceid','$dpid','$depid'); "; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function factura_modChitanta( $chitid , $clientid , $userid , $factid , $value , $svalue , $serial , $number , $content , $invoiceid,$depid) { $query = "UPDATE `bills` SET `clientid` = '$clientid', `userid` = '$userid', `factid` = '$factid', `value` = '$value', `svalue` = '$svalue', `serial` = '$serial', `number` = '$number', `invoiceid` = '$invoiceid', `ondate` = NOW(), `departament` = '$depid', `content` = '$content' WHERE `bills`.`id` ='$chitid' LIMIT 1 ; "; mysql_query( $query ) or die(mysql_error()); } function factura_lockChitanta( $billid ) { $query = "UPDATE `bills` SET `printed`=1 , `closed`=1 WHERE `id`='$billid' LIMIT 1"; mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows(); } function factura_searchBillQueryGenerator ($searchval, $searchcriteria, $page, $from, $to, $orderby,$ordermode,$viewall=1,$userid=0,$punctdelucru_filter) { $fromLimit = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $to = mysql_nextDay( $to ); $count = $_SESSION["settings"]["searchcount"]; if($viewall!="1") { $viewquery= " AND ( f.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid') "; } if($punctdelucru_filter!=NULL) { $query = "SELECT `c`.* FROM `comandaForClientAdv` c WHERE `locationId`='$punctdelucru_filter'"; $result = mysql_query($query) or die(mysql_error()); $punctdelucruQuery=""; while($row = mysql_fetch_array( $result )) { $punctdelucruQuery.=" OR `fact`.fromActAdvId = ".$row["id"]." "; } } else { $punctdelucruQuery=" OR `fact`.fromActAdvId !='-1'"; } if ($searchcriteria == "serial") $query = "SELECT `f`.*, `p`.`name` FROM `bills` f, `partners` p WHERE (`f`.`number` = '$searchval' OR `f`.serial = '$searchval' )AND `p`.`id` = `f`.`clientid` AND `f`.value > 0".$viewquery." ORDER BY $orderby $ordermode LIMIT $fromLimit, $count"; else $query = "SELECT `f`.*, `p`.`name` FROM `bills` f, `partners` p, `facturi` fact WHERE `p`.`name` LIKE '%$searchval%' AND `p`.`id` = `f`.`clientid` AND `f`.value > 0 AND `f`.`factid` = `fact`.`id` AND `f`.`ondate` BETWEEN '$from' AND '$to'".$viewquery." AND (`fact`.fromActAdvId = '-1'".$punctdelucruQuery.") ORDER BY $orderby $ordermode LIMIT $fromLimit, $count"; //echo $query; return $query; } function chitanta_setPrinted( $id , $value ) { $updateQ = "UPDATE `bills` SET `printed` = '$value' WHERE `bills`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function chitanta_setClosed( $id , $value ) { $updateQ = "UPDATE `bills` SET `closed` = '$value' WHERE `bills`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ); } function factura_remBill( $billid ) { $query = "DELETE FROM `bills` WHERE `id`=$billid LIMIT 1"; mysql_query( $billid ); } function factura_getBill( $billid ) { $query = "SELECT * FROM `bills` WHERE `id`=$billid LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() == 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function factura_getBills( $factid ) { $query = "SELECT * FROM `bills` WHERE `factid`='$factid' AND `value` > 0"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) $bills[ $row["id"] ] = $row; return $bills; } } function factura_getBillsBetween( $factid, $fromDate, $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT * FROM `bills` WHERE `factid`='$factid' AND `value` > 0 AND `ondate` BETWEEN '$fromDate' AND '$toDate'"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) $bills[ $row["id"] ] = $row; return $bills; } } function factura_getOps( $orderby, $from, $to, $searchval, $punctdelucru_filter, $ordermode = "desc", $pagetoshow = -1 ) { $to = mysql_nextDay( $to ); if($punctdelucru_filter!=NULL) { $query = "SELECT `c`.* FROM `comandaForClientAdv` c WHERE `locationId`='$punctdelucru_filter'"; $result = mysql_query($query) or die(mysql_error()); $punctdelucruQuery=""; while($row = mysql_fetch_array( $result )) { $punctdelucruQuery.=" OR `f`.fromActAdvId = ".$row["id"]." "; } } else { $punctdelucruQuery=" OR `f`.fromActAdvId !='-1'"; } $query = "SELECT op.id AS id, op.type AS type, p.name AS clientname, u.username AS username, op.value , op.onValuta AS onValuta, op.number AS number, op.ondate AS ondate , op.factid as factid, op.clientid AS clientid, op.cursValue AS cursValue, op.cursValueDate as cursValueDate FROM op, users u, partners p, facturi f WHERE u.id = op.userid AND f.id = op.factid AND p.id = op.clientid AND op.ondate BETWEEN '$from' AND '$to' AND p.name LIKE '%$searchval%' AND (`f`.fromActAdvId = '-1'".$punctdelucruQuery.") ORDER BY $orderby $ordermode"; if( $pagetoshow != -1 ) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pagetoshow - 1) * $count; $query .= " LIMIT $from, $count"; } $result = mysql_query( $query ) or die($query."
".mysql_error()); while( $row = mysql_fetch_array( $result ) ) $list[ $row ["id"] ] = $row; return $list; } function factura_getFacturaOps( $factid ) { $query = "SELECT * FROM `op` WHERE `factid`='$factid'"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; } return NULL; } function factura_getFacturaOpsBetween( $factid, $fromDate, $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT * FROM `op` WHERE `factid`='$factid' AND `ondate` BETWEEN '$fromDate' AND '$toDate'"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; } return NULL; } function factura_getPaidValue( $factid ) { $ins=$_SESSION["bill"]["inserted"]; $select = "SELECT SUM(`value`) as `sum` FROM `bills` WHERE `factid`='$factid' AND `active`='1'"; if($ins!="") $select.=" AND `id` != '$ins'"; $result = mysql_query( $select ) or die(mysql_error()); $sum = 0; if( mysql_affected_rows() > 0 ) { $row = mysql_fetch_array( $result ); $sum = $row["sum"]; } $select = "SELECT SUM(`value`*`cursValue`) as `sum` FROM `op` WHERE `factid`='$factid'"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() > 0 ) { $row = mysql_fetch_array( $result ); $sum += $row["sum"]; } return $sum; } function factura_getPaidValueValuta( $factid ) { $ins=$_SESSION["bill"]["inserted"]; $select = "SELECT SUM(`value`) as `sum` FROM `bills` WHERE `factid`='$factid' AND `active`='1'"; if($ins!="") $select.=" AND `id` != '$ins'"; $result = mysql_query( $select ) or die(mysql_error()); $sum = 0; if( mysql_affected_rows() > 0 ) { $row = mysql_fetch_array( $result ); $sum = $row["sum"]; } $select = "SELECT SUM(`value`) as `sum` FROM `op` WHERE `factid`='$factid'"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() > 0 ) { $row = mysql_fetch_array( $result ); $sum += $row["sum"]; } return $sum; } function factura_getPaidValueInvoice( $invoiceid ) { $select = "SELECT SUM(`value`) as `sum` FROM `bills` WHERE `invoiceid`='$invoiceid' AND `active`='1'"; $result = mysql_query( $select ); $sum = 0; if( mysql_affected_rows() > 0 ) { $row = mysql_fetch_array( $result ); $sum = $row["sum"]; } return $sum; } function factura_getPaidValues() { $query = "SELECT sum( value*cursValue ) as `paid`, `factid`, `value`, `cursValue`,`ondate` FROM `bills` WHERE `active`='1' GROUP BY id"; $results = mysql_query( $query )or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) { if($pais [ $row["factid"] ]==NULL) $pais [ $row["factid"] ] = $row; else { $pais [ $row["factid"] ]["paid"]+=$row["paid"]; $pais [ $row["factid"] ]["value"]+=$row["value"]; $pais [ $row["factid"] ]["ondate"].=",".$row["ondate"]; } } $query = "SELECT `id`, SUM( value * cursValue ) as `paid`, `factid`, `value`, `cursValue`,`ondate` FROM op GROUP BY id"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() ) { while( $row = mysql_fetch_array( $results ) ) $pais2[ $row[ "id" ] ] = $row; foreach( $pais2 as $key => $value ) if( $pais[ $value["factid"] ] == NULL ){ $pais[ $value["factid"] ] = $value;}else {$pais[ $value["factid"] ]["paid"] += $value["paid"]; $pais[ $value["factid"] ]["value"] += $value["value"];$pais [ $value["factid"] ]["ondate"].=",".$value["ondate"];} //ha vannak mar chitantak erre a facturara akkor hozzaadom az op-ket } return $pais; } } function factura_getPaidValuesInterval($from, $to) { $query = "SELECT sum( value ) as `paid`, `factid` FROM `bills` WHERE `active`='1' AND `ondate` BETWEEN '$from' AND '$to' GROUP BY factid"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) $pais [ $row["factid"] ] = $row; $query = "SELECT SUM( value * cursValue ) as `paid`, `factid` FROM op WHERE `ondate` BETWEEN '$from' AND '$to' GROUP BY factid"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() ) { while( $row = mysql_fetch_array( $results ) ) $pais2[ $row[ "factid" ] ] = $row; foreach( $pais2 as $key => $value ) if( $pais[ $key ] == NULL )$pais[ $key ] = $value;else $pais[ $key ]["paid"] += $value["paid"]; //ha vannak mar chitantak erre a facturara akkor hozzaadom az op-ket } return $pais; } } //location and serials function location_addLocation( $array ) { $insertQ = "INSERT INTO `locations` ( `id` , `name` , `type` ,`address`,`judet`,`oras`,`tel`,`fax`) VALUES ( NULL , '".$array["name"]."', '".$array["type"]."','".$array["address"]."','".$array["judet"]."','".$array["oras"]."','".$array["tel"]."','".$array["fax"]."' ); "; mysql_query( $insertQ ); return mysql_insert_id(); } function location_updateLocation( $locid , $array ) { $updateQ = "UPDATE `locations` SET `name`='".$array["name"]."', `type`='".$array["type"]."' , `address`='".$array["address"]."', `judet`='".$array["judet"]."', `oras`='".$array["oras"]."', `tel`='".$array["tel"]."', `fax`='".$array["fax"]."' WHERE `id`=$locid LIMIT 1"; mysql_query( $updateQ ) or die(mysql_error()); } function location_addSerial( $locid , $type , $array ) { $insertQ = "INSERT INTO `serials` ( `id` , `locid` , `type` , `serial` , `number` ,`current`) VALUES ( NULL , '$locid', '$type', '".$array["seria"]."', '".$array["number"]."','".$array["number"]."' );"; mysql_query( $insertQ ); } function location_updateSerial( $locid , $type , $serial , $number ) { //chekc if serial already in use $updateQ = "UPDATE `serials` SET `serial`='$serial',`number`='$number',`current`=$number WHERE `locid`=$locid AND `type`=$type LIMIT 1"; mysql_query( $updateQ ); } function location_getLocation( $locid ) { $select = "SELECT * FROM `locations` WHERE `id`=$locid LIMIT 1;"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function location_getLocations() { $select = "SELECT * FROM `locations`"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $locations[ $row["id"] ] = $row; } return $locations; } function location_getSerial( $locid , $type ) { $select = "SELECT * FROM `serials` WHERE `locid`=$locid AND `type`=$type LIMIT 1"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function location_assignSerial( $userid , $serialtype) { $query = "SELECT l.* FROM `users` u, `locations` l WHERE `u`.id='$userid' AND `u`.defstock = `l`.id LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); mysql_query("START TRANSACTION;") or die(mysql_error()); $query = "SELECT * FROM `serials` WHERE `locid`='".$row["id"]."' AND `type`='$serialtype' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); $query = "UPDATE `serials` SET `current`='".($row["current"]+1)."' WHERE `id`='".$row["id"]."' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); mysql_query("COMMIT") or die(mysql_error()); return $row; } //users function users_addUser( $array ) { if( $array["useip"] == NULL ) $array["useip"]=0; $insertQ = "INSERT INTO `users` ( `id` , `cnp` , `active` , `username` , `upassword` , `forname` , `lastname` , `gender` , `birth` , `nationality` , `email` , `homephone` , `mobile` , `defstock` , `access` , `anulate`, `discount`, `ip`, `useip`,`clientView`,`clientDatorieView`,`generalFinalPriceView`,`emailPass`,`comandaall`,`facturaall`,`contractall`,`chitantaall`,`comandaallw`,`facturaallw`,`contractallw`,`chitantaallw`,`partnerall`,`modelall`,`serviceall`,`templateall`,`crm_visibility`) VALUES ( NULL , NULL , '".$array["active"]."', '".$array["username"]."', PASSWORD('".$array["upassword"]."'), '".$array["forname"]."', '".$array["lastname"]."', '', NULL , NULL , NULL , NULL , NULL , '".$array["defstock"]."', '".$array["access"]."','".$array["anulate"]."','".$array["discount"]."', '".$array["ip"]."', '".$array["useip"]."', '".$array["clientView"]."', '".$array["clientDatorieView"]."', '".$array["generalFinalPriceView"]."', '".$array["emailPass"]."', '".$array["comandaall"]."', '".$array["facturaall"]."', '".$array["contractall"]."', '".$array["chitantaall"]."', '".$array["comandaallw"]."', '".$array["facturaallw"]."', '".$array["contractallw"]."', '".$array["chitantaallw"]."', '".$array["partnerall"]."', '".$array["modelall"]."', '".$array["serviceall"]."','".$array["templateall"]."', '".$array["crm_visibility"]."' ); "; mysql_query( $insertQ ) or die(mysql_error()); return mysql_insert_id(); } function users_updateUser( $userid , $array ) { if( $array["active"] == "nu" )$array["active"] = 0;else $array["active"] = 1; if( $array["useip"] == NULL ) { $array["useip"]=0; } $update = "UPDATE `users` SET `username`='".$array["username"]."', `forname`='".$array["forname"]."', `lastname`='".$array["lastname"]."', `defstock`='".$array["defstock"]."', `access`='".$array["access"]."', `anulate`='".$array["anulate"]."', `clientView`='".$array["clientView"]."', `clientDatorieView`='".$array["clientDatorieView"]."', `generalFinalPriceView`='".$array["generalFinalPriceView"]."', `discount`='".$array["discount"]."', `ip`='".$array["ip"]."', `useIP`='".$array["useip"]."', `comandaall`='".$array["comandaall"]."', `facturaall`='".$array["facturaall"]."', `contractall`='".$array["contractall"]."', `chitantaall`='".$array["chitantaall"]."', `comandaallw`='".$array["comandaallw"]."', `facturaallw`='".$array["facturaallw"]."', `contractallw`='".$array["contractallw"]."', `chitantaallw`='".$array["chitantaallw"]."', `partnerall`='".$array["partnerall"]."', `modelall`='".$array["modelall"]."', `serviceall`='".$array["serviceall"]."', `templateall`='".$array["templateall"]."', `active`='".$array["active"]."', `crm_visibility`='".$array["crm_visibility"]."' WHERE `id`='$userid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); if( $array["upassword"] != NULL ) { $update = "UPDATE `users` SET `upassword`=PASSWORD('".$array["upassword"]."') WHERE `id`='$userid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } } function users_updateSingleUser( $userid , $array ) { if( $array["active"] == "nu" )$array["active"] = 0;else $array["active"] = 1; $update = "UPDATE `users` SET `cnp`='".$array["cnp"]."', `forname`='".$array["forname"]."', `lastname`='".$array["lastname"]."', `homephone`='".$array["homephone"]."', `mobile`='".$array["mobile"]."', `fax`='".$array["fax"]."', `email`='".$array["email"]."', `emailPass`='".$array["emailPass"]."', `colorActiveBg`='".$array["colorActiveBg"]."', `colorActiveSBg`='".$array["colorActiveSBg"]."', `colorActiveBgText`='".$array["colorActiveBgText"]."' WHERE `id`='$userid' LIMIT 1;"; $Result = mysql_query( $update ); if( $array["upassword"] != NULL ) { $update = "UPDATE `users` SET `upassword`=PASSWORD('".$array["upassword"]."') WHERE `id`='$userid' LIMIT 1;"; $passwordResult = mysql_query( $update ); } if( $array["upassword"] != NULL ) if($passwordResult || $Result) $totalResult = 1; else $totalResult = 0; else $totalResult = $Result; return $totalResult; } function users_getUser( $userid ) { $query = "SELECT * FROM `users` WHERE `id`='$userid' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function users_getUsers() { $select = "SELECT * FROM `users` ORDER by `forname`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $users[ $row["id"] ] = $row; } return $users; } function users_getAsociatHr($id) { $select = "SELECT * FROM `hr` where `userid`='$id'"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else return 1; } function completeNumber( $x ) { if (($pos = strpos ($x, '.')) == false) $x = $x . ".00"; else { $decimal = substr( $x, $pos + 1, strlen( $x ) - 1 - $pos ); if (strlen ($decimal) < 2) $x = $x . "0"; } return $x; } function users_getLocationInfo( $userid ) { $selectQ = "SELECT * FROM `users` WHERE `id`='$userid' LIMIT 1;"; $result = mysql_query( $selectQ ); $row = mysql_fetch_array( $result ); $stockid = $row["defstock"]; $selectQ = "SELECT * FROM `stocks` WHERE `id`='$stockid' LIMIT 1;"; $result = mysql_query( $selectQ ); $row = mysql_fetch_array( $result ); $locid = $row["locid"]; $selectQ = "SELECT * FROM `locations` WHERE `id`='$locid' LIMIT 1;"; $result = mysql_query( $selectQ ); return mysql_fetch_array( $result ); } function completeTemplate($templateId,$documentSeries,$documentNumber,$addressHC,$countyHC,$addressPlHC,$countyPlHC,$cifHC,$registruHC,$bankHC,$ibanHC,$telfaxHC,$emailHC,$webHC,$nameC,$addessC,$countyC,$cifC,$registruC,$bankC,$ibanC,$invoiceDate,$lastDate,$elementsList,$invoiceWithoutTVA,$invoiceonlyTVA,$invoiceTotalSum,$rootFolder,$codDeValidare,$deLaStoc,$mergeLaStoc,$contraValoarea,$intocmitDe,$modDePlata,$data,$nravizmarfii,$dataex,$telfaxCumparator,$emailCumparator,$webCumparator,$capitalSocial,$adica,$cursValutar,$shipperinfo,$directDelivery,$dangerous,$truckerinfo,$truckerPartnerInfo,$truckerAmount,$loadingPlace,$loadingDate,$dischargePlace,$dischargeDate,$addFacturaClient,$facturaAmount,$facturaAmountCurrency,$comments,$otherinfo,$kmplini,$kmgol,$pretplini,$pretgol,$plinitotal,$goltotal,$kmprettotal,$tipcamion,$adr,$driversName,$driversTel,$profit,$dataExecutiei, $proiectName,$descriereProiect,$managerProiect,$persoanaDeContact,$elementsListHr,$functia,$functiaclient,$durata,$reprezentant,$hrid,$tipContract,$obiectContract,$dataInceput,$perioadaInceput,$perioadaSfarsit,$orePeZi,$orePeSaptamana,$concediu,$angajatText) { $loadedTemplate = loadTemplate($templateId); //changing the images for real text $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/seria_documentului.jpg",$documentSeries); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_sediu.jpg",$addressHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_sediu.jpg",$addressHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_sediu.jpg",$countyHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_punct_de_lucru.jpg",$countyPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/CIF.jpg",$cifHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/Registru.jpg",$registruHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/banca.jpg",$bankHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/cod_iban.jpg",$ibanHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/tel_fax.jpg",$telfaxHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/email.jpg",$emailHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/web.jpg",$webHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cumparator.jpg",$nameC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/adresa_cumparator.jpg",$addessC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/judet_cumparator.jpg",$countyC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cif_cumparator.jpg",$cifC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/registru_cumparator.jpg",$registruC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/banca_cumparator.jpg",$bankC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/iban_cumparator.jpg",$ibanC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/termen_de_plata.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataExecutiei); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"lista_elemente.jpg",$elementsList); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/fara_TVA.jpg",$invoiceWithoutTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/fara_TVA.jpg",$invoiceWithoutTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/din_care_TVA.jpg",$invoiceonlyTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/din_care_TVA.jpg",$invoiceonlyTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/cod_de_validare.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/de_la_stoc.jpg",$deLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/merge_la_stoc.jpg",$mergeLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/contravaloarea.jpg",$contraValoarea); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/contravaloarea.jpg",$contraValoarea); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/mod_de_plata.jpg",$modDePlata); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/curs_de_schimb.jpg",$cursValutar); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"aviz/cod_generat.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/adica.jpg",$adica); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/adica.jpg",$adica); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_aviz_a_marfii.jpg",$nravizmarfii); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/telfax_cumparator.jpg",$telfaxCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/email_cumparator.jpg",$emailCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/web_cumparator.jpg",$webCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/capital_social.jpg",$capitalSocial); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/shipper.jpg",$shipperinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/delivery.jpg",$directDelivery); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dangerous.jpg",$dangerous); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/trucker.jpg",$truckerinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/truckerinfo.jpg",$truckerPartnerInfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/truckeramount.jpg",$truckerAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingplace.jpg",$loadingPlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingplace.jpg",$loadingPlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingdate.jpg",$loadingDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingdate.jpg",$loadingDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargeplace.jpg",$dischargePlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargedate.jpg",$dischargeDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargedate.jpg",$dischargeDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaforclient.jpg",$addFacturaClient); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamount.jpg",$facturaAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamountcurrency.jpg",$facturaAmountCurrency); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/otherinfo.jpg",$otherinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/profit.jpg",$profit); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/driverstel.jpg",$driversTel); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/driversname.jpg",$driversName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/adr.jpg",$adr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/kmplini.jpg",$kmplini); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/kmgol.jpg",$kmgol); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/pretplini.jpg",$pretplini); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/pretgol.jpg",$pretgol); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/plinitotal.jpg",$plinitotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/goltotal.jpg",$goltotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/total.jpg",$kmprettotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/tipcamion.jpg",$tipcamion); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/nume_proiect.jpg",$proiectName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/descriere.jpg",$descriereProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/proiect_manager.jpg",$managerProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/contact_person.jpg",$persoanaDeContact); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/elemente_hr.jpg",$elementsListHr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/nume_proiect.jpg",$proiectName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/descriere.jpg",$descriereProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/proiect_manager.jpg",$managerProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/contact_person.jpg",$persoanaDeContact); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/elemente_hr.jpg",$elementsListHr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/durata.jpg",$durata); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/functiaclient.jpg",$functiaclient); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/functia.jpg",$functia); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/reprezentant.jpg",$reprezentant); $perioada = $perioadaInceput." - ".$perioadaSfarsit; $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/tip_contract.jpg",$tipContract); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/obiect_contract.jpg",$obiectContract); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/data_inceput.jpg",$dataInceput); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/data_inceput.jpg",$dataInceput); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/perioada.jpg",$perioada); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/durata_zii.jpg",$orePeZi); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/durata_saptamana.jpg",$orePeSaptamana); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/durata_zii.jpg",$orePeZi); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/durata_saptamana.jpg",$orePeSaptamana); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/concediu.jpg",$concediu); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/hr.jpg",$angajatText); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/hr.jpg",$angajatText); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/conditii.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/functia.jpg",$functiaclient); //changing the images for real text $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/seria_documentului.jpg",$documentSeries); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_sediu.jpg",$addressHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_sediu.jpg",$addressHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_sediu.jpg",$countyHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_punct_de_lucru.jpg",$countyPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/CIF.jpg",$cifHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/Registru.jpg",$registruHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/banca.jpg",$bankHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/cod_iban.jpg",$ibanHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/tel_fax.jpg",$telfaxHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/email.jpg",$emailHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/web.jpg",$webHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cumparator.jpg",$nameC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/adresa_cumparator.jpg",$addessC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/judet_cumparator.jpg",$countyC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cif_cumparator.jpg",$cifC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/registru_cumparator.jpg",$registruC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/banca_cumparator.jpg",$bankC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/iban_cumparator.jpg",$ibanC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/termen_de_plata.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataExecutiei); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"lista_elemente.jpg",$elementsList); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/fara_TVA.jpg",$invoiceWithoutTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/fara_TVA.jpg",$invoiceWithoutTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/din_care_TVA.jpg",$invoiceonlyTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/din_care_TVA.jpg",$invoiceonlyTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/cod_de_validare.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/de_la_stoc.jpg",$deLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/merge_la_stoc.jpg",$mergeLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/contravaloarea.jpg",$contraValoarea); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/contravaloarea.jpg",$contraValoarea); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/mod_de_plata.jpg",$modDePlata); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/curs_de_schimb.jpg",$cursValutar); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"aviz/cod_generat.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/adica.jpg",$adica); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/adica.jpg",$adica); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_aviz_a_marfii.jpg",$nravizmarfii); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/telfax_cumparator.jpg",$telfaxCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/email_cumparator.jpg",$emailCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/web_cumparator.jpg",$webCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/capital_social.jpg",$capitalSocial); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/shipper.jpg",$shipperinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/delivery.jpg",$directDelivery); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dangerous.jpg",$dangerous); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/trucker.jpg",$truckerinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/truckerinfo.jpg",$truckerPartnerInfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/truckeramount.jpg",$truckerAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingplace.jpg",$loadingPlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingplace.jpg",$loadingPlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingdate.jpg",$loadingDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingdate.jpg",$loadingDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargeplace.jpg",$dischargePlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargedate.jpg",$dischargeDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargedate.jpg",$dischargeDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaforclient.jpg",$addFacturaClient); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamount.jpg",$facturaAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamountcurrency.jpg",$facturaAmountCurrency); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/otherinfo.jpg",$otherinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/profit.jpg",$profit); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/driverstel.jpg",$driversTel); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/driversname.jpg",$driversName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/adr.jpg",$adr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/kmplini.jpg",$kmplini); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/kmgol.jpg",$kmgol); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/pretplini.jpg",$pretplini); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/pretgol.jpg",$pretgol); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/plinitotal.jpg",$plinitotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/goltotal.jpg",$goltotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/total.jpg",$kmprettotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/tipcamion.jpg",$tipcamion); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/nume_proiect.jpg",$proiectName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/descriere.jpg",$descriereProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/proiect_manager.jpg",$managerProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/contact_person.jpg",$persoanaDeContact); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/elemente_hr.jpg",$elementsListHr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/nume_proiect.jpg",$proiectName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/descriere.jpg",$descriereProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/proiect_manager.jpg",$managerProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/contact_person.jpg",$persoanaDeContact); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/elemente_hr.jpg",$elementsListHr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/durata.jpg",$durata); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/functiaclient.jpg",$functiaclient); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/functia.jpg",$functia); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/reprezentant.jpg",$reprezentant); $perioada = $perioadaInceput." - ".$perioadaSfarsit; $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/tip_contract.jpg",$tipContract); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/obiect_contract.jpg",$obiectContract); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/data_inceput.jpg",$dataInceput); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/data_inceput.jpg",$dataInceput); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/perioada.jpg",$perioada); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/durata_zii.jpg",$orePeZi); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/durata_saptamana.jpg",$orePeSaptamana); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/durata_zii.jpg",$orePeZi); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/durata_saptamana.jpg",$orePeSaptamana); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/concediu.jpg",$concediu); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/hr.jpg",$angajatText); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/hr.jpg",$angajatText); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/conditii.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAngajat/functia.jpg",$functiaclient); return $loadedTemplate; } function completeTemplateDaily($templateId,$documentSeries,$documentNumber,$addressHC,$countyHC,$addressPlHC,$countyPlHC,$cifHC,$registruHC,$bankHC,$ibanHC,$telfaxHC,$emailHC,$webHC,$nameC,$addessC,$countyC,$cifC,$registruC,$bankC,$ibanC,$invoiceDate,$lastDate,$elementsList,$invoiceWithoutTVA,$invoiceonlyTVA,$invoiceTotalSum,$rootFolder,$codDeValidare,$deLaStoc,$mergeLaStoc,$contraValoarea,$intocmitDe,$data,$nravizmarfii,$dataex,$telfaxCumparator,$emailCumparator,$webCumparator,$capitalSocial,$adica,$shipperinfo,$directDelivery,$dangerous,$truckerinfo,$truckerPartnerInfo,$truckerAmount,$loadingPlace,$loadingDate,$dischargePlace,$dischargeDate,$addFacturaClient,$facturaAmount,$facturaAmountCurrency,$comments,$otherinfo,$kmplini,$kmgol,$pretplini,$pretgol,$plinitotal,$goltotal,$kmprettotal,$tipcamion,$adr,$driversName,$driversTel,$profit,$dataExecutiei, $proiectName,$descriereProiect,$managerProiect,$persoanaDeContact,$elementsListHr,$functia,$functiaclient,$durata,$reprezentant,$hrid,$tipContract,$obiectContract,$dataInceput,$perioadaInceput,$perioadaSfarsit,$orePeZi,$orePeSaptamana,$concediu,$angajatText) { $invoiceWithoutTVA = completeNumber ($invoiceWithoutTVA); $invoiceonlyTVA = completeNumber ($invoiceonlyTVA); $invoiceTotalSum = completeNumber ($invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); // berakni az $adica valtozot a declarational... // 34 elements on function declaration $loadedTemplate = loadTemplate($templateId); //changing the images for real text $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/seria_documentului.jpg",$documentSeries); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_sediu.jpg",$addressHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_sediu.jpg",$addressHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_sediu.jpg",$countyHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_punct_de_lucru.jpg",$countyPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/CIF.jpg",$cifHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/Registru.jpg",$registruHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/banca.jpg",$bankHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/cod_iban.jpg",$ibanHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/tel_fax.jpg",$telfaxHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/email.jpg",$emailHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/web.jpg",$webHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/banca_cumparator.jpg",$bankC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/iban_cumparator.jpg",$ibanC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/termen_de_plata.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataExecutiei); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"lista_elemente.jpg",$elementsList); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/fara_TVA.jpg",$invoiceWithoutTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/fara_TVA.jpg",$invoiceWithoutTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/din_care_TVA.jpg",$invoiceonlyTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/din_care_TVA.jpg",$invoiceonlyTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/cod_de_validare.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/de_la_stoc.jpg",$deLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/merge_la_stoc.jpg",$mergeLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/contravaloarea.jpg",$contraValoarea); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/contravaloarea.jpg",$contraValoarea); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"aviz/cod_generat.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/adica.jpg",$adica); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/adica.jpg",$adica); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_aviz_a_marfii.jpg",$nravizmarfii); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/telfax_cumparator.jpg",$telfaxCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/email_cumparator.jpg",$emailCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/web_cumparator.jpg",$webCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/capital_social.jpg",$capitalSocial); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/shipper.jpg",$shipperinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/delivery.jpg",$directDelivery); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dangerous.jpg",$dangerous); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/trucker.jpg",$truckerinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/truckerinfo.jpg",$truckerPartnerInfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/truckeramount.jpg",$truckerAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingplace.jpg",$loadingPlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingplace.jpg",$loadingPlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingdate.jpg",$loadingDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingdate.jpg",$loadingDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargeplace.jpg",$dischargePlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargedate.jpg",$dischargeDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargedate.jpg",$dischargeDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaforclient.jpg",$addFacturaClient); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamount.jpg",$facturaAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamountcurrency.jpg",$facturaAmountCurrency); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/otherinfo.jpg",$otherinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/profit.jpg",$profit); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/driverstel.jpg",$driversTel); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/driversname.jpg",$driversName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/adr.jpg",$adr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/kmplini.jpg",$kmplini); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/kmgol.jpg",$kmgol); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/pretplini.jpg",$pretplini); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/pretgol.jpg",$pretgol); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/plinitotal.jpg",$plinitotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/goltotal.jpg",$goltotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/total.jpg",$kmprettotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/tipcamion.jpg",$tipcamion); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/nume_proiect.jpg",$proiectName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/descriere.jpg",$descriereProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/proiect_manager.jpg",$managerProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/contact_person.jpg",$persoanaDeContact); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/elemente_hr.jpg",$elementsListHr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/nume_proiect.jpg",$proiectName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/descriere.jpg",$descriereProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/proiect_manager.jpg",$managerProiect); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/contact_person.jpg",$persoanaDeContact); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/elemente_hr.jpg",$elementsListHr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/durata.jpg",$durata); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/functiaclient.jpg",$functiaclient); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/functia.jpg",$functia); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/reprezentant.jpg",$reprezentant); $perioada = $perioadaInceput." - ".$perioadaSfarsit; $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/tip_contract.jpg",$tipContract); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/obiect_contract.jpg",$obiectContract); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/data_inceput.jpg",$dataInceput); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/data_inceput.jpg",$dataInceput); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/perioada.jpg",$perioada); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/durata_zii.jpg",$orePeZi); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/durata_saptamana.jpg",$orePeSaptamana); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/durata_zii.jpg",$orePeZi); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/durata_saptamana.jpg",$orePeSaptamana); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/concediu.jpg",$concediu); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/hr.jpg",$angajatText); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/hr.jpg",$angajatText); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/conditii.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"contractAnagajat/functia.jpg",$functiaclient); return $loadedTemplate; } /////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// function getNumber ($value) { switch ($value) { case 1 : $str = getTraducere("un",$_SESSION["settings"]["default_lang"]); break; case 2 : $str = getTraducere("doua",$_SESSION["settings"]["default_lang"]); break; case 3 : $str = getTraducere("trei",$_SESSION["settings"]["default_lang"]); break; case 4 : $str = getTraducere("patru",$_SESSION["settings"]["default_lang"]); break; case 5 : $str = getTraducere("cinci",$_SESSION["settings"]["default_lang"]); break; case 6 : $str = getTraducere("sase",$_SESSION["settings"]["default_lang"]); break; case 7 : $str = getTraducere("sapte",$_SESSION["settings"]["default_lang"]); break; case 8 : $str = getTraducere("opt",$_SESSION["settings"]["default_lang"]); break; case 9 : $str = getTraducere("noua",$_SESSION["settings"]["default_lang"]); break; default : $str = ""; break; } return $str; } function getDecimal ($number) { if ($number [0] != 0) { if ($number [0] == 1) { if ($number [1] == 0) { $str = "zece"; } else { if(getNumber ($number [1]) == "doua") $str = (getNumber ($number [1]) == "doua" ? "doi" : getNumber ($number [1])) . "sprezece"; if(getNumber ($number [1]) == "sase") $str = (getNumber ($number [1]) == "sase" ? "sai" : getNumber ($number [1])) . "sprezece"; if(getNumber ($number [1]) == "patru") $str = (getNumber ($number [1]) == "patru" ? "pai" : getNumber ($number [1])) . "sprezece"; if(getNumber ($number [1]) != "sase" && getNumber ($number [1]) != "doua" && getNumber ($number [1]) != "patru") $str = getNumber ($number [1]) . "sprezece"; } } else { $str = (getNumber ($number [0]) == "sase" ? "sai" : getNumber ($number [0])) . "zeci"; if ($number [1] != 0) $str = $str . "si" . (getNumber ($number [1]) == "doua" ? "doua" : getNumber ($number [1])); } } else { $str = getNumber ($number [1]); } if ($number [1] == 1 && $number [0] != 1 && $number [0] != 0) $str = $str . "a"; return $str; } function getString ($number) { $length = strlen ($number); if ($length == 1) $str = getNumber ($number); else $str = getDecimal (substr ($number, $length - 2, 2)); if ($length > 2) if ($number [$length - 3] == 1) $str = "osuta" . $str; else if( $number [$length - 3]!=0 ) $str = getNumber ($number [$length - 3]) . "sute" . $str; if ($length >= 4) if ($length == 4) if ($number [$length - 4] == 1) $str = "omie" . $str; else $str = getNumber ($number [$length - 4]) . "mii" . $str; else $str = getDecimal (substr ($number, $length - 5, 2)) . "mii" . $str; if ($length > 5) if ($number [$length - 6] == 1) $str = "osuta" . $str; else $str = getNumber ($number [$length - 6]) . "sute" . $str; if ($length == 7) if ($number [$length - 7] == 1) $str = "un milion" . $str; else $str = getNumber ($number [$length - 7]) . "milioane" . $str; return $str; } function getStringValue ($number, $currency) { // hibakezeles $regexpr = "^ *(([1-9][0-9]{0,6})|(0))(\.[0-9]+){0,1}$"; if (ereg ($regexpr, $number) == false) return getTraducere("Valoarea nu este valida",$_SESSION["settings"]["default_lang"])."!"; if (($pos = strpos ($number, '.')) != false) $number = substr ($number, 0, $pos + 3); $number = trim ($number, " "); $i = strpos ($number, "."); if ($i == false) $whole = $number; else { $whole = substr ($number, 0, $i); $float = substr ($number, $i + 1, strlen ($number) - $i + 1); } $whole = getString ($whole); if ($whole == "") $whole = "zero"; if ($float == false) $float = "zero"; else { if (strlen ($float) == 1) $float = $float . "0"; $float = getString ($float); } if($float!="zero") $bani = " si $float " . ($float == "un" ? ($currency=="RON"?"ban":"centi") : ($currency=="RON"?"bani":"centi")); else $bani=""; if($number<=19) $returnValue="$whole " . ($whole == "un" ? ($currency=="RON"?" lei":" $currency") : ($currency=="RON"?" lei":"$currency")) . $bani; else $returnValue="$whole " . ($whole == "un" ? "de " : "de ").$currency . $bani; return $returnValue; } function convertNumber( $x ) { return round($x,2); } function convertNumber4( $x ) { return round($x,4); } function convertToSerial( $x ) { $howManyChars = $_SESSION["settings"]["serialCharsNumbers"]; if(strlen($x)>$_SESSION["settings"]["serialCharsNumbers"]) $whole=$x; for($i=1;$i<=$howManyChars;$i++) { if( strlen( $x ) == $i ) { for($j=1;$j<=$howManyChars-strlen( $x );$j++) $charsString.="0"; $whole = $charsString.$x; } } return $whole; } //////////////////////////////////////////////////////////////////////////////////// function list_items_out () { $query = "SELECT * FROM stock_items_out"; $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) { $list [$row ["id"]] = $row; } return $list; } function getStockItems_out( $from, $to ) { //$from = mysql_prevDay( $from ); $to = mysql_nextDay( $to ); $stockid = $_SESSION["user"]["defstock"]; $query = "SELECT * FROM stock_items_out s WHERE s.stockid = '$stockid' AND s.ondate BETWEEN '$from' AND '$to'"; $result = mysql_query( $query ) or die($query.mysql_error()); while ($row = mysql_fetch_array ($result)) $items [$row ["id"]] = $row; return $items; } function stock_getStockItemsInInterval( $from, $to, $orderby, $ordermode, $pagetoshow = -1 , $defstock) { //$from = mysql_prevDay( $from ); $to = mysql_nextDay( $to ); if($_SESSION["user"]["access"]=="administrare") { $locationFilter = ""; } else { $locationid = $_SESSION["user"]["defstock"]; $locationFilter = " AND s.locid = '$locationid'"; } if($defstock==NULL) $stockFilter=""; else $stockFilter = " AND si.stockid='$defstock'"; $query = "SELECT si.id AS id, c.name AS name, c.code AS code, s.name AS locname, si.quantity AS quantity, si.price AS price, si.ondate AS ondate, si.quantityType AS quantityType FROM stocks s, stock_items_in si, container c WHERE s.id = si.stockid AND c.id = si.itemid ".$locationFilter.$stockFilter." AND si.ondate BETWEEN '$from' AND '$to' ORDER BY $orderby $ordermode"; if ($pagetoshow != -1) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pagetoshow - 1) * $count; $query = $query . " LIMIT $from, $count"; } $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while ($row = mysql_fetch_array ($result)) { $counter++; $items [$row ["id"]] = $row; } return $items; } function stock_getStockItemsOutInterval( $from, $to, $orderby, $ordermode, $pagetoshow = -1 , $defstock) { $to = mysql_nextDay( $to ); if($_SESSION["user"]["access"]=="administrare") { $locationFilter = ""; } else { $locationid = $_SESSION["user"]["defstock"]; $locationFilter = " AND s.locid = '$locationid'"; } if($defstock==NULL) $stockFilter=""; else $stockFilter = " AND si.stockid='$defstock'"; $query = "SELECT si.id AS id, c.name AS name, c.code AS code, s.name AS locname, si.quantity AS quantity, si.price AS price, si.ondate AS ondate, si.quantityType AS quantityType FROM stocks s, stock_items_out si, container c WHERE s.id = si.stockid AND c.id = si.itemid ".$locationFilter.$stockFilter." AND si.ondate BETWEEN '$from' AND '$to' ORDER BY $orderby $ordermode"; if ($pagetoshow != -1) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pagetoshow - 1) * $count; $query = $query . " LIMIT $from, $count"; } $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $items [$row ["id"]] = $row; return $items; } function getServiceEntry ($id) { $query = "SELECT * FROM services WHERE id = '$id' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); if($result) $entry = mysql_fetch_array ($result); return $entry; } function settings_getSetting( $type ) { $query = "SELECT * FROM `settings` WHERE `type`='$type' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return $row["value"]; } function settings_getSettings() { $query = "SELECT * FROM `settings`"; $results = mysql_query( $query ) or die(mysql_error()); if( $results ) { while( $row = mysql_fetch_array( $results ) ) { $_SESSION["settings"][ $row["type"] ] = $row["value"]; } } return NULL; } function settings_updateSettings( $array ) { foreach( $array as $key => $value ) { if( $array["IPsecurity"]==NULL ) { $key="IPsecurity"; $value=0; } $query = "UPDATE `settings` SET `value`='$value' WHERE `type`='$key' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } } function settings_setSetting( $type , $value ) { $query = "UPDATE `settings` SET `value`='$value' WHERE `type`='$type' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } function settings_makeOutPrice( $value ) { $value = $value + ($value * $_SESSION["settings"]["outadaos"]); return convertNumber4( $value ); } function settings_makeOutPriceFromModel( $value ) { return convertNumber4( $value ); } function settings_makeFullPrice( $value , $tva ) { $value += $value * $_SESSION["settings"]["outadaos"]; $value += $value * $tva; return convertNumber4( $value ); } function settings_makeFullPriceFromModel( $value , $tva ) { $value += $value; $value += $value * $tva; return convertNumber4( $value ); } function settings_makeTvaPrice( $value , $tva) { $value += $value * $tva; return convertNumber4( $value ); } function settings_getTva( $value , $tva) { return convertNumber( $value * $tva ); } //////a ceg adatai akie a managemetredszer:)//// function admin_getCompanyDetails( ) { $query = "SELECT COUNT(*) AS count FROM companies"; $result = mysql_query( $query ) or die(mysql_error()); $result = mysql_fetch_array ($result); $count = $result ["count"]; if ($count == 1) { $query = "SELECT * FROM companies"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return $row; } return NULL; } function admin_changeCompanyInfo( $array ) { foreach( $array as $key => $value ) $$key = $value; $query = "UPDATE companies SET `name` = '$name', `comname` = '$comname', `contactperson` = '$contactperson', `country` = '$country', `state`='$state', `city` = '$city', `address` = '$address', `orcnumber` = '$orcnumber', `bank` = '$bank', `iban` = '$iban', `cui` = '$cui', `capsocial`='$capsocial', `phone` = '$phone', `fax`= '$fax', `mobile` = '$mobile', `cemail` = '$cemail', `web` = '$web'"; $result = mysql_query( $query ) or die(mysql_error()); } function expens_addExpensFromNir($catid,$locationId,$provider,$observatii,$value,$tva,$onValuta,$payed,$number,$expdate,$lastdayofpay,$cursValue,$commandId, $date) { $query = "INSERT INTO `expenses` ( `id` , `number` , `catid` , `value` , `tva` , `ondate` , `userid` , `expdate` ,`provider`,`payed`,`lastdayofpay`, `proiectid`,`onValuta`,`cursValue`,`observatii`,`ordinId`,`locationId`,`carid`,`commandId`) VALUES ( NULL , '$number', '$catid', '$value', '$tva','$date', '".$_SESSION["user"]["id"]."', '$expdate','$provider','$payed','$lastdayofpay' ,'$addfactid','$onValuta','$cursValue','$observatii','$ordinid','$locationId','$carid','$commandId');"; mysql_query( $query ) or die($query." ".mysql_error()); return mysql_insert_id(); } function expens_addExpens( $array ) { foreach( $array as $key => $xvalue ) $$key = $xvalue; $commands = split(",",$comandanr); $commandId=""; foreach( $commands as $ckey => $cvalue) { while(strpos($cvalue, "0")===0) $cvalue=substr($cvalue,1); if($cvalue!=NULL) $commandId.=" ".command_getCommandIdFromNr($cvalue).","; } if( $tva == NULL )$tva = ( $bvalue * 19 )/ 100; $query = "INSERT INTO `expenses` ( `id` , `number` , `catid` , `value` , `tva` , `ondate` , `userid` , `expdate` ,`provider`,`payed`,`lastdayofpay`, `proiectid`,`onValuta`,`cursValue`,`observatii`,`ordinId`,`locationId`,`carid`,`commandId`,`deductibil`,`dosarid`) VALUES ( NULL , '$number', '$catid', '$value', '$tva', NOW(), '".$_SESSION["user"]["id"]."', '$expdate','$provider','$payed','$lastdayofpay' ,'$addfactid','$onValuta','$cursValue','$observatii','$ordinid','$locationId','$carid','$commandId','$deduct','$dosarid');"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function expens_modExpens( $expensId , $array ) { foreach( $array as $key => $xvalue ) $$key = $xvalue; $commands = split(",",$comandanr); $commandId=""; foreach( $commands as $ckey => $cvalue) { while(strpos($cvalue, "0")===0) $cvalue=substr($cvalue,1); if($cvalue!=NULL) $commandId.=" ".command_getCommandIdFromNr($cvalue).","; } $update = "UPDATE `expenses` SET `number` = '$number', `catid` = '$catid', `value` = '$value', `onValuta` = '$onValuta', `tva` = '$tva', `expdate` = '$expdate', `provider` = '$provider', `payed` = '$payed', `lastdayofpay` = '$lastdayofpay', `observatii` = '$observatii', `locationId` = '$locationId', `carid` = '$carid', `commandId` = '$commandId', `cursValue` = '$cursValue', `deductibil` = '$deductibil', `dosarid` = '$dosarid' WHERE `expenses`.`id` ='$expensId' LIMIT 1 ;"; mysql_query( $update ) or die(mysql_error()); } function expens_delExpens( $expensId ) { $delSql = "DELETE FROM `expenses` WHERE `id` = '$expensId';"; mysql_query( $delSql ) or die(mysql_error()); } function expens_delExpensCat( $catid ) { $delSql = "DELETE FROM `expenses_cat` WHERE `id` = '$catid';"; mysql_query( $delSql ) or die(mysql_error()); } function expens_addCat( $name ) { //leellenorizni, hogy van-e mar az adatbazisban $questName = strtolower( $name ); $insertQ = "SELECT * FROM `expenses_cat` WHERE LOWER(`name`) = '$questName'"; $result = mysql_query( $insertQ ); $row = mysql_fetch_array($result); if($row["name"]=='') { $insertQ = "INSERT INTO `expenses_cat` (`id`,`name`) VALUES ( NULL , '$name' )"; mysql_query( $insertQ ); return mysql_insert_id(); } else { return $row["id"]; } } function expens_getExpens( $expensId ) { $query = "SELECT * FROM `expenses` WHERE `id`='$expensId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { $row = mysql_fetch_array( $result ); return $row; } else return NULL; } function expens_getCategories() { $selectQ = "SELECT * FROM `expenses_cat` ORDER BY `name`"; $result = mysql_query( $selectQ ); if( $result ) { while( $row = mysql_fetch_array( $result )) $list[ $row["id"] ] = $row; return $list; } return NULL; } function expens_getCategory( $id ) { $selectQ = "SELECT * FROM `expenses_cat` WHERE `id`='$id' ORDER BY `name`"; $result = mysql_query( $selectQ ); if( $result ) { $row = mysql_fetch_array( $result ); return $row; } return NULL; } function mysql_prevDay( $date ) { $query = "SELECT ADDDATE('$date', -1 );"; $result = mysql_query( $query ) or die(mysql_error()); return mysql_result( $result , 0 , 0 ); } function mysql_nextDay( $date ) { $query = "SELECT ADDDATE('$date', 1 );"; $result = mysql_query( $query ) or die(mysql_error()); return mysql_result( $result , 0 , 0 ); } function expens_queryGenerator( $page , $orderby , $ordermode , $fromDate , $toDate , $searchval, $searchCriteria , $filter_menu) { $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu) $filterSql = " AND e.`catid` = '$filter_menu'"; //searchCrietria if($searchval) $timeLimitQuery=""; else $timeLimitQuery=" AND e.`expdate` BETWEEN '$fromDate' AND '$toDate' "; if($searchCriteria=="serial") $searchPlus = " AND e.`number` LIKE '$searchval'"; if($searchCriteria=="name") { $query = "SELECT e.* FROM `expenses` e, `partners` p WHERE `e`.`id` != '0' ".$timeLimitQuery." AND p.`name` LIKE '%$searchval%' AND e.`provider` = p.`id` ".$filterSql." ORDER BY e.`$orderby` $ordermode LIMIT $from,$howmany"; } else { $query = "SELECT * FROM `expenses` e WHERE `e`.`id` != '0' ".$timeLimitQuery.$searchPlus." ".$filterSql." ORDER BY $orderby $ordermode LIMIT $from,$howmany"; } return $query; } function expens_getExpensSearchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return count( $result ); } function expens_getExpenses( $query ) { $results = mysql_query( $query ) or die(mysql_error()); if( $results ) { while( $row = mysql_fetch_array( $results ) ) $bons[ $row["id"] ] = $row; return $bons; } return NULL; } //startpage function factura_getLatestFacturaItems () { $query = "SELECT f1.rowName AS rowName, f1.modelid as modelid, f1.type AS type, f1.id AS id, p.name AS clientname, p.id as clientid, m.name AS modelname, f2.ondate AS ondate, f1.price as price, f2.id as factid FROM facturi_items f1, facturi f2, models m, partners p, services s WHERE f2.clientid = p.id AND f1.factid = f2.id ORDER BY f2.ondate DESC LIMIT 0, 5"; $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $list [$row ["id"]] = $row; return $list; } function factura_getServiceDateNotonFactura( $serviciiId,$commandId,$maxDate,$itemsId) { $query="SELECT * FROM `comandaForClientAdvItemsDates` WHERE `serviceid`='$serviciiId' AND (`commandid`='$commandId') AND `onFactura`=0 AND `date` <= '$maxDate' AND `itemsId` = '$itemsId' ORDER BY `date` ASC"; $result=mysql_query( $query ) or die(mysql_error()); if($result) { return $result; } else return NULL; } function subtract_dates($begin_date, $end_date) { return round(((strtotime($end_date) - strtotime($begin_date)) / 86400)); } function subtract_datesForMinutes($begin_date, $end_date) { return round(((strtotime($end_date) - strtotime($begin_date)) / 60)); } function subtract_dates_hour($begin_date, $end_date) { return strtotime($end_date) - strtotime($begin_date); } function factura_getSoldItemsZi($commandid, $serviceid) { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$commandid' AND `prodid`='$serviceid' AND `sellType`='' order by `startDate`"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); $startdata=$row["startDate"]; $enddata=$row["endDate"]; $end=mysql_nextDay($enddata); while($startdata!=$end) { $query2=" SELECT `date` FROM `facturi_items` ,`facturi` WHERE `facturi_items`.`modelid`='$serviceid' AND `facturi_items`.`factid`=`facturi`.`id` AND `facturi`.`fromActId`='$commandid'"; $result2=mysql_query($query2) or die(mysql_error()); $count=mysql_num_rows($result2); if($count!=0) { $volt=0; while($row2=mysql_fetch_array($result2)) { if($startdata==$row2["date"]) { $volt++; } } if( $volt==0 ) return $startdata; } else { break; return $startdata; } $startdata=mysql_nextDay($startdata); } return $startdata; } function factura_getZilnicDatesNr($start, $end) { $date_diff = subtract_dates($start, $end ); $date_diff ++; return $date_diff; } function factura_getSoldItemsZi2($commandid, $serviceid, $maxDate, $rowid) { $query1=" SELECT `factid`, `endDate` FROM `facturi_items` ,`facturi` WHERE `facturi_items`.`modelid`='$serviceid' AND `facturi_items`.`factid`=`facturi`.`id` AND `facturi`.`fromActAdvId`='$commandid' AND `facturi`.`active` = '1' AND `facturi`.`type`='1'"; $result1=mysql_query($query1) or die(mysql_error()); $num=mysql_num_rows($result1); if($num>0) { while($dates=mysql_fetch_array($result1)) { if(factura_getStornedFactura($dates["factid"])==NULL ) $d=$dates["endDate"]; } $query3="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$commandid' AND `prodid`='$serviceid' AND `id`='$rowid' AND `sellType`='' order by `startDate`"; $result3=mysql_query($query3) or die(mysql_error()); if($result3&&mysql_num_rows($result3)>0) $row3=mysql_fetch_array($result3); $lastCommandDate=$row3["endDate"]; $year=substr($d,0,4); $month=substr($d,5,2); $day=substr($d,8,2); $lastDate=date("Y-m-d", mktime(0, 0, 0, $month, $day+1, $year)); //innen hianyzik valami $maxingDate=$lastDate; if(subtract_dates($maxDate,$maxingDate)<0) $maxingDate=$maxDate; if(subtract_dates($maxingDate,$lastCommandDate)<0) { $maxingDate=$lastCommandDate; $maxDate=$lastCommandDate; } } else { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$commandid' AND `prodid`='$serviceid' AND `id`='$rowid' AND `sellType`='' order by `startDate`"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); $lastDate=$row["startDate"]; $maxingDate=$row["endDate"]; if(subtract_dates($maxDate,$maxingDate)<0) $maxDate=$maxingDate; } $today=$maxDate; $day = mktime (0,0,0,substr($maxDate,5,2),substr($maxDate,8,2),substr($maxDate,0,4)); $daybefore=date('Y-m-d',$day); $date_diff = subtract_dates($lastDate, $daybefore ); $date_diff ++; $tmb[0]=$lastDate; $tmb[1]=$daybefore; $tmb[2]=$date_diff; $tmb[3]=$maxingDate; return $tmb; } function factura_getSoldItemsSaptamana($commandid, $serviceid) { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$commandid' AND `prodid`='$serviceid' AND `sellType`='' order by `startDate`"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); $startdata=$row["startDate"]; $day=$row["ziua"]; if($day==luni) $day=1; if($day==marti) $day=2; if($day==miercuri) $day=3; if($day==joi) $day=4; if($day==vineri) $day=5; if($day==sambata) $day=6; if($day==duminica) $day=0; $enddata=$row["endDate"]; $end=mysql_nextDay($enddata); while($startdata!=$end) { $year1=substr($startdata,0,4); $month1=substr($startdata,5,2); $day1=substr($startdata,8,2); $weekday = date("w", mktime(0,0,0,$month1,$day1,$year1)); while( strtotime($weekday)==strtotime($day) ) { $query2=" SELECT `date` FROM `facturi_items` ,`facturi` WHERE `facturi_items`.`modelid`='$serviceid' AND `facturi_items`.`factid`=`facturi`.`id` AND `facturi`.`fromActId`='$commandid'"; $result2=mysql_query($query2) or die(mysql_error()); $count=mysql_num_rows($result2); if($count!=0) { $volt=0; while($row2=mysql_fetch_array($result2)) { if($startdata==$row2["date"]) { $volt++; } } if( $volt==0 ) return $startdata; } else { break; return $startdata; } $startdata=mysql_nextDay($startdata); } //else $startdata=mysql_nextDay($startdata); } return $startdata; } function factura_getSaptamanalDatesNr($start, $end, $weekday) { $year=substr($start,0,4); $month=substr($start,5,2); $day=substr($start,8,2); $today=date("Y-m-d"); $days = mktime (0,0,0,date("m") ,date("d")-1,date("Y")); $daybefore=date('Y-m-d',$days); $year1=substr($end,0,4); $month1=substr($end,5,2); $day1=substr($end,8,2); if( $weekday == NULL || $weekday == " - " || $weekday == "-" || $weekday == "" || $weekday=="Selectaţi..." ) //ha nincs megadva h melyik nap kell a szolgaltatas { $user_date = $year1.'-01-01'; $user_date = strtotime($$user_date); $firstday = date('w', $user_date); if( $firstday==1) { $weeknumstart = strftime("%W",mktime(0,0,0,$month,$day,$year)); $weeknumend = strftime("%W",mktime(0,0,0,$month1,$day1,$year1)); } else { $weeknumstart = strftime("%W",mktime(0,0,0,$month,$day,$year))+1; $weeknumend = strftime("%W",mktime(0,0,0,$month1,$day1,$year1))+1; } $quantity = $weeknumend - $weeknumstart; } else //ha meg van adva h melyik nap kell { if($weekday==luni) $day=1; if($weekday==marti) $day=2; if($weekday==miercuri) $day=3; if($weekday==joi) $day=4; if($weekday==vineri) $day=5; if($weekday==sambata) $day=6; if($weekday==duminica) $day=0; $startdata=$start; $volt=0; while( strtotime($startdata)!=strtotime($end) ) { $year1=substr($startdata,0,4); $month1=substr($startdata,5,2); $day1=substr($startdata,8,2); $weekdaynum = date("w", mktime(0,0,0,$month1,$day1,$year1)); if($weekdaynum==$day) { $volt++; } $startdata=mysql_nextDay($startdata); } $quantity=$volt; } return $quantity; } function factura_getSoldItemsSaptamana2($commandid, $serviceid, $maxDate, $rowid) { $query1=" SELECT `factid`, `startDate`,`endDate` FROM `facturi_items` ,`facturi` WHERE `facturi_items`.`modelid`='$serviceid' AND `facturi_items`.`factid`=`facturi`.`id` AND `facturi`.`fromActAdvId`='$commandid' AND `facturi`.`active`='1' AND `facturi`.`type`='1'"; $result1=mysql_query($query1) or die(mysql_error()); $count=mysql_num_rows($result1); if($count>0) { while($dates=mysql_fetch_array($result1)) { if(factura_getStornedFactura($dates["factid"])==NULL ) { $d=$dates["endDate"]; $nrweek=$dates["weekNumber"]; } } $year1=substr($d,0,4); $month1=substr($d,5,2); $day1=substr($d,8,2); $lastDate=date("Y-m-d", mktime(0, 0, 0, $month1, $day1+1, $year1)); $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$commandid' AND `prodid`='$serviceid' AND `id`='$rowid' AND`sellType`='' order by `startDate`"; $result=mysql_query( $query ) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); $weekday=$row["ziua"]; $maxingDate=$row["endDate"]; if(subtract_dates($maxDate,$maxingDate)<0) $maxDate=$maxingDate; } else { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$commandid' AND `prodid`='$serviceid' AND `id`='$rowid' AND `sellType`='' order by `startDate`"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); $weekday=$row["ziua"]; $lastDate=$row["startDate"]; $maxingDate=$row["endDate"]; if(subtract_dates($maxDate,$maxingDate)<0) $maxDate=$maxingDate; } $year=substr($lastDate,0,4); $month=substr($lastDate,5,2); $day=substr($lastDate,8,2); $today=$maxDate; $days = mktime (0,0,0,substr($maxDate,5,2), substr($maxDate,8,2),substr($maxDate,0,4)); $daybefore=date('Y-m-d',$days); $year1=substr($daybefore,0,4); $month1=substr($daybefore,5,2); $day1=substr($daybefore,8,2); if( $weekday == NULL || $weekday == "" || $weekday == "-" || $weekday == " -" || $weekday == " - ") //ha nincs megadva h melyik nap kell a szolgaltatas { $user_date = $year1.'-01-01'; $user_date = strtotime($$user_date); $firstday = date('w', $user_date); if( $firstday==1) { $weeknumstart = strftime("%W",mktime(0,0,0,$month,$day,$year)); $weeknumend = strftime("%W",mktime(0,0,0,$month1,$day1,$year1)); } else { $weeknumstart = strftime("%W",mktime(0,0,0,$month,$day,$year))+1; $weeknumend = strftime("%W",mktime(0,0,0,$month1,$day1,$year1))+1; } if( $nrweek==52 && $weeknumstart==1 ) //ha dec-ben ki volt szamlazva arra a hetre akkor januarban nem szamlazza ujra { $nrweek=1; } if( $nrweek==$weeknumstart ) { $quantity = $weeknumend - $weeknumstart; } else $quantity = $weeknumend - $weeknumstart + 1; } else //ha meg van adva h melyik nap kell { if($weekday==luni) $day=1; if($weekday==marti) $day=2; if($weekday==miercuri) $day=3; if($weekday==joi) $day=4; if($weekday==vineri) $day=5; if($weekday==sambata) $day=6; if($weekday==duminica) $day=0; $startdata=$lastDate; $end=mysql_nextDay($daybefore); $volt=0; if(strtotime($startdata)0) { $row=mysql_fetch_array($result); } $weekday=$row["data"]; $maxingDate=$row["endDate"]; if(subtract_dates($maxDate,$maxingDate)<0) $maxDate=$maxingDate; } else { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$commandid' AND `prodid`='$serviceid' AND `id`='$rowid' AND `sellType`='' order by `startDate`"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); $lastDate=$row["startDate"]; $weekday=$row["data"]; $maxingDate=$row["endDate"]; if(subtract_dates($maxDate,$maxingDate)<0) $maxDate=$maxingDate; } if( strlen($weekday)==1 ) { $day="0".$weekday; } else $day=$weekday; $today = $maxDate; $days = mktime (0,0,0,substr($maxDate,5,2),substr($maxDate,8,2),substr($maxDate,0,4)); $daybefore = date('Y-m-d',$days); $startdata = $lastDate; if($startdata==NULL) $quantity=0; $month=substr($startdata,5,2); if(strtotime($startdata) $value ) { $list [$key] = $value; if ($paid [$key] != NULL||$paid_op[$key]!=NULL) { $list [$key]["total"] = convertNumber($value ["total"]) - convertNumber($paid [$key]["paid"]) - convertNumber($paid_op [$key]["paid_op"]); } else $list [$key]["total"] = convertNumber($value ["total"]); $list [$key]["ondate"] = $minfact [$key]["ondate"]; } usort ($list, "compare"); if (count ($list) > 5) $list = array_splice ($list, 0, 5); return $list; } function partner_getAllMarkedPartners ($viewall,$userid ) { $userInfo = users_getUser( $userid ); if($userInfo["clientView"]==0) $clientViewFilter=" AND `p`.`userid`='$userid'"; else $clientViewFilter=""; if($viewall!="1") { $viewquery= " AND ( p.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR p.`userid`='$userid') "; } $query = "SELECT p.id AS id, p.name AS name, p.phone AS tel, p.country AS country, p.state AS state, p.city AS city, p.address AS address, ROUND(SUM(ROUND(f.value * f.cursValue,2)),2) AS total FROM facturi f, partners p WHERE p.id = f.clientid and f.active=1 and f.type=1 ".$clientViewFilter." $viewquery GROUP BY p.id, p.name"; $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) { $total [$row ["id"]] = $row; } $query = "SELECT b.clientid AS id, SUM(b.value) AS paid FROM bills b WHERE b.active = 1 GROUP BY b.clientid"; $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $paid [$row ["id"]] = $row; $query = "SELECT b.clientid AS id, SUM(b.value * b.cursValue) AS paid_op FROM op b GROUP BY b.clientid"; $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $paid_op [$row ["id"]] = $row; $query = "SELECT f.clientid AS id, MIN(f.ondate) AS ondate FROM facturi f WHERE f.active = 1 and f.type = 1 GROUP BY f.clientid"; $result = mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) $minfact [$row ["id"]] = $row; if( $total == NULL )return NULL; foreach( $total as $key => $value ) { $list [$key] = $value; if ($paid [$key] != NULL||$paid_op[$key]!=NULL) { $list [$key]["total"] = convertNumber(convertNumber(floatval($value ["total"])) - convertNumber(floatval($paid [$key]["paid"])) - convertNumber(floatval($paid_op [$key]["paid_op"]))); } else $list [$key]["total"] = convertNumber($value ["total"]); $list [$key]["ondate"] = $minfact [$key]["ondate"]; } usort ($list, "compare"); // TODO limitalni a listat amikor meglessz a szamolo alul es a lapozas //if (count ($list) > 100) $list = array_splice (&$list, 0, 100); return $list; } function cmp($a, $b) { return strcmp($a["name"], $b["name"]); } function compare ($x, $y) { if ($x ["total"] == $y ["total"]) return 0; return $x ["total"] < $y ["total"] ? 1 : -1; } function partner_getLatestMarkedPartners2( ) { $query = "SELECT p.id AS id, p.name AS name, SUM(f.value) AS total FROM facturi f, partners p WHERE p.id = f.clientid anf f.active = 1 and f.type=1 GROUP BY p.id, p.name"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while ($row = mysql_fetch_array ($result)) $total [$row ["id"]] = $row; }else return NULL; $query = "SELECT b.clientid AS id, SUM(b.value) AS paid FROM bills b GROUP BY b.clientid"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while ($row = mysql_fetch_array ($result)) $paid [$row ["id"]] = $row; }else return NULL; $query = "SELECT f.clientid as id, SUM(op.sum) AS paid FROM op, facturi f WHERE f.id = op.factid and f.actibe=1 and f.type=1 GROUP BY f.clientid"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while ($row = mysql_fetch_array ($result)) if (isset ($paid [$row ["id"]])) $paid [$row ["id"]]["paid"] = $paid [$row ["id"]]["paid"] + $row ["paid"]; else $paid [$row ["id"]] = $row; }else return NULL; $query = "SELECT f.clientid AS id, MIN(f.ondate) AS ondate FROM facturi f GROUP BY f.clientid"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while ($row = mysql_fetch_array ($result)) $minfact [$row ["id"]] = $row; if( $total ) { foreach ($total as $key => $value) { if ($paid [$key] != NULL) { $list [$key] = $value; $list [$key]["total"] = $value ["total"] - $paid [$key]["paid"]; } else $list [$key]["total"] = $value ["total"]; $list [$key]["ondate"] = $minfact [$key]["ondate"]; } }else return NULL; usort ($list, "compare"); if (count ($list) > 5) $list = array_splice ($list, 0, 5); return $list; }else return NULL; } //statistix function stats_getOps( $fromDate, $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT op.* AS id, p.name AS clientname, u.forname AS username, op.value , op.number AS number, op.ondate AS ondate , op.factid as factid, (`op`.`value`*`op`.`cursValue`) as OpValue FROM op, users u, partners p WHERE u.id = op.userid AND p.id = op.clientid AND `op`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; $result = mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) $list[ $row ["id"] ] = $row; return $list; } function stats_facturaGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name`, (`f`.`value`*`f`.`cursValue`) AS facturiValue FROM `facturi` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`type`='1' AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function stats_facturaRestantaGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name`, (`f`.`value`*`f`.`cursValue`) AS facturiValue FROM `facturi` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`value` > 0 AND `f`.`type`='1' AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function stats_comenziGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `f`.`facturaForClientRawValue`, `f`.`FacturaForClientInfo`, `f`.`ondate` FROM `comandaForClientAdv` f WHERE `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function stats_intalniriGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.* FROM `crm_events` f WHERE `f`.`categoryId`='1' AND `f`.`dateFor` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function stats_ofertareGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.* FROM `crm_events` f WHERE `f`.`categoryId`='3' AND `f`.`dateFor` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function stats_billGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `bills` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.value > 0 AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function stats_opGenerateQuery ( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `op` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.value > 0 AND `op`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function stats_howmanyFacturi( $from, $to ) { $query = stats_facturaGenerateQuery( $from , $to ); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { $counter++; foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; if( $active ) $facturiValueWithTva += $facturiValue; } } return $facturiValueWithTva; } function stats_howmanyFacturiRestanta( $from, $to ) { $query = stats_facturaGenerateQuery( $from , $to ); $pais = factura_getPaidValuesInterval($from,$to); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { $counter++; foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; if( $active ) { $paid = convertNumber($pais[ $id ]["paid"]); $facturiValueWithTva += $facturiValue-$paid; } } } return $facturiValueWithTva; } function stats_howmanyFacturiPer( $from, $to ) { $query = stats_facturaGenerateQuery( $from , $to ); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; if( $active ) { $counter++; $facturiValueWithTva += $facturiValue; } } if($counter!=0) $infoToReturn = convertNumber($facturiValueWithTva/$counter); else $infoToReturn=0; } return $infoToReturn; } function stats_howmanyComenzi( $from, $to , $currencyLink ) { $query = stats_comenziGenerateQuery( $from , $to ); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; if( $active ) { $counter++; $cursValueUsd = weHaveCurs(substr($ondate,0,4), substr($ondate,5,2), substr($ondate,8,2), 7 , "USD", $currencyLink); $cursValueEur = weHaveCurs(substr($ondate,0,4), substr($ondate,5,2), substr($ondate,8,2), 7 , "EUR", $currencyLink); if($FacturaForClientInfo=="RON" || $FacturaForClientInfo=="") $facturaValue=$facturaForClientRawValue; if($FacturaForClientInfo=="EUR") $facturaValue=convertNumber($facturaForClientRawValue*$cursValueEur); if($FacturaForClientInfo=="USD") $facturaValue=convertNumber($facturaForClientRawValue*$cursValueUsd); $facturiValueWithTva += $facturaValue; } } if($counter!=0) $infoToReturn = convertNumber($facturiValueWithTva/$counter); else $infoToReturn=0; } return $infoToReturn; } function stats_howmanyIntalniri( $from, $to ) { $query = stats_intalniriGenerateQuery( $from , $to ); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; $counter++; } } return $counter; } function stats_howmanyOfertare( $from, $to ) { $query = stats_ofertareGenerateQuery( $from , $to ); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; $counter++; } } return $counter; } function stats_howmanyBills( $from, $to ) { $query = stats_billGenerateQuery( $from , $to ); $bills = factura_searchFactura( $query ); if ($bills) { foreach( $bills as $key => $xvalue ) { $counter++; foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; if( $active ) $billsValue += $value; } } return $billsValue; } function stats_howmanyOps( $from, $to ) { $ops = stats_getOps( $from, $to ); if ($ops) { foreach( $ops as $key => $xvalue ) { $counter++; foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; $opsValue += $OpValue; } } return $opsValue; } function loadMailSettings($host,$web,$emailAdress,$emailPassword,$propertyCompanyName,$propertyCompanyEmail) { $params['host'] = $host; // The smtp server host/ip $params['port'] = 25; // The smtp server port $params['helo'] = $web; // What to use when sending the helo command. Typically, your domain/hostname $params['auth'] = TRUE; // Whether to use basic authentication or not $params['user'] = $emailAdress; // Username for authentication $params['pass'] = $emailPassword; // Password for authentication $params['papermanagement']['fromCompany'] = $propertyCompanyName; $params['papermanagement']['fromCompanyEmail'] = $propertyCompanyEmail; return $params; } function mail_sendmailip( $_ip ) { $mail_content=' '.getTraducere("Alert",$_SESSION["settings"]["default_lang"]).'
'; $mail_content.='
'.$plusText.' '.getTraducere("Cineva a incercat sa intre in software-ul management",$_SESSION["settings"]["default_lang"]).' '.$rootFolder.' '.getTraducere("de pe urmatorul ip",$_SESSION["settings"]["default_lang"]).':
'.$_ip.'
'; $mail_content.=""; $subject=getTraducere("Incercare de patrundere in sistem",$_SESSION["settings"]["default_lang"]).$rootFolder; $fdestemail="office@managenet.ro"; $from_mail = "From: \"Website Service\" ( Contact form )<$femail>"; $from_mail .= "\nReturn-Path: [office@managenet.ro] \nContent-Transfer-Encoding: 16bit\n"; $from_mail .= "Content-Type: text; charset=iso-8859-1"; $send_params['recipients'] = array($fdestemail); // The recipients (can be multiple) $send_params['headers'] = array('Content-type: text/html; charset=iso-8859-1', 'From: alert <'.$fdestemail.'>', // Headers '\nReturn-Path: office@managenet.ro\nContent-Transfer-Encoding: 16bit\nTo: '.$fdestemail, 'Subject: '.$subject,'\nReturn-Path: office@sigma-net.ro\nContent-Transfer-Encoding: 16bit\n'); $send_params['from'] = $fdestemail; // This is used as in the MAIL FROM: cmd // It should end up as the Return-Path: header $send_params['body'] = $mail_content; // The body of the email if(is_object($smtp = smtp::connect($params)) AND $smtp->send($send_params)) { $eredmeny=1; }else { $eredmeny=0; } } function sendEmailToClientWithStatictics($clientEmail,$mailContent,$mailSubject,$params,$versions,$rootFolder) { //require_once "Mail.php"; //require_once('Mail/mime.php'); $send_params['recipients'] = array($clientEmail); // The recipients (can be multiple) $send_params['headers'] = array('Content-type: text/html; charset=iso-8859-1', 'From: "'.$params['papermanagement']['fromCompany'].'" <'.$params['papermanagement']['fromCompanyEmail'].'>', // Headers 'To: '.$clientEmail, 'Subject: '.$mailSubject); $send_params['from'] = $params['papermanagement']['fromCompanyEmail']; // This is used as in the MAIL FROM: cmd $mailContentBase = 'Statistica Client - PaperManagement
'; $mailContentEnding = '
'.getTraducere("generat din SigmaNet PaperManagement v",$_SESSION["settings"]["default_lang"]).' '.$versions["actual"]["number"].'
www.sigma-net.ro
'; // It should end up as the Return-Path: header $send_params['body'] = $mailContentBase.$mailContent.$mailContentEnding; // The body of the email // $message = new Mail_mime(array('eol' => "\n")); // $message->setTXTBody(strip_tags($send_params['body'])); // for plain-text // $message->setHTMLBody($send_params['body']); // $body = $message->get(); // $headers = array ('From' => $params['papermanagement']['fromCompanyEmail'], // 'To' => $clientEmail, // 'Subject' => $mailSubject); // // $headers=$message->headers($headers); //// print_r($params); //// print_r($headers); // global $mailSettings; // //print_r($mailSettings); // $smtp = Mail::factory('smtp', // array ('host' => $params["host"], // 'port' => $params["port"], // 'auth' => true, // 'username' => $mailSettings["emailAddress"], // 'password' => $mailSettings["emailPass"])); // // // $mail = $smtp->send($clientEmail, $headers, $body); // if (PEAR::isError($mail)) { // $error["EmailSending"][0] = $smtp->errors; // $error["EmailSending"]["sentSomething"] = 0; // echo $mail->getMessage(); // return $error; // // } else { // $error["EmailSending"][0] = $smtp->errors; // $error["EmailSending"]["sentSomething"] = 1; // return $error; // } if(is_object($smtp = smtp::connect($params)) AND $smtp->send($send_params)) { // Any recipients that failed (relaying denied for example) will be logged in the errors variable. $error["EmailSending"][0] = $smtp->errors; $error["EmailSending"]["sentSomething"] = 1; return $error; } else { $error["EmailSending"][0] = $smtp->errors; $error["EmailSending"]["sentSomething"] = 0; print_r($smtp->errors); return $error; } } function insertAccessCodeForFactura($clientid,$userid,$factid,$type,$accessCode,$accessEmail) { $query = "INSERT INTO `documentViews` (`clientid`,`userid`,`factid`,`type`,`accessCode`,`accessEmail`,`views`, `datetime`, `lastIP`) VALUES ('$clientid','$userid','$factid','$type','$accessCode','$accessEmail','0',NOW(),'0.0.0.0')"; return $resultQuery = mysql_query( $query ) or die(mysql_error()); } function readAccessCodeForFactura($accessCode,$accessEmail) { $query = "SELECT * FROM `documentViews` WHERE `accessCode` = '$accessCode' AND `accessEmail` = '$accessEmail';"; $resultQuery = mysql_query( $query ) or die(mysql_error()); $accessRow = mysql_fetch_array($resultQuery); return $accessRow; } function updateAccessCodeForFactura($accessCode,$accessEmail,$lastIP) { $query = "SELECT * FROM `documentViews` WHERE `accessCode` = '$accessCode' AND `accessEmail` = '$accessEmail';"; $resultQuery = mysql_query( $query ) or die(mysql_error()); $accessRow = mysql_fetch_array($resultQuery); $facturaViews = $accessRow["views"]; $facturaViews++; $updateQuery = "UPDATE `documentViews` SET `views` = '$facturaViews', `lastViews` = NOW(), `lastIP`='$lastIP' WHERE `accessCode` = '$accessCode' AND `accessEmail` = '$accessEmail';"; return $resultUpdateQuery = mysql_query($updateQuery) or die(mysql_error()); } //commandForClient function command_getPartnerCommandForClient( $clientid, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `comandaForClient` WHERE `clientid`=$clientid AND `active` ='1' ORDER BY numberSerial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_deleteCommandForClientAdv( $facturaId ) { $query = "DELETE FROM `comandaForClientAdv` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function command_getCommandForClient( $pageno , $orderby ) { $query = "SELECT * FROM `comandaForClient` WHERE `active` ='1' ORDER BY secondserial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getcontractAngajat( $pageno = -1, $orderby ) { $query = "SELECT * FROM `contractAngajat` WHERE `active` ='1' ORDER BY secondserial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getCommandForClientPunct( $defStockId , $pageno = -1, $orderby ) { $query = "SELECT * FROM `comandaForClient` command, `users` users WHERE command.`active` ='1' AND command.`userid`=users.`id` AND users.`defstock` = '$defStockId' ORDER BY command.`id` ASC"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $counter=0; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; $counter++; } return $counter; } function command_updateUnicOnFactura( $commandId, $serviceId, $data , $enddate, $rowid) { $query = "UPDATE `comandaForClientAdvItemsDates` SET `onFactura`=1 WHERE `commandid`='$commandId' AND `serviceid`='$serviceId' AND `date`>='$data' AND `itemsId`='$rowid' AND `date`<='$enddate'"; $results = mysql_query( $query ) or die($query.mysql_error()); } function command_updateUnicNotOnFactura( $factid ) { $queryFacturi = "SELECT `f`.fromActAdvId, `fi`.* FROM `facturi_items` fi, `facturi` f WHERE `fi`.`factid`=`f`.`id` AND `f`.`id`='$factid' group by `fi`.`id`"; //echo $queryFacturi; $resultsFacturi = mysql_query( $queryFacturi ); while($row = mysql_fetch_array($resultsFacturi)) { $commandId=$row["fromActAdvId"]; $startdate = $row["startDate"]; $enddate = $row["endDate"]; $serviceId = $row["modelid"]; $query = "UPDATE `comandaForClientAdvItemsDates` SET `onFactura`=0 WHERE `commandid`='$commandId' AND `serviceid`='$serviceId' AND `date`>='$startdate' AND `date`<='$enddate'"; $results = mysql_query( $query ) or die(mysql_error()); } } function stats_commandForClientGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `comandaForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function commandForClient_delete( $facturaId ) { $query = "DELETE FROM `comandaForClient` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function command_addcommandForClient( $clientid , $userid , $stockid , $rawvalue , $value , $serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei, $onValuta , $cursValue, $shipperinfo,$directDelivery,$dangerous,$truckerinfo,$truckerAmountCurrency,$truckerAmount,$loadingPlace,$loadingDate,$dischargePlace,$dischargeDate,$addFacturaClient,$facturaAmount,$facturaAmountCurrency,$_comments,$lastSerial,$facturaAmountTva,$cursValue,$truckerAmountTva,$truckerPartnerInfo,$comments,$adr,$driversName,$driversTel,$profit, $proiectName,$descriereProiect,$managerProiect,$persoanaDeContact,$depid) { $content = addslashes ($content); $insertQ = "INSERT INTO `comandaForClient` ( `id` , `clientid` , `userid` , `stockid` , `firstserial` , `secondserial` , `itemForClient` , `numberSerial` , `loadingDate` , `facturaForClientRawValue` , `FacturaForClientValue` , `FacturaForClientInfo` , `content` , `ondate` , `active` , `printed` , `closed` , `cursValutar`, `dischargeDate`, `numeProiect`, `descriereProiect`, `managerProiect`, `persoanaDeContact`, `observatii`, `departament` ) VALUES (NULL , '$clientid', '$userid', '$stockid' , '$serial', '$serial', '', '$lastSerial', '$loadingDate', '$facturaAmount', '$facturaAmountTva', '$facturaAmountCurrency', '$content', NOW(), '1', '0', '0', '$cursValue','$dischargeDate','$proiectName' ,'$descriereProiect', '$managerProiect' , '$persoanaDeContact','$_comments','$depid');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function commandForClient_registerItems( $factid , $name, $description , $inceput , $predare, $realizat, $fazaAmount, $fazaAmountCurrency , $fazaAmountTva ) { $query = "INSERT INTO comandaForClientItems VALUES (NULL, '$factid', '$name', '$description' ,'$inceput' , '$predare', '$realizat' , '$fazaAmount' , '$fazaAmountCurrency' , '$fazaAmountTva', NOW());"; $result = mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function commandForClient_registerItemsHr( $factid , $id, $description , $inceput , $predare, $realizat ) { $query = "INSERT INTO comandaForClientItemsHr VALUES (NULL, '$factid', '$id', '$description' ,'$inceput' , '$predare', '$realizat' , NOW());"; mysql_query( $query ) or die(mysql_error()); } function commandForClient_registerItemsFazaHr( $factid , $id, $description , $inceput , $predare, $realizat , $fazaid , $fromoras , $tooras , $carid ) { $query = "INSERT INTO comandaForClientFazaItemsHr VALUES (NULL, '$factid', '$id', '$description' ,'$inceput' , '$predare', '$realizat' , NOW() , '$fazaid' , '$fromoras' , '$tooras' , '$carid');"; mysql_query( $query ) or die(mysql_error()); } function commandForClient_registerItemsAntreprenorHr( $factid , $id, $description , $inceput , $predare, $realizat , $fazaid , $fromoras , $tooras , $carid , $subAmount , $subAmountCurrency , $subAmountTva ) { $query = "INSERT INTO comandaForClientFazaItemsProviders VALUES (NULL, '$factid', '$id', '$description' ,'$inceput' , '$predare', '$realizat' , NOW() , '$fazaid' , '$fromoras' , '$tooras' , '$carid' , '$subAmount' , '$subAmountCurrency' , '$subAmountTva');"; mysql_query( $query ) or die(mysql_error()); } function commandForClient_unRegisterItems( $factid ) { $query = "DELETE FROM `comandaForClientItems` WHERE `comandaForClientItems`.`documentid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); } function commandForClient_unRegisterItemsHr( $factid ) { $query = "DELETE FROM `comandaForClientItemsHr` WHERE `comandaForClientItemsHr`.`documentid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); } function commandForClient_unRegisterItemsFazaHr( $factid ) { $query = "DELETE FROM `comandaForClientFazaItemsHr` WHERE `comandaForClientFazaItemsHr`.`documentid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); } function commandForClient_unRegisterItemsAntreprenorHr( $factid ) { $query = "DELETE FROM `comandaForClientFazaItemsProviders` WHERE `comandaForClientFazaItemsProviders`.`documentid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); } function commandForClient_setActiveNess( $factid , $state ) { $update = "UPDATE `comandaForClient` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function commandForClient_modFactura( $id , $clientid , $userid , $stockid , $rawvalue , $value ,$serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei , $onValuta , $cursValue, $shipperinfo,$directDelivery,$dangerous,$truckerinfo,$truckerAmountCurrency,$truckerAmount,$loadingPlace,$loadingDate,$dischargePlace,$dischargeDate,$addFacturaClient,$facturaAmount,$facturaAmountCurrency,$_comments, $lastSerial,$facturaAmountTva,$cursValue,$truckerAmountTva,$truckerPartnerInfo,$comments,$adr,$driversName,$driversTel,$profit, $proiectName,$descriereProiect,$managerProiect,$persoanaDeContact,$depid) { $content = addslashes ($content); $updateQ = "UPDATE `comandaForClient` SET `clientid` = '$clientid', `userid` = '$userid', `stockid` = '$stockid', `numberSerial` = '$lastSerial', `loadingDate` = '$loadingDate', `content` = '$content', `facturaForClientRawValue` = '$facturaAmount', `FacturaForClientValue` = '$facturaAmountTva', `FacturaForClientInfo` = '$facturaAmountCurrency', `dischargeDate` = '$dischargeDate', `numeProiect` = '$proiectName', `descriereProiect` = '$descriereProiect', `managerProiect` = '$managerProiect', `persoanaDeContact` = '$persoanaDeContact', `observatii` = '$_comments', `departament`= '$depid', `cursValutar` = '$cursValue' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function commandForClient_setPrinted( $id , $value ) { $updateQ = "UPDATE `comandaForClient` SET `printed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function commandForClient_setClosed( $id , $value ) { $updateQ = "UPDATE `comandaForClient` SET `closed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function commandForClient_setSerial( $id , $serial ) { $update = "UPDATE `comandaForClient` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function commandForClient_getFacturi() { $select = "SELECT * FROM `comandaForClient`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function commandForClient_getFactura( $id ) { $select = "SELECT * FROM `comandaForClient` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function generateDataFromComandaForClient( $id ) { $select = "SELECT * FROM `comandaForClient` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function generateDataFromordinDeplasare( $id ) { $select = "SELECT * FROM `ordinDeplasare` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function generateDataFromDecont( $id ) { $select = "SELECT * FROM `decont` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } //nincs megcsinalva!!!!!!!!!!!! function commandForClient_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $firstserial, $secondserial, $serial,$viewall=1,$userid=0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($viewall!="1") { $viewquery= " AND ( f.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid') "; } if($filter_menu == "platite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`number` = '$searchval'"; else $plus_search="AND `p`.`name` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`name` FROM `comandaForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'".$viewquery." ORDER BY $orderby $ordermode"; $result = mysql_query($query) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { if(convertNumber($pais[ $row["id"] ]["paid"])==convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`name` FROM `comandaForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1'".$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu == "neplatite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`number` = '$searchval'"; else $plus_search="AND `p`.`name` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`name` FROM `comandaForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'".$viewquery." ORDER BY $orderby $ordermode"; $result = mysql_query($query) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { //fizetve if(convertNumber($pais[ $row["id"] ]["paid"])!=convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`name` FROM `comandaForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1'".$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu != "platite" && $filter_menu != "neplatite" && $filter_menu != "expirate") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial") { if($firstserial!=NULL) $serialFilter.= " AND `f`.`firstserial` = '$firstserial'"; if($secondserial!=NULL) $serialFilter.= " AND `f`.`secondserial` = '$secondserial'"; if($serial!=NULL) $serialFilter.= " AND `f`.`numberSerial` = '$serial'"; $query = "SELECT `f`.*, `p`.`name` FROM `comandaForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$serialFilter.$filterMenuSql.$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } else { $query = "SELECT `f`.*, `p`.`name` FROM `comandaForClient` f, `partners` p WHERE `p`.`name` LIKE '%$searchval%' AND `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql.$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } } return $query; } function commandForClient_searchGenerateQueryForAngajatGeneral( $hrid ) { $query = "SELECT `f`.*, `fitems`.`documentid` , `fitems`.`hrid` FROM `comandaForClient` f, `hr` h , `comandaForClientItemsHr` fitems WHERE `h`.`id` = `fitems`.`hrid` AND `f`.`id` = `fitems`.`documentid` AND `f`.active = '1' AND `h`.`id` = '$hrid' GROUP BY `f`.`id` "; return $query; } function commandForClient_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function commandForClient_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } //ordinDeplasare function command_getPartnerordinDeplasare( $clientid, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `ordinDeplasare` WHERE `clientid`=$clientid AND `active` ='1' ORDER BY numberSerial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getordinDeplasare( $pageno, $orderby , $date ) { $year = substr($date,0,4); $month = substr($date,5,2); $day = substr($date,8,2); $monthNow = $month; $afterDay = 30; if($monthNow%2 != 0 && $monthNow!=2 && $monthNow < 8) $afterDay ++; if($monthNow%2 == 0 && $monthNow >= 8) $afterDay ++; if($monthNow==2) $afterDay --; //if($monthNow<10) $monthNow = '0'.$monthNow; $firstDate = $year."-".$monthNow."-01"; $lastDate = $year."-".$monthNow."-".$afterDay; $query = "SELECT * FROM `ordinDeplasare` WHERE `active` ='1' AND `ondate` BETWEEN '$firstDate' AND '$lastDate' ORDER BY firstserial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function stats_ordinDeplasareGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `ordinDeplasare` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function ordinDeplasare_delete( $facturaId ) { $query = "DELETE FROM `ordinDeplasare` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } //nincs kijavitva!!!!!!!!!!!!!!!!!1 function command_addordinDeplasare($nrTemplate, $hrid , $userid , $defstock , $nrDocument , $delegatPentru , $content , $fromtaraid,$fromjudetid, $fromorasid ,$totaraid,$tojudetid, $toorasid , $datadela , $datala , $alteLocatii , $diurna , $diurnaPret , $comments , $distance , $fuelTax , $fuelPrice , $carid , $fromActId , $fazaId , $fuelTax , $fuelPrice, $carid , $dataManuala , $transportBon, $cazareBon ) { $content = addslashes ($content); $insertQ = "INSERT INTO `ordinDeplasare` ( `id` , `hrId` , `userid` , `stockid` , `firstserial` , `fromtara`, `fromjudet`, `from` , `totara`, `tojudet`, `to` , `datadela` , `datala` , `content` , `active` , `printed` , `closed` , `ondate` , `cursValutar` , `comments` , `fromActId` , `fazaId` , `alteLocatii` , `diurna` , `diurnaPret` , `delegatPentru`, `fuelTax`, `fuelPrice`, `carid`, `transportBon`, `cazareBon`, `nrTemplate` ) VALUES ( NULL , '$hrid', '$userid', '$defstock', '$nrDocument','$fromtaraid','$fromjudetid', '$fromorasid', '$totaraid','$tojudetid', '$toorasid', '$datadela', '$datala', '$content', '1', '0', '0', '$dataManuala' , '1', '$comments', '$fromActId', '$fazaId', '$alteLocatii', '$diurna', '$diurnaPret', '$delegatPentru' , '$fuelTax' , '$fuelPrice' , '$carid','$transportBon','$cazareBon','$nrTemplate');"; $result = mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function ordinDeplasare_registerItems( $factid , $idBon ) { $query = "INSERT INTO ordinDeplasareItems VALUES (NULL, '$factid', NOW() , '$idBon');"; mysql_query( $query ) or die(mysql_error()); } function ordinDeplasare_unRegisterItems( $factid ) { $query = "DELETE FROM `ordinDeplasareItems` WHERE `ordinDeplasareItems`.`documentid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); } function ordinDeplasare_setActiveNess( $factid , $state ) { $update = "UPDATE `ordinDeplasare` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function ordinDeplasare_modFactura($nrTemplate, $id , $hrid , $userid , $defstock , $nrDocument , $delegatPentru , $content ,$fromtaraid,$fromjudetid, $fromorasid ,$totaraid,$tojudetid, $toorasid , $datadela , $datala , $alteLocatii , $diurna , $diurnaPret , $comments , $distance , $fuelTax , $fuelPrice , $carid , $dataManuala , $transportBon , $cazareBon) { $content = addslashes ($content); $updateQ = "UPDATE `ordinDeplasare` SET `hrId` = '$hrid', `firstserial` = '$nrDocument', `delegatPentru` = '$delegatPentru', `content` = '$content', `fromtara` = '$fromtaraid', `fromjudet` = '$fromjudetid', `from` = '$fromorasid', `totara` = '$totaraid', `tojudet` = '$tojudetid', `to` = '$toorasid', `datadela` = '$datadela', `datala` = '$datala', `ondate` = '$dataManuala' , `alteLocatii` = '$alteLocatii', `diurna` = '$diurna', `diurnaPret` = '$diurnaPret', `fuelTax` = '$fuelTax', `fuelPrice` = '$fuelPrice', `carid` = '$carid', `transportBon` = '$transportBon', `cazareBon` = '$cazareBon', `nrTemplate`='$nrTemplate' WHERE `id` = '$id' LIMIT 1;" ; $result=mysql_query( $updateQ ) or die(mysql_error()); } function ordinDeplasare_setPrinted( $id , $value ) { $updateQ = "UPDATE `ordinDeplasare` SET `printed` = '$value' WHERE `id` = '$id' LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function ordinDeplasare_setClosed( $id , $value ) { $updateQ = "UPDATE `ordinDeplasare` SET `closed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function ordinDeplasare_setSerial( $id , $serial ) { $update = "UPDATE `ordinDeplasare` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ); } function ordinDeplasare_getFacturi() { $select = "SELECT * FROM `ordinDeplasare`"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function ordinDeplasare_getFactura( $id ) { $select = "SELECT * FROM `ordinDeplasare` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } //nincs megcsinalva!!!!!!!!!!!! function ordinDeplasare_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; //$fromDate = mysql_prevDay( $fromDate ); $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "platite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`firstserial` = '$searchval'"; else $plus_search="AND (`p`.`forname` LIKE '%$searchval%' OR `p`.`lastname` LIKE '%$searchval%')"; $query = "SELECT `f`.*, `p`.`name` FROM `ordinDeplasare` f, `hr` p WHERE `p`.`id` = `f`.`hrId` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; $result = mysql_query( $query ) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { if(convertNumber($pais[ $row["id"] ]["paid"])==convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`name` FROM `ordinDeplasare` f, `hr` p WHERE `p`.`id` = `f`.`hrId` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1' ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu != "platite" && $filter_menu != "neplatite" && $filter_menu != "expirate") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial" && $searchval!=NULL) $query = "SELECT `f`.*, `p`.`forname` FROM `ordinDeplasare` f, `hr` p WHERE `f`.`firstserial` = '$searchval' AND `p`.`id` = `f`.`hrId` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; else $query = "SELECT `f`.*, `p`.`forname` FROM `ordinDeplasare` f, `hr` p WHERE (`p`.`forname` LIKE '%$searchval%' OR `p`.`lastname` LIKE '%$searchval%') AND `p`.`id` = `f`.`hrId` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; } return $query; } function ordinDeplasare_searchGenerateQueryFromActId( $fromActId ) { $query = "SELECT `f`.*, `p`.`forname` FROM `ordinDeplasare` f, `hr` p WHERE fromActId = '$fromActId' AND `p`.`id` = `f`.`hrId` ORDER BY ondate DESC"; return $query; } function ordinDeplasare_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function ordinDeplasare_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function getOrdinDeplasareRegisteredItems ($commandId) { $query = "SELECT * FROM ordinDeplasareItems WHERE documentid = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getOrdinDeplasareRegisteredItemsCount ($commandId) { $query = "SELECT * FROM ordinDeplasareItems WHERE documentid = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function getCommandForPartnerRegisteredItems ($commandId) { $query = "SELECT * FROM comandaForClientItems WHERE documentid = $commandId ORDER by id ASC"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerRegisteredItem ($itemId) { $query = "SELECT * FROM comandaForClientItems WHERE id = $itemId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerRegisteredItemsCount ($commandId) { $query = "SELECT * FROM comandaForClientItems WHERE documentid = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function getCommandForPartnerRegisteredItemsHr ($commandId) { $query = "SELECT * FROM comandaForClientItemsHr WHERE documentid = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerRegisteredItemsCountHr ($commandId) { $query = "SELECT * FROM comandaForClientItemsHr WHERE documentid = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function getCommandForPartnerRegisteredFazaItemsHr ($commandId,$fazaid) { $query = "SELECT * FROM comandaForClientFazaItemsHr WHERE documentid = $commandId AND fazaid = $fazaid ORDER by id ASC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerRegisteredFazaItemsCountHr ($commandId,$fazaid) { $query = "SELECT * FROM comandaForClientFazaItemsHr WHERE documentid = $commandId AND fazaid = $fazaid;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function getCommandForPartnerRegisteredFazaItemsHrStats ($commandId,$hrid) { $query = "SELECT * FROM comandaForClientFazaItemsHr WHERE documentid = $commandId AND hrid = $hrid ORDER by id ASC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerRegisteredFazaItemsStatsCountHr ($commandId,$hrid) { $query = "SELECT * FROM comandaForClientFazaItemsHr WHERE documentid = $commandId AND hrid = $hrid;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function getCommandForPartnerRegisteredAntreprenorItemsHr ($commandId,$fazaid) { $query = "SELECT * FROM comandaForClientFazaItemsProviders WHERE documentid = $commandId AND fazaid = $fazaid ORDER by id ASC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerRegisteredAntreprenorItemsCountHr ($commandId,$fazaid) { $query = "SELECT * FROM comandaForClientFazaItemsProviders WHERE documentid = $commandId AND fazaid = $fazaid;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function getCommandFromPartnerRegisteredItems ($commandId) { $query = "SELECT * FROM comandaForPartnerItems WHERE documentid = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandFromPartnerRegisteredItemsCount ($commandId) { $query = "SELECT * FROM comandaForPartnerItems WHERE documentid = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function getUser($user) { $query="SELECT * FROM users WHERE id='$user'"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } //StickUser Acces ellenorzo function getAnyCmStickAccessCode($usercode) { $query="SELECT * FROM users WHERE `CmStickSecret`=PASSWORD('$usercode')"; $result=mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)>0) return true; else return false; } function getGeneralCmStickAccessCode($settingCode) { $query="SELECT * FROM `settings` WHERE `type`='CmStickAccess' AND `value`=PASSWORD('$settingCode')"; $result=mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)>0) return true; else return false; } function getCmStickAccessCodeForUser($userid,$usercode) { $query="SELECT * FROM `users` WHERE `id`='$userid' AND `CmStickSecret`=PASSWORD('$usercode')"; $result=mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)>0) return true; else return false; } //contractForClient function contract_getPartnercontractForClient( $clientid, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `contractForClient` WHERE `clientid`=$clientid AND `active` ='1' ORDER BY numberSerial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function contract_getcontractForClient( $pageno = -1, $orderby ) { $query = "SELECT * FROM `contractForClient` WHERE `active` ='1' ORDER BY secondserial DESC"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function bon_getBonuri( $pageno = -1, $orderby,$loc_id ) { if ($loc_id) $loc="AND `loc_id`='$loc_id'"; else $loc=''; $query = "SELECT * FROM `bonConsum` WHERE `active` ='1' $loc ORDER BY number DESC"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function stats_contractForClientGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `contractForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function contractForClient_delete( $facturaId ) { $query = "DELETE FROM `contractForClient` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } //nincs kijavitva!!!!!!!!!!!!!!!!!1 function contract_addcontractForClient( $clientid , $userid , $stockid , $rawvalue , $value , $serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei, $onValuta , $cursValue, $shipperinfo,$directDelivery,$dangerous,$truckerinfo,$truckerAmountCurrency,$truckerAmount,$loadingPlace,$loadingDate,$dischargePlace,$dischargeDate,$addFacturaClient,$facturaAmount,$facturaAmountCurrency,$_comments,$lastSerial,$facturaAmountTva,$cursValue,$truckerAmountTva,$truckerPartnerInfo,$comments,$adr,$driversName,$driversTel,$profit, $proiectName,$descriereProiect,$managerProiect,$persoanaDeContact,$functia,$functiaclient,$reprezentant,$fromActId,$depid) { $content = addslashes ($content); $insertQ = "INSERT INTO `contractForClient` ( `id` , `clientid` , `userid` , `stockid` , `firstserial` , `secondserial` , `itemForClient` , `numberSerial` , `loadingDate` , `facturaForClientRawValue` , `FacturaForClientValue` , `FacturaForClientInfo` , `content` , `ondate` , `active` , `printed` , `closed` , `cursValutar`, `dischargeDate`, `numeProiect`, `descriereProiect`, `managerProiect`, `persoanaDeContact`, `functia`, `reprezentant`, `functiaclient`, `fromActId`, `departament` ) VALUES (NULL , '$clientid', '$userid', '$stockid' , '$serial', '$serial', '', '$lastSerial', '$loadingDate', '$facturaAmount', '$facturaAmountTva', '$facturaAmountCurrency', '$content', NOW(), '1', '0', '0', '$cursValue','$dischargeDate','$proiectName' ,'$descriereProiect', '$managerProiect' , '$persoanaDeContact', '$functia', '$reprezentant', '$functiaclient','$fromActId','$depid');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function contractForClient_registerItems( $factid , $name, $description , $inceput , $predare, $realizat, $fazaAmount, $fazaAmountCurrency , $fazaAmountTva ) { $query = "INSERT INTO contractForClientItems VALUES (NULL, '$factid', '$name', '$description' ,'$inceput' , '$predare', '$realizat' , '$fazaAmount' , '$fazaAmountCurrency' , '$fazaAmountTva', NOW());"; mysql_query( $query ) or die(mysql_error()); } function contractForClient_unRegisterItems( $factid ) { $query = "DELETE FROM `contractForClient` WHERE `comandaForClientItems`.`documentid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); } function contractForClient_setActiveNess( $factid , $state ) { $update = "UPDATE `contractForClient` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function contractForClient_modFactura( $id , $clientid , $userid , $stockid , $rawvalue , $value ,$serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei , $onValuta , $cursValue, $shipperinfo,$directDelivery,$dangerous,$truckerinfo,$truckerAmountCurrency,$truckerAmount,$loadingPlace,$loadingDate,$dischargePlace,$dischargeDate,$addFacturaClient,$facturaAmount,$facturaAmountCurrency,$_comments, $lastSerial,$facturaAmountTva,$cursValue,$truckerAmountTva,$truckerPartnerInfo,$comments,$adr,$driversName,$driversTel,$profit,$shippername, $proiectName,$descriereProiect,$managerProiect,$persoanaDeContact,$functia,$functiaclient,$reprezentant,$depid) { $content = addslashes ($content); $updateQ = "UPDATE `contractForClient` SET `clientid` = '$clientid', `userid` = '$userid', `stockid` = '$stockid', `numberSerial` = '$lastSerial', `loadingDate` = '$loadingDate', `content` = '$content', `facturaForClientRawValue` = '$facturaAmount', `FacturaForClientValue` = '$facturaAmountTva', `FacturaForClientInfo` = '$facturaAmountCurrency', `dischargeDate` = '$dischargeDate', `numeProiect` = '$proiectName', `descriereProiect` = '$descriereProiect', `managerProiect` = '$managerProiect', `persoanaDeContact` = '$persoanaDeContact', `functia` = '$functia', `reprezentant` = '$reprezentant', `functiaclient` = '$functiaclient', `departament` = '$depid', `cursValutar` = '$cursValue' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function contractForClient_setPrinted( $id , $value ) { $updateQ = "UPDATE `contractForClient` SET `printed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function contractForClient_setClosed( $id , $value ) { $updateQ = "UPDATE `contractForClient` SET `closed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function contractForClient_setSerial( $id , $serial ) { $update = "UPDATE `contractForClient` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function contractForClient_getFacturi() { $select = "SELECT * FROM `contractForClient`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function contractForClient_getFactura( $id ) { $select = "SELECT * FROM `contractForClient` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function actAditional_getFactura( $id ) { $select = "SELECT * FROM `actAditional` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function contractAngajat_getFactura( $id ) { $select = "SELECT * FROM `contractAngajat` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function generateDataFromcontractForClient( $id ) { $select = "SELECT * FROM `contractForClient` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function generateDataFromcontractAngajatHr( $hrid ) { $select = "SELECT * FROM `contractAngajat` WHERE `hrid`='$hrid' ORDER BY id DESC LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function generateDataFromcontractForPartner( $id ) { $select = "SELECT * FROM `contractForPartner` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } //nincs megcsinalva!!!!!!!!!!!! function contractForClient_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $firstserial, $secondserial, $serial,$viewall=1,$userid=0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; if($viewall!="1") { $viewquery= " AND ( f.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid') "; } $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "platite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`number` = '$searchval'"; else $plus_search="AND `p`.`name` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`name` FROM `contractForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'".$viewquery." ORDER BY $orderby $ordermode"; $result = mysql_query($query) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { if(convertNumber($pais[ $row["id"] ]["paid"])==convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`name` FROM `contractForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1'".$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu == "neplatite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`number` = '$searchval'"; else $plus_search="AND `p`.`name` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`name` FROM `contractForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'".$viewquery." ORDER BY $orderby $ordermode"; $result = mysql_query($query) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { //fizetve if(convertNumber($pais[ $row["id"] ]["paid"])!=convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`name` FROM `contractForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1'".$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu != "platite" && $filter_menu != "neplatite" && $filter_menu != "expirate") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial") { if($firstserial!=NULL) $serialFilter.= " AND `f`.`firstserial` = '$firstserial'"; if($secondserial!=NULL) $serialFilter.= " AND `f`.`secondserial` = '$secondserial'"; if($serial!=NULL) $serialFilter.= " AND `f`.`numberSerial` = '$serial'"; $query = "SELECT `f`.*, `p`.`name` FROM `contractForClient` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$serialFilter.$filterMenuSql.$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } else { $query = "SELECT `f`.*, `p`.`name` FROM `contractForClient` f, `partners` p WHERE `p`.`name` LIKE '%$searchval%' AND `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql.$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } } return $query; } function contractForClient_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function contractForClient_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function getcontractForClientRegisteredItems ($commandId) { $query = "SELECT * FROM contractForClientItems WHERE documentid = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getcontractForClientRegisteredItemsCount ($commandId) { $query = "SELECT * FROM contractForClientItems WHERE documentid = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } //hr function hr_addUser( $array ) { $query="select * from `hr` where `forname`='".$array["forname"]."' and `lastname`='".$array["lastname"]."'"; //echo $query; $res=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($res); if($row["id"]!=NULL) return NULL; $query="select MAX(id) from `hr`"; $res=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($res); $insertQ = "INSERT INTO `hr` ( `id` , `cnp` , `forname` , `lastname` , `gender` , `birth` , `email` , `homephone` , `mobile` , `buletin` , `specialDomain` , `observations` , `adresa` , `judet` , `oras` , `tara` , `eliberatde` , `dataEliberarii` , `salariubrut` , `sporuri` , `indemnizatii` , `adaosuri`, `punctDeLucru` , `activ`,`telemarketing`,`contact`,`vanzare`,`executare`,`tipAngajat`,`userid`,`Impozit`,`Tva`,`bank`,`iban`,`main_departament`) VALUES ( '".($row["MAX(id)"]+1)."','".$array["cnp"]."', '".$array["forname"]."', '".$array["lastname"]."', '".$array["gender"]."','".$array["birth"]."','".$array["email"]."','".$array["homephone"]."','".$array["mobile"]."', '".$array["buletin"]."', '".$array["specialDomain"]."','".$array["observations"]."','".$array["adresa"]."','".$array["judet"]."','".$array["oras"]."','".$array["tara"]."','".$array["eliberatde"]."','".$array["dataEliberarii"]."','".$array["salariubrut"]."','".$array["sporuri"]."','".$array["indemnizatii"]."','".$array["adaosuri"]."','".$array["punctDeLucru"]."','".$array["activ"]."','".$array["telemarketing"]."','".$array["contact"]."','".$array["vanzare"]."','".$array["executare"]."','".$array["tipAngajat"]."','".$array["hrUserId"]."','".$array["impozit"]."','".$array["tva"]."','".$array["bank"]."','".$array["iban"]."','".$array["main_departament"]."');"; mysql_query( $insertQ ) or die(mysql_error()); return ($row["MAX(id)"]+1); } function hr_addOras( $hrid,$orasid ) { $inserteles="INSERT INTO `hr_orase`(`id`,`hrid`,`orasid`) VALUES (NULL,'$hrid','$orasid')"; mysql_query($inserteles) or die(mysql_error()); } function hr_addClient( $hrid,$clientid ) { $inserteles="INSERT INTO `hr_clienti`(`id`,`hrid`,`clientid`) VALUES (NULL,'$hrid','$clientid')"; mysql_query($inserteles) or die(mysql_error()); } function hr_delOras( $hrid, $orasid ) { $query = "DELETE FROM `hr_orase` WHERE `hrid`='$hrid' and `orasid`='$orasid' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } function hr_delClient( $hrid, $clientid ) { $query = "DELETE FROM `hr_clienti` WHERE `hrid`='$hrid' and `clientid`='$clientid' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } function hr_getOrase($userid) { $query="SELECT * FROM `hr_orase` where `hrid`='$userid'"; $result=mysql_query( $query ) or die(mysql_error()); return $result; } function hr_getClients($userid) { $query="SELECT * FROM `hr_clienti` where `hrid`='$userid'"; $result=mysql_query( $query ) or die(mysql_error()); return $result; } function hr_hasOras($punctid) { $query="SELECT * FROM `hr_orase` where `orasid`='$punctid'"; $result=mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)==0) return false; return true; } function hr_getOrasDriverNum($punctid) { $query="SELECT * FROM `hr_orase` where `orasid`='$punctid'"; $result=mysql_query( $query ) or die(mysql_error()); return mysql_num_rows($result); } //megyekre leosztas function hr_addJudet( $hrid, $judetid ) { $inserteles="INSERT INTO `hr_judete`(`id`,`hrid`,`judetid`) VALUES (NULL,'$hrid','$judetid')"; mysql_query($inserteles); } function hr_delJudet( $hrid, $judetid ) { $query = "DELETE FROM `hr_judete` WHERE `hrid`='$hrid' and `judetid`='$judetid' LIMIT 1;"; mysql_query( $query ) or die(mysql_error()); } function hr_getJudete($userid) { $query="SELECT * FROM `hr_judete` where `hrid`='$userid'"; $result=mysql_query( $query ) or die(mysql_error()); return $result; } function hr_hasJudet($punctid) { $query="SELECT * FROM `hr_judete` where `judetid`='$punctid'"; $result=mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)==0) return false; return true; } function hr_getJudetDriverNum($punctid) { $query="SELECT * FROM `hr_judete` where `judetid`='$punctid'"; $result=mysql_query( $query ) or die(mysql_error()); return mysql_num_rows($result); } //megyekre leosztas vege function hr_updateUser( $userid , $array ) { $update = "UPDATE `hr` SET `cnp`='".$array["cnp"]."', `forname`='".$array["forname"]."', `lastname`='".$array["lastname"]."', `gender`='".$array["gender"]."', `birth`='".$array["birth"]."', `email`='".$array["email"]."', `homephone`='".$array["homephone"]."', `mobile`='".$array["mobile"]."', `buletin`='".$array["buletin"]."', `specialDomain`='".$array["specialDomain"]."', `adresa`='".$array["adresa"]."', `judet`='".$array["judet"]."', `oras`='".$array["oras"]."', `tara`='".$array["tara"]."', `eliberatde`='".$array["eliberatde"]."', `dataEliberarii`='".$array["dataEliberarii"]."', `salariubrut`='".$array["salariubrut"]."', `sporuri`='".$array["sporuri"]."', `indemnizatii`='".$array["indemnizatii"]."', `adaosuri`='".$array["adaosuri"]."', `punctDeLucru`='".$array["punctDeLucru"]."', `observations`='".$array["observations"]."', `telemarketing`='".$array["telemarketing"]."', `contact`='".$array["contact"]."', `vanzare`='".$array["vanzare"]."', `executare`='".$array["executare"]."', `tipAngajat`='".$array["tipAngajat"]."', `bank`='".$array["bank"]."', `iban`='".$array["iban"]."', `Impozit`='".$array["impozit"]."', `Tva`='".$array["tva"]."', `userid`='".$array["hrUserId"]."', `main_departament`='".$array["main_departament"]."', `activ`='".$array["activ"]."' WHERE `id`='$userid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function hr_updateSingleUser( $userid , $array ) { $update = "UPDATE `hr` SET `cnp`='".$array["cnp"]."', `forname`='".$array["forname"]."', `lastname`='".$array["lastname"]."', `gender`='".$array["gender"]."', `birth`='".$array["birth"]."', `email`='".$array["email"]."', `homephone`='".$array["homephone"]."', `mobile`='".$array["mobile"]."', `buletin`='".$array["buletin"]."', `specialDomain`='".$array["specialDomain"]."', `main_departament`='".$array["main_departament"]."', `observations`='".$array["observations"]."' WHERE `id`='$userid' LIMIT 1;"; $Result = mysql_query( $update ) or die(mysql_error()); $totalResult = $Result; return $totalResult; } function hr_getUser( $userid ) { $query = "SELECT * FROM `hr` WHERE `id`='$userid' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function hr_getUserAsoc( $adminuserid ) { $query = "SELECT * FROM `hr` WHERE `userid`='$adminuserid' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function hr_getAdminUserAsoc( $hruserid ) { $query = "SELECT * FROM `hr` WHERE `id`='$hruserid' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $result ); return ( $row["userid"] ); } function hr_getSofors( ) { $query = "SELECT * FROM `hr` WHERE `specialDomain` BETWEEN 6999 AND 7006 "; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return $result; } function hr_getSoforsTel($id ) { $query = "SELECT * FROM `hr` WHERE `id`=$id LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return $result; } function hr_getSoforsOras($id ) { $query = "SELECT * FROM `hr` WHERE `id`=$id LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if($result) { $punct=mysql_fetch_array($result); $punctid=$punct["punctDeLucru"]; $query2="SELECT * FROM locations where `id`=$punctid"; $result2 = mysql_query( $query2 ) or die(mysql_error()); $oras=mysql_fetch_array($result2); $orasid=$oras["oras"]; if($id<10000) $query3="SELECT * FROM `cities` where `id`=$orasid"; else $query3="SELECT * FROM `cities_new` where `id`=$orasid"; $result3 = mysql_query( $query3 ) or die(mysql_error()); } //if( mysql_affected_rows() <= 0 )return NULL; //return ( $row = mysql_fetch_array( $result ) ); return $result3; } function hr_getUsers() { $select = "SELECT * FROM `hr` ORDER by `forname`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $users[ $row["id"] ] = $row; } return $users; } //cars function cars_addCar( $array ) { $insertQ = "INSERT INTO `cars` ( `id` , `nameCar`, `carType` , `plate` , `registrating` , `fueltax`,`RCA_data`,`RCA_Nr_polita`,`RCA_partener`,`Casco_data`,`Casco_Nr_polita`,`Casco_partener`,`Data_exp_verificare`,`stationare`,`Data_exp_rovigneta`,`Data_exp_trusa`,`Data_exp_stingator`,`Data_exp_licenta`,`Data_exp_tahograf`,`userid`,`ondate`) VALUES ( NULL ,'".$array["nameCar"]."', '".$array["carstype"]."' , '".$array["plate"]."', '".$array["registrating"]."', '".$array["fueltax"]."', '".$array["expdatecar1"]."', '".$array["nrpolita1"]."', '".$array["furnizor"]."', '".$array["expdatecar2"]."', '".$array["nrpolita2"]."', '".$array["furnizor2"]."', '".$array["expdatecar3"]."','".$array["stationare"]."', '".$array["expdatecar4"]."', '".$array["expdatecar5"]."', '".$array["expdatecar6"]."', '".$array["expdatecar7"]."', '".$array["expdatecar8"]."','".$_SESSION["user"]["id"]."','NOW()');"; mysql_query( $insertQ ) or die(mysql_error()); return mysql_insert_id(); } function cars_ExpiredCarsRCA() { $query = "SELECT * FROM cars"; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { if($row["RCA_data"]!="0000-00-00") { $date=$row["RCA_data"]; $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareExpiredRca"] * 24 * 60 * 59); $todayDate = date("Y-m-d",$nextWeek); $day=subtract_dates($date, $todayDate); if($day>=1) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=6;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function cars_ExpiredCarsCasco() { $query = "SELECT * FROM cars"; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { if($row["Casco_data"]!="0000-00-00") { $date=$row["Casco_data"]; $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareExpiredCasco"] * 24 * 60 * 59); $todayDate = date("Y-m-d",$nextWeek); $day=subtract_dates($date, $todayDate); if($day>=1) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=8;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function cars_ExpiredCarsVerification() { $query = "SELECT * FROM cars"; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { if($row["Data_exp_verificare"]!="0000-00-00") { $date=$row["Data_exp_verificare"]; $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareExpiredVerification"] * 24 * 60 * 59); $todayDate = date("Y-m-d",$nextWeek); $day=subtract_dates($date, $todayDate); if($day>=1) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=15;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function cars_ExpiredCarsRovigneta() { $query = "SELECT * FROM cars"; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { if($row["Data_exp_rovigneta"]!="0000-00-00") { $date=$row["Data_exp_rovigneta"]; $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareExpiredRovigneta"] * 24 * 60 * 59); $todayDate = date("Y-m-d",$nextWeek); $day=subtract_dates($date, $todayDate); if($day>=1) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=16;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function cars_ExpiredCarsTrusa() { $query = "SELECT * FROM cars"; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { if($row["Data_exp_trusa"]!="0000-00-00") { $date=$row["Data_exp_trusa"]; $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareExpiredTrusa"] * 24 * 60 * 59); $todayDate = date("Y-m-d",$nextWeek); $day=subtract_dates($date, $todayDate); if($day>=1) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=17;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function cars_ExpiredCarsStingator() { $query = "SELECT * FROM cars"; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { if($row["Data_exp_stingator"]!="0000-00-00") { $date=$row["Data_exp_stingator"]; $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareExpiredStingator"] * 24 * 60 * 59); $todayDate = date("Y-m-d",$nextWeek); $day=subtract_dates($date, $todayDate); if($day>=1) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=18;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function cars_ExpiredCarsLicenta() { $query = "SELECT * FROM cars"; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { if($row["Data_exp_licenta"]!="0000-00-00") { $date=$row["Data_exp_licenta"]; $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareExpiredLicenta"] * 24 * 60 * 59); $todayDate = date("Y-m-d",$nextWeek); $day=subtract_dates($date, $todayDate); if($day>=1) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=19;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function cars_ExpiredCarsTahograf() { $query = "SELECT * FROM cars"; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { if($row["Data_exp_tahograf"]!="0000-00-00") { $date=$row["Data_exp_tahograf"]; $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareExpiredTahograf"] * 24 * 60 * 59); $todayDate = date("Y-m-d",$nextWeek); $day=subtract_dates($date, $todayDate); if($day>=1) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=20;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function cars_getCarsType() { $query="SELECT * FROM `carsType` order by `id`"; $result=mysql_query( $query ) or die(mysql_error()); return $result; } function cars_getCarTypeById( $id ) { $query="SELECT * FROM `carsType` WHERE `id`='$id'"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } function cars_updateCar( $carid , $array ) { $userid=$_SESSION["user"]["id"]; $update = "UPDATE `cars` SET `nameCar`='".$array["nameCar"]."', `carType`='".$array["carstype"]."', `plate`='".$array["plate"]."', `registrating`='".$array["registrating"]."', `fueltax`='".$array["fueltax"]."', `userid`='".$userid."', `RCA_data`='".$array["expdatecar1"]."', `RCA_Nr_polita`='".$array["nrpolita1"]."', `RCA_partener`='".$array["furnizor"]."', `Casco_data`='".$array["expdatecar2"]."', `Casco_Nr_polita`='".$array["nrpolita2"]."', `Casco_partener`='".$array["furnizor2"]."', `Data_exp_verificare`='".$array["expdatecar3"]."', `stationare`='".$array["stationare"]."', `Data_exp_rovigneta`='".$array["expdatecar4"]."', `Data_exp_trusa`='".$array["expdatecar5"]."', `Data_exp_stingator`='".$array["expdatecar6"]."', `Data_exp_licenta`='".$array["expdatecar7"]."', `Data_exp_tahograf`='".$array["expdatecar8"]."' WHERE `id`='$carid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function cars_updateSingleCar( $carid , $array ) { $userid=$_SESSION["user"]["id"]; $update = "UPDATE `cars` SET `nameCar`='".$array["nameCar"]."', `plate`='".$array["plate"]."', `carType`='".$array["carstype"]."', `registrating`='".$array["registrating"]."', `fueltax`='".$array["fueltax"]."', `userid`='".$userid."', `RCA_data`='".$array["expdatecar1"]."', `RCA_Nr_polita`='".$array["nrpolita1"]."', `RCA_partener`='".$array["furnizor"]."', `Casco_data`='".$array["expdatecar2"]."', `Casco_Nr_polita`='".$array["nrpolita2"]."', `Casco_partener`='".$array["furnizor2"]."', `Data_exp_verificare`='".$array["expdatecar3"]."', `stationare`='".$array["stationare"]."', `Data_exp_rovigneta`='".$array["expdatecar4"]."', `Data_exp_trusa`='".$array["expdatecar5"]."', `Data_exp_stingator`='".$array["expdatecar6"]."', `Data_exp_licenta`='".$array["expdatecar7"]."', `Data_exp_tahograf`='".$array["expdatecar8"]."' WHERE `id`='$carid' LIMIT 1;"; $Result = mysql_query( $update ) or die(mysql_error()); $totalResult = $Result; return $totalResult; } function cars_getCar( $carid ) { $query = "SELECT * FROM `cars` WHERE `id`='$carid' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function cars_getCars() { $select = "SELECT * FROM `cars` ORDER by `nameCar`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $cars[ $row["id"] ] = $row; } return $cars; } function cars_delCar( $carid ) { $query = "DELETE FROM cars WHERE id = $carid"; mysql_query( $query ) or die(mysql_error()); } //delivery //proces verbal de predare primire function del_delivery_items($id) { $query="DELETE FROM deliveryPredarePrimire_items WHERE `procesid`='$id'"; mysql_query( $query ) or die(mysql_error()); } function getDeliveryRegisteredItems ($deliverid) { $query = "SELECT * FROM `deliveryPredarePrimire_items` WHERE `procesid` = '$deliverid';"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getDeliveryRegisteredItemsCount ($deliverid) { $query = "SELECT * FROM `deliveryPredarePrimire_items` WHERE `procesid` = '$deliverid';"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function delivery_setSerial( $id , $serial, $number ) { $update = "UPDATE `deliveryPredarePrimire` SET `serial`='".$serial."',`number`='".$number."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function generateDataFromDelivery( $id ) { $select = "SELECT * FROM `deliveryPredarePrimire` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function delivery_getMaxDocumentNR() { $select = "SELECT MAX(nrDocument) FROM `deliveryPredarePrimire`"; $result = mysql_query( $select ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return $row["MAX(nrDocument)"]; } function delivery_setActiveNess( $deliverid , $state ) { $update = "UPDATE `deliveryPredarePrimire` SET `active`='$state' WHERE `id`='$deliverid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function delivery_setPrinted( $id , $value ) { $updateQ = "UPDATE `deliveryPredarePrimire` SET `printed` = '$value' WHERE `deliveryPredarePrimire`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ); } function delivery_setClosed( $id , $value ) { $updateQ = "UPDATE `deliveryPredarePrimire` SET `closed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function delivery_delDelivery( $deliverid ) { $query = "DELETE FROM `deliveryPredarePrimire` WHERE id = $deliverid"; mysql_query( $query ) or die(mysql_error()); } function delivery_registerItems( $deliverid ,$produsid, $modelid , $price , $natprice , $quantity , $type, $rowName ) { $query = "INSERT INTO deliveryPredarePrimire_items VALUES (NULL, '$deliverid','$produsid', '$modelid', '$price', '$natprice' , '$quantity', '$type' , '$rowName', NOW());"; mysql_query( $query ) or die(mysql_error()); } function delivery_addDelivery( $factid,$clientid , $userid , $stockid , $rawvalue , $value , $content , $paymode , $dataExecutiei, $onValuta , $cursValue, $commandId, $commandIdAdv,$nrDocument,$punctDeLucru) { $content = addslashes ($content); $insertQ = "INSERT INTO `deliveryPredarePrimire` ( `id` ,`factid`, `clientid` , `userid` , `stockid` , `rawvalue` , `value` , `content` , `printed` , `closed` ,`ondate`,`active`,`paymode`, `dataExecutiei`, `onValuta` , `cursValue` , `fromActId` , `fromActAdvId`, `nrDocument`,`punctDeLucru`) VALUES ( NULL ,'$factid', '$clientid', '$userid', '$stockid', '$rawvalue', '$value','$content', '0', '0',NOW(),'1','$paymode' , '$dataExecutiei' , '$onValuta' , '$cursValue' , '$commandId' , '$commandIdAdv','$nrDocument','$punctDeLucru'); "; mysql_query( $insertQ ) or die(mysql_error()); $deliverid = mysql_insert_id (); return $deliverid; } function delivery_modDelivery( $id ,$factid, $clientid , $userid , $stockid , $rawvalue , $value , $content , $paymode , $dataExecutiei , $onValuta , $cursValue,$nrDocument,$punctDeLucru) { if($dataExecutiei==NULL) $dataExecutiei="0000-00-00"; $content = addslashes ($content); $updateQ = "UPDATE `deliveryPredarePrimire` SET `factid` = '$factid', `clientid` = '$clientid', `userid` = '$userid', `stockid` = '$stockid', `rawvalue` = '$rawvalue', `value` = '$value', `paymode` = '$paymode', `dataExecutiei` = '$dataExecutiei', `onValuta` = '$onValuta', `cursValue` = '$cursValue', `content` = '$content', `punctDeLucru`='$punctDeLucru' `nrDocument`=$nrDocument'' WHERE `deliveryPredarePrimire`.id ='$id' LIMIT 1;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function delivery_getDelivery( $id ) { $select = "SELECT * FROM `deliveryPredarePrimire` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function delivery_getDeliveries() { $select = "SELECT * FROM `deliveryPredarePrimire` ORDER by `id`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $delivery[ $row["id"] ] = $row; } return $delivery; } function delivery_delete( $deliverid ) { $query = "DELETE FROM `deliveryPredarePrimire` WHERE id = $deliverid"; mysql_query( $query ) or die(mysql_error()); } function delivery_rollbackSerialNumber( $deliverid ) { $delivery = delivery_getDelivery( $deliverid ); $serial = $delivery["serial"]; $serialNumber = $delivery["number"]; $lockQ = "LOCK TABLES `serials` WRITE"; $result = mysql_query( $lockQ ) or die(mysql_error()); $selectQ = "SELECT * FROM `serials` WHERE `serial`='$serial' LIMIT 1;"; $result = mysql_query( $selectQ ); $row = mysql_fetch_array( $result ); $lastSerialNumber = $row["current"]; if( $lastSerialNumber == $serialNumber + 1 ) { $updateQ = "UPDATE `serials` SET `current` = '$serialNumber' WHERE `serial`='$serial' LIMIT 1"; mysql_query( $updateQ ); } $unlockQ = "UNLOCK TABLES;"; mysql_query( $unlockQ ); } function delivery_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; //$fromDate = mysql_prevDay( $fromDate ); $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial" && $searchval!=NULL) $query = "SELECT `f`.*, `p`.`name` FROM `deliveryPredarePrimire` f, `partners` p WHERE `f`.`number` = '$searchval' AND `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; else $query = "SELECT `f`.*, `p`.`name` FROM `deliveryPredarePrimire` f, `partners` p WHERE `p`.`name` LIKE '%$searchval%' AND `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; return $query; } function delivery_searchDelivery( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function delivery_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } //daily_program //fisa zilnica de lucru function getItemsFromFisa($locationid,$soforid) { $query = "SELECT * FROM `fisaZilnicadeLucru_items` WHERE `locationid`='$locationid' AND `soforid`='$soforid' AND `realizat`=0"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $entry[ $row["id"] ] = $row; } return $entry; } function getDaily_ProgramRegisteredItems ($deliverid) { $query = "SELECT * FROM `fisaZilnicadeLucru_items` WHERE `fisaid` = '$deliverid';"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function fisa_ExpiredFisa() { $query = "SELECT * FROM `fisaZilnicadeLucru` "; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { $date=$row["editDate"]; $todayDate= date("Y-m-d"); $day=subtract_dates($date, $todayDate); if($day>=1) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=7;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } return $list; } function getSofor ($soforid) { $query = "SELECT * FROM `hr` WHERE `id` = '$soforid'"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return $row; } function daily_getMaxDocumentNR() { $select = "SELECT MAX(nrDocument) FROM `fisaZilnicadeLucru`"; $result = mysql_query( $select ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return $row["MAX(nrDocument)"]; } function getDaily_ProgramRegisteredItemsCount ($deliverid) { $query = "SELECT * FROM `fisaZilnicadeLucru_items` WHERE `fisaid` = '$deliverid';"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function daily_program_setSerial( $id , $serial ) { $update = "UPDATE `fisaZilnicadeLucru` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function generateDataFromDaily_Program( $id ) { $select = "SELECT * FROM `fisaZilnicadeLucru` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function daily_program_setActiveNess( $deliverid , $state ) { $update = "UPDATE `fisaZilnicadeLucru` SET `active`='$state' WHERE `id`='$deliverid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function daily_program_setPrinted( $id , $value ) { $updateQ = "UPDATE `fisaZilnicadeLucru` SET `printed` = '$value' WHERE `fisaZilnicadeLucru`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function daily_program_setClosed( $id , $value ) { $updateQ = "UPDATE `fisaZilnicadeLucru` SET `closed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function daily_program_delDaily_Program( $deliverid ) { $items="DELETE FROM `fisaZilnicadeLucru` where `fisaid`='$deliverid'"; mysql_query($items); $query = "DELETE FROM `fisaZilnicadeLucru` WHERE id = $deliverid"; mysql_query( $query ) or die(mysql_error()); } function daily_program_registerItems( $deliverid ,$serviciiid, $clientid,$contact, $locationid , $durata , $quantity , $soforid,$executie,$realizat,$weeknum ) { $query = "INSERT INTO fisaZilnicadeLucru_items VALUES (NULL, '$deliverid','$serviciiid','$clientid','$contact', '$locationid', '$durata', '$quantity', '$soforid', $executie,'$realizat','$weeknum' );"; mysql_query( $query ) or die(mysql_error()); } function del_daily_program_items($id) { $query="DELETE FROM fisaZilnicadeLucru_items WHERE `fisaid`='$id'"; mysql_query( $query ) or die(mysql_error()); } function daily_program_addDaily_Program( $userid ,$soferid, $stockid , $totaldurata , $content , $dataExecutiei,$nrDocument,$edit) { $content = addslashes ($content); $insertQ = "INSERT INTO `fisaZilnicadeLucru` ( `id` , `userid` , `soforid`, `stockid` ,`totaldurata` , `content` , `printed` , `closed` ,`ondate`,`active`, `dataExecutiei`, `nrDocument`,`editDate`) VALUES ( NULL , '$userid','$soferid', '$stockid', '$totaldurata','$content', '0', '0',NOW(),'1', '$dataExecutiei' ,'$nrDocument','$edit'); "; mysql_query( $insertQ ) or die(mysql_error()); $deliverid = mysql_insert_id (); //delivery_addChitanta( $clientid , $userid , $facturid , 0 , 0 , $serial , $number , $content , 0 ); // $clientid , $userid , $factid , $value , $svalue , $serial , $number , $content return $deliverid; } function daily_program_modDaily_Program( $id , $userid ,$soferid, $stockid ,$totaldurata, $content , $dataExecutiei,$nrDocument,$edit) { if($dataExecutiei==NULL) $dataExecutiei="0000-00-00"; $content = addslashes ($content); $updateQ = "UPDATE `fisaZilnicadeLucru` SET `userid` = '$userid', `stockid` = '$stockid', `totaldurata` ='$totaldurata', `nrDocument`='$nrDocument', `dataExecutiei` = '$dataExecutiei', `content` = '$content', `editDate` = '$edit', `soforid` = '$soferid' WHERE `fisaZilnicadeLucru`.id ='$id' LIMIT 1;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function daily_program_getDaily_Program( $id ) { $select = "SELECT * FROM `fisaZilnicadeLucru` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function daily_program_getDaily_Programs() { $select = "SELECT * FROM `fisaZilnicadeLucru` ORDER by `id`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $delivery[ $row["id"] ] = $row; } return $delivery; } function daily_program_delete( $deliverid ) { $query = "DELETE FROM `fisaZilnicadeLucru` WHERE id = $deliverid"; mysql_query( $query ) or die(mysql_error()); } function daily_program_rollbackSerialNumber( $deliverid ) { $delivery = delivery_getDelivery( $deliverid ); $serial = $delivery["serial"]; $serialNumber = $delivery["number"]; $lockQ = "LOCK TABLES `serials` WRITE"; $result = mysql_query( $lockQ ); $selectQ = "SELECT * FROM `serials` WHERE `serial`='$serial' LIMIT 1;"; $result = mysql_query( $selectQ ) or die(mysql_error()); $row = mysql_fetch_array( $result ); $lastSerialNumber = $row["current"]; if( $lastSerialNumber == $serialNumber + 1 ) { $updateQ = "UPDATE `serials` SET `current` = '$serialNumber' WHERE `serial`='$serial' LIMIT 1"; mysql_query( $updateQ ) or die(mysql_error()); } $unlockQ = "UNLOCK TABLES;"; mysql_query( $unlockQ ) or die(mysql_error()); } function daily_program_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $id) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial" && $searchval!=NULL) { $query = "SELECT `f`.* FROM `fisaZilnicadeLucru` f WHERE `f`.`number` = '$searchval' AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; } else if ( $searchcriteria == "id" ) { $query = "SELECT `f`.* FROM `fisaZilnicadeLucru` f WHERE `f`.`id` = '$id' ORDER BY $orderby $ordermode"; } else $query = "SELECT `f`.* FROM `fisaZilnicadeLucru` f WHERE `ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; return $query; } function daily_program_searchDaily_Program( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function daily_program_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_num_rows($result);//$row ["nrFactura"]; } //hrDocument function hrDocumentInsert($documentName , $userid , $documentLink,$menu) { $insertQ = "INSERT INTO `hrDocumente` ( `id` , `hrid` , `documentName` , `documentLink` , `ondate`,`menu`) VALUES ( NULL ,'".$userid."', '".$documentName."', '".$documentLink."', NOW(), '".$menu."');"; mysql_query( $insertQ ) or die(mysql_error()); return mysql_insert_id(); } function hrDocument_get($userid,$menu) { $select = "SELECT * FROM `hrDocumente` WHERE `hrid` = '$userid' and `menu`='$menu' ORDER by `ondate`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $documente[ $row["id"] ] = $row; } return $documente; } function hrDocumentDelete($id) { $insertQ = "DELETE FROM `hrDocumente` WHERE `id` = '$id'"; mysql_query( $insertQ ) or die(mysql_error()); } //contractAngajat function contractAngajat_delete( $facturaId ) { $query = "DELETE FROM `contractAngajat` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function command_addcontractAngajat( $userid , $stockid , $number, $content , $comments , $hrid,$tipContract,$obiectContract,$dataInceput,$perioadaInceput,$perioadaSfarsit,$orePeZi,$orePeSaptamana,$concediu,$dataManuala,$reprezentatName,$reprezentatCalitate,$reprezentatBuletin,$repartizare,$dataSalariu,$protectie,$lucru,$sanitare,$alimentatie,$altesanatate,$proba,$concedierii,$demisiei,$confidentialitate) { $content = addslashes ($content); $perioada = $perioadaInceput." - ".$perioadaSfarsit; $insertQ = "INSERT INTO `contractAngajat` ( `id` , `userid` , `stockid` , `secondSerial` , `hrid` , `tipContract` , `obiectContract` , `durata` , `content` , `ondate` , `active` , `printed` , `closed` , `dataInceput`, `perioada`, `determinatLuni`, `conditii`, `durataMunciiZii`, `durataMunciiSaptamana`, `concediu`, `reprezentatName`, `reprezentatCalitate`, `reprezentatBuletin`, `repartizare`, `dataSalariu`, `protectie`, `lucru`, `sanitare`, `alimentatie`, `altesanatate`, `proba`, `concedierii`, `demisiei`, `confidentialitate` ) VALUES (NULL , '$userid', '$stockid' , '$number', '$hrid', '$tipContract', '$obiectContract', '$durata', '$content', '$dataManuala', '1', '0', '0', '$dataInceput','$perioada' ,'$determinatLuni', '$conditii' , '$durataMunciiZii','$durataMunciiSaptamana','$concediu' , 'reprezentatName','reprezentatCalitate','reprezentatBuletin','repartizare', 'dataSalariu','protectie','lucru','sanitare','alimentatie','altesanatate','proba','concedierii','demisiei','confidentialitate');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function contractAngajat_setActiveNess( $factid , $state ) { $update = "UPDATE `contractAngajat` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ); } function contractAngajat_modFactura( $id, $userid , $stockid , $number, $content , $comments , $hrid,$tipContract,$obiectContract,$dataInceput,$perioadaInceput,$perioadaSfarsit,$orePeZi,$orePeSaptamana,$concediu,$dataManuala,$reprezentatName,$reprezentatCalitate,$reprezentatBuletin,$repartizare,$dataSalariu,$protectie,$lucru,$sanitare,$alimentatie,$altesanatate,$proba,$concedierii,$demisiei,$confidentialitate ) { $content = addslashes ($content); $perioada = $perioadaInceput." - ".$perioadaSfarsit; $updateQ = "UPDATE `contractAngajat` SET `userid` = '$userid', `stockid` = '$stockid', `secondSerial` = '$number', `hrid` = '$hrid', `tipContract` = '$tipContract', `obiectContract` = '$obiectContract', `durata` = '$durata', `content` = '$content', `dataInceput` = '$dataInceput', `ondate` = '$dataManuala', `perioada` = '$perioada', `durataMunciiZii` = '$orePeZi', `durataMunciiSaptamana` = '$orePeSaptamana', `reprezentatName` = '$reprezentatName', `reprezentatCalitate` = '$reprezentatCalitate', `reprezentatBuletin` = '$reprezentatBuletin', `repartizare` = '$repartizare', `dataSalariu` = '$dataSalariu', `protectie` = '$protectie', `lucru` = '$lucru', `sanitare` = '$sanitare', `alimentatie` = '$alimentatie', `altesanatate` = '$altesanatate', `proba` = '$proba', `concedierii` = '$concedierii', `demisiei` = '$demisiei', `confidentialitate` = '$confidentialitate', `concediu` = '$concediu' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function contractAngajat_setPrinted( $id , $value ) { $updateQ = "UPDATE `contractAngajat` SET `printed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function contractAngajat_setClosed( $id , $value ) { $updateQ = "UPDATE `contractAngajat` SET `closed` = '$value' WHERE `id` ='$id' LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function contractAngajat_setSerial( $id , $serial ) { $update = "UPDATE `contractAngajat` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function contractAngajat_getFacturi() { $select = "SELECT * FROM `contractAngajat`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function generateDataFromcontractAngajat( $id ) { $select = "SELECT * FROM `contractAngajat` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function contractAngajat_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $firstserial, $secondserial, $serial, $id) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "platite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`secondserial` = '$searchval'"; else $plus_search="AND `p`.`forname` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `contractAngajat` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; $result = mysql_query( $query ) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { if(convertNumber($pais[ $row["id"] ]["paid"])==convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `contractAngajat` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1' ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu == "neplatite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`secondserial` = '$searchval'"; else $plus_search="AND `p`.`forname` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `contractAngajat` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; $result = mysql_query( $query ) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { //fizetve if(convertNumber($pais[ $row["id"] ]["paid"])!=convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `contractAngajat` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1' ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu != "platite" && $filter_menu != "neplatite" && $filter_menu != "expirate") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial") { if($serial!=NULL) $serialFilter.= " AND `f`.`seconderial` = '$serial'"; $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `contractAngajat` f, `hr` p WHERE `p`.`id` = `f`.`hrid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$serialFilter.$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; } else if( $searchcriteria == "id" ) { $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `contractAngajat` f, `hr` p WHERE `p`.`id` = `f`.`hrid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND `f`.`id`= '$id' ORDER BY $orderby $ordermode"; } else { $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `contractAngajat` f, `hr` p WHERE `p`.`forname` LIKE '%$searchval%' AND `p`.`id` = `f`.`hrid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; } } return $query; } //actAditional function actAditional_delete( $facturaId ) { $query = "DELETE FROM `actAditional` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function command_addactAditional( $userid , $stockid , $number, $content , $comments , $hrid , $obiectContract , $deladata , $panaladata , $contractNr , $contractData ) { $content = addslashes ($content); $insertQ = "INSERT INTO `actAditional` ( `id` , `userid` , `stockid` , `secondSerial` , `hrid` , `obiectContract` , `content` , `ondate` , `active` , `printed` , `closed` , `delaData`, `panalaData`, `contractNr`, `contractData` ) VALUES (NULL , '$userid', '$stockid' , '$number', '$hrid', '$obiectContract', '$content', NOW(), '1', '0', '0', '$deladata','$panaladata' ,'$contractNr', '$contractData');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function command_getactAditional( $pageno = -1, $orderby , $hrid ) { $query = "SELECT * FROM `actAditional` WHERE `active` ='1' AND `hrid` = '$hrid' ORDER BY secondserial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function actAditional_setActiveNess( $factid , $state ) { $update = "UPDATE `actAditional` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function actAditional_modFactura( $id, $userid , $stockid , $number, $content , $comments , $hrid , $obiectContract , $deladata , $panaladata , $contractNr , $contractData ) { $content = addslashes ($content); $perioada = $perioadaInceput." - ".$perioadaSfarsit; $updateQ = "UPDATE `actAditional` SET `userid` = '$userid', `stockid` = '$stockid', `secondserial` = '$number', `hrid` = '$hrid', `obiectContract` = '$obiectContract', `content` = '$content', `delaData` = '$deladata', `panalaData` = '$panaladata', `contractNr` = '$contractNr', `contractData` = '$contractData' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function actAditional_setPrinted( $id , $value ) { $updateQ = "UPDATE `actAditional` SET `printed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function actAditional_setClosed( $id , $value ) { $updateQ = "UPDATE `actAditional` SET `closed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function actAditional_setSerial( $id , $serial ) { $update = "UPDATE `actAditional` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function actAditional_getFacturi() { $select = "SELECT * FROM `actAditional`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function generateDataFromactAditional( $id ) { $select = "SELECT * FROM `actAditional` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function actAditional_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $firstserial, $secondserial, $serial) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "platite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`secondserial` = '$searchval'"; else $plus_search="AND `p`.`forname` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `actAditional` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; $result = mysql_query( $query ) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { if(convertNumber($pais[ $row["id"] ]["paid"])==convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `actAditional` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1' ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu == "neplatite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`secondserial` = '$searchval'"; else $plus_search="AND `p`.`forname` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `actAditional` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; $result = mysql_query( $query ) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { //fizetve if(convertNumber($pais[ $row["id"] ]["paid"])!=convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `actAditional` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1' ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu != "platite" && $filter_menu != "neplatite" && $filter_menu != "expirate") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial") { if($serial!=NULL) $serialFilter.= " AND `f`.`seconderial` = '$serial'"; $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `actAditional` f, `hr` p WHERE `p`.`id` = `f`.`hrid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$serialFilter.$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; } else { $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `actAditional` f, `hr` p WHERE `p`.`forname` LIKE '%$searchval%' AND `p`.`id` = `f`.`hrid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; } } return $query; } function actAditional_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function actAditional_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function contractForClientGeneratedStat( $fromActId ) { $select = "SELECT * FROM `contractForClient` WHERE `fromActId`='$fromActId' AND `active` = '1' LIMIT 1;"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function factura_getCommandForClientFacturi( $commandId, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `facturi` WHERE `fromActId`='$commandId' AND `active` ='1' AND `type`='1' ORDER BY ondate $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function expens_queryGeneratorFromActId( $fromActId , $page = 1 , $orderby , $ordermode , $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; $query = "SELECT * FROM `expenses` WHERE `proiectid` = '$fromActId' AND `expdate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; return $query; } function expens_queryGeneratorFromActAdvId( $fromActId , $page = 1 , $orderby , $ordermode , $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; $query = "SELECT * FROM `expenses` WHERE (`commandId` = '$fromActId' || `commandId` = '$fromActId,' || `commandId` LIKE '% $fromActId,%') AND `expdate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; return $query; } function bonconsum_queryGeneratorFromActAdvId( $fromActId , $page = 1 , $orderby , $ordermode , $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; $query = "SELECT * FROM `bonConsum` WHERE `fromActAdvId` = '$fromActId' AND `ondate` BETWEEN '$fromDate' AND '$toDate' AND `active`='1' ORDER BY $orderby $ordermode"; return $query; } function bonconsum_getBonConsumRegisteredItems( $expensid ) { $query = "SELECT * FROM `bonConsum_items` WHERE `factid`='$expensid' AND `price` >= 0"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) $expenses[ $row["id"] ] = $row; return $expenses; } } function contractAngajat_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function contractAngajat_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } //cities distances es judete function cities_getCities() { return getCitiesWithOld("0"); } function counties_getCounties() { $query = "SELECT * FROM `cities_Counties` ORDER BY name ASC"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $counties[ $row["id"] ] = $row; } return $counties; } function cities_insertCity($judetid, $name, $country) { //megnezem van e mar city $query = "SELECT `id` FROM `cities_new` WHERE `name` = '$name' and country = '$country' and judetid = '$judetid'"; $result = mysql_query($query) or die(mysq_error()); if(mysql_num_rows($result)!=0) { $row=mysql_fetch_array($result); $citymax=$row["id"]; } else { $queryc="SELECT MAX(`id`) as maxid FROM cities_new"; $result=mysql_query($queryc); $res=mysql_fetch_array($result); $citymax=$res["maxid"]+1; $query="INSERT INTO `cities_new`(`id`,`judetid`,`name`,`country`) VALUES('$citymax','$judetid','$name','$country')"; mysql_query($query) or die(mysql_error()); } return $citymax; } function counties_insertCounty($name,$country) { //megnezem van e mar city $query = "SELECT `id` FROM `cities_Counties` WHERE `name` LIKE '$name%'"; $result = mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)!=0) { $row=mysql_fetch_array($result); $citymax=$row["id"]; } else { $queryc="SELECT MAX(`id`) as maxid FROM cities_Counties"; $result=mysql_query($queryc); $res=mysql_fetch_array($result); $citymax=$res["maxid"]+1; $query="INSERT INTO `cities_Counties`(`id`,`name`,`country`) values('$citymax','$name','$country')"; mysql_query($query) or die(mysql_error()); } return $citymax; } function cities_insertCityDistance( $cityId, $cityIdFrom, $cityIdTo, $distanceFrom, $distanceTo) { if($distanceFrom!=0) { $query1="INSERT INTO `citiesDistances` values(NULL,$cityIdFrom,$cityId,$distanceFrom)"; mysql_query($query1) or die(mysql_error()); $query2="INSERT INTO `citiesDistances` values(NULL,$cityId,$cityIdFrom,$distanceFrom)"; mysql_query( $query2 ) or die(mysql_error()); } if($distanceTo!=0) { $query3="INSERT INTO `citiesDistances` values(NULL,$cityId,$cityIdTo,$distanceTo)"; mysql_query( $query3 ) or die(mysql_error()); $query4="INSERT INTO `citiesDistances` values(NULL,$cityIdTo,$cityId,$distanceTo)"; mysql_query($query4) or die(mysql_error()); } } function cities_insertCityDistance2( $cityId) { $query1="INSERT INTO `citiesDistances` values(NULL,$cityId,$cityId,0)"; mysql_query($query1) or die(mysql_error()); } function cities_getCity($id) { if($id<10000) $query = "SELECT * FROM `cities` WHERE `id` = '$id'"; else $query = "SELECT * FROM `cities_new` WHERE `id` = '$id'"; $results = mysql_query( $query ) or die(mysql_error()); if($results&&mysql_num_rows($results)>0) $row = mysql_fetch_array( $results ); return $row; } function cityNotExists($name) { $query = "SELECT * FROM `cities_new` WHERE `name` LIKE '%$name'%"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_num_rows($result) <= 0 ) { $query = "SELECT * FROM `cities` WHERE `name` LIKE '%$name'%"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_num_rows($result) <= 0 ) return NULL; } $row = mysql_fetch_array( $results ); return $row["id"]; } function countyNotExists($name) { $query = "SELECT * FROM `cities_Counties` WHERE `name` LIKE '%$name'%"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 ) return NULL; $row = mysql_fetch_array( $results ); return $row["id"]; } function counties_getCounty($id) { $query = "SELECT * FROM `cities_Counties` WHERE `id` = '$id'"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $results ); return $row; } function cities_getCityNev($id) { if($id<10000) $query = "SELECT `name` FROM `cities` WHERE `id` = '$id'"; else $query = "SELECT `name` FROM `cities_new` WHERE `id` = '$id'"; $results = mysql_query( $query ) or die(mysql_error()); return $results; } function counties_getCountyNev($id) { $query = "SELECT `name` FROM `cities_Counties` WHERE `id` = '$id'"; $results = mysql_query( $query ) or die(mysql_error()); return $results; } function cities_getDistance( $from , $to ) { $query ="SELECT * FROM `citiesDistances` WHERE `from` = '$from' AND `to` = '$to' ORDER BY `id` ASC"; $result = mysql_query( $query ) or die(mysql_error()); if($result) $row = mysql_fetch_array( $result ); return $row["many"]; } function cities_deleteDistance( $cityIdFrom, $cityIdTo ) { $query1="DELETE FROM `citiesDistances` WHERE `from`='$cityIdFrom' and `to`='$cityIdTo'"; mysql_query($query1) or die(mysql_error()); $query2="DELETE FROM `citiesDistances` WHERE `from`='$cityIdTo' and `to`='$cityIdFrom'"; mysql_query( $query2 ) or die(mysql_error()); } function cities_addCity( $name ) { $query = "INSERT INTO `cities` (`id` ,`name` ) VALUES (NULL , '$name');"; $results = mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function counties_addCounty( $name ) { $query = "INSERT INTO `cities_Counties` (`id` ,`name` ) VALUES (NULL , '$name');"; $results = mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function insert_Distances( $array , $total ) { foreach( $array as $key => $xvalue ) $$key = $xvalue; if($orasNou!=NULL) cities_addCity( $orasNou ); $cities = cities_getCities(); $citiesSecond = cities_getCities(); $counter1=0; foreach($cities as $key => $value) { $counter2=0; foreach($citiesSecond as $keySecond => $valueSecond) { $citiesValue = "distance_".$counter1."_".$counter2; if($value["id"]!=$valueSecond["id"]) { if($citiesData[$counter1][$counter2]==NULL) { $from = $value["id"]; $to = $valueSecond["id"]; $many = $$citiesValue; $query = "INSERT INTO `citiesDistances` (`id` ,`from` ,`to` ,`many` ) VALUES (NULL , '$from', '$to', '$many');"; $results = mysql_query( $query ) or die(mysql_error()); } } else { $citiesData[$counter1][$counter2] = 0; $from = $value["id"]; $to = $valueSecond["id"]; $many = $$citiesValue; $query = "INSERT INTO `citiesDistances` (`id` ,`from` ,`to` ,`many` ) VALUES (NULL , '$from', '$to', '$many');"; $results = mysql_query( $query ) or die(mysql_error()); } $counter2++; } $counter1++; } } function insert_distance( $array ) { //megnezni h az a ket varos kozott amelyik koze be akarom szurni van-e tavolsag } function empty_Distances() { $query = "TRUNCATE TABLE `citiesDistances`"; $results = mysql_query( $query ) or die(mysql_error()); } // functii codes function hr_getCodes() { $query = "SELECT * FROM `functiiRomania` ORDER BY name ASC"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $codes[ $row["id"] ] = $row; } return $codes; } function hr_getDomainName($id) { $query="select cod, name from `functiiRomania` where `id`='$id';"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } function hr_getMaxId() { $query="select MAX(id) from `hr`"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return ($row["MAX(id)"]); } function hr_getCode( $id ) { $select = "SELECT * FROM `functiiRomania` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } //dispozitie function factura_addDp($nrTemplate, $hrid , $userid , $factid , $value , $svalue , $serial , $number , $content , $invoiceid , $dispozitieType, $dataDocument,$clientid) { $content = addslashes ($content); $query = "INSERT INTO `dispozitie` ( `id` , `clientid` , `userid` , `factid` , `value` , `svalue` , `serial`,`number`,`ondate` , `content` ,`printed`,`closed`,`active`,`invoiceid`,`type`,`hrid`,`nrTemplate`) VALUES ( NULL , '$clientid', '$userid', '$factid', '$value', '$svalue','$serial','$number', '$dataDocument' , '$content','0','0','1' ,'$invoiceid','$dispozitieType','$hrid','$nrTemplate'); "; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function factura_modDp($nrTemplate, $chitid , $hrid , $userid , $factid , $value , $svalue , $serial , $number , $content , $invoiceid , $dispozitieType,$dataDocument,$clientid) { $query = "UPDATE `dispozitie` SET `clientid` = '$clientid', `userid` = '$userid', `factid` = '$factid', `value` = '$value', `svalue` = '$svalue', `serial` = '$serial', `number` = '$number', `invoiceid` = '$invoiceid', `type` = '$dispozitieType', `hrid` = '$hrid', `ondate` = '$dataDocument', `nrTemplate`='$nrTemplate', `content` = '$content' WHERE `dispozitie`.`id` ='$chitid' LIMIT 1 ; "; mysql_query( $query ) or die(mysql_error()); } function factura_setDpActiveNess( $billid , $state ) { $updateQ = "UPDATE `dispozitie` SET `active`='$state' WHERE `id`='$billid' LIMIT 1;"; mysql_query( $updateQ ) or die(mysql_error()); } function factura_searchDp( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if (mysql_affected_rows () < 1) return NULL; while ($row = mysql_fetch_array ($result)) { $facturi [$row ["id"]] = $row; } return $facturi; } function factura_lockDp( $billid ) { $query = "UPDATE `dispozitie` SET `printed`=1 , `closed`=1 WHERE `id`='$billid' LIMIT 1"; mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows(); } function factura_searchDpQueryGenerator ($searchval, $searchcriteria, $page, $orderby,$ordermode) { $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $count = $_SESSION["settings"]["searchcount"]; if($orderby=="name"||$orderby=="") { $orderby="`f`.value"; } if ($searchcriteria == "serial") $query = "SELECT `f`.* FROM `dispozitie` f WHERE (`f`.`number` = '$searchval' OR `f`.serial = '$searchval' ) AND `f`.value > 0 ORDER BY $orderby $ordermode LIMIT $from, $count"; else $query = "SELECT `f`.* FROM `dispozitie` f WHERE `f`.`clientid` IN (SELECT `id` FROM `partners` p WHERE (`p`.`name` LIKE '%$searchval%' ) ) ORDER BY $orderby $ordermode LIMIT $from, $count"; return $query; } function dp_setPrinted( $id , $value ) { $updateQ = "UPDATE `dispozitie` SET `printed` = '$value' WHERE `dispozitie`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function dp_setClosed( $id , $value ) { $updateQ = "UPDATE `dispozitie` SET `closed` = '$value' WHERE `dispozitie`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function factura_remDp( $billid ) { $query = "DELETE FROM `dispozitie` WHERE `id`=$billid LIMIT 1"; mysql_query( $billid ) or die(mysql_error()); } function factura_getDp( $billid ) { $query = "SELECT * FROM `dispozitie` WHERE `id`=$billid LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() == 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function factura_getDps() { $query = "SELECT * FROM `dispozitie` ORDER BY `id` DESC"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() == 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function factura_getDpForHr( $factid ) { $query = "SELECT * FROM `dispozitie` WHERE `hrid`='$factid' AND `value` > 0"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) $bills[ $row["id"] ] = $row; return $bills; } } // jog rendszer - menurendszer function getMenus( $userid , $accessMenu ) { $query = "SELECT u.`subMenuId` , sm.`id` as subMenuId, sm.`subMenuName`, sm.`subMenuMod`, sm.`subMenuCode`, sm.`subMenuShowForm`, sm.`xaction`, sm.`jumpform`, sm.`subform` , m.* FROM `accessForUsers` u, `accessSubMenus` sm, `accessMenus` m WHERE u.`userId`='$userid' AND u.`subMenuId` = sm.`id` AND sm.`menuId` = m.`id` AND m.`accessId`='$accessMenu' GROUP BY sm.`id` ORDER BY m.`menuName`, sm.`id`"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) $menus[ $row["subMenuId"] ] = $row; return $menus; } } function getAccessMenus( $userid ) { $query = "SELECT gr.`id` as AccessId, gr.`accessName`, u.`subMenuId` , sm.`id` as subMenuId, sm.`subMenuName`, sm.`subMenuMod`, sm.`subMenuCode`, sm.`subMenuShowForm`, sm.`xaction`, sm.`jumpform`, sm.`subform` , m.* FROM `accessGroups` gr, `accessForUsers` u, `accessSubMenus` sm, `accessMenus` m WHERE u.`userId`='$userid' AND u.`subMenuId` = sm.`id` AND sm.`menuId` = m.`id` AND m.`accessId` = gr.`id` GROUP BY m.`accessId`"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) $menus[ $row["AccessId"] ] = $row; return $menus; } } function getSingleAccessMenus( $userid , $singleMenuId ) { $query = "SELECT u.`subMenuId` FROM `accessForUsers` u WHERE u.`userId`='$userid' AND u.`subMenuId` = '$singleMenuId'"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_num_rows($results) <= 0 )return NULL; else return 1; } function getCatAccessMenus( $userid , $menuId ) { $query = "SELECT u.`subMenuId` FROM `accessForUsers` u , `accessMenus` m , `accessSubMenus` sm WHERE u.`userId`='$userid' AND u.`subMenuId` = sm.`id` AND sm.`menuId` = m.`id` AND m.`id` = '$menuId'"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_num_rows($results) <= 0 )return NULL; else return 1; } function getCatAccessMenusByMod( $userid , $mod , $vmod ,$showform , $xaction , $subform) { $query = "SELECT u.`subMenuId` FROM `accessForUsers` u , `accessMenus` m , `accessSubMenus` sm WHERE u.`userId`='$userid' AND ((sm.`subMenuMod`='$mod' AND sm.`subMenuShowForm`='$showform') OR sm.`subMenuCode` = '$vmod') AND u.`subMenuId` = sm.`id`"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_num_rows($results) <= 0 )return NULL; else return 1; } function AccessMenusChange( $mod , $vmod) { $query = "SELECT g.`accessName`, g.`id` FROM `accessGroups` g, `accessMenus` m , `accessSubMenus` sm WHERE sm.`subMenuMod`='$mod' AND sm.`subMenuCode` = '$vmod' AND sm.`menuId` = m.`id` AND m.`accessId`=g.`id`"; $results = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array($results); if( mysql_num_rows($results) <= 0 )return NULL; else return $row["id"]; } function getAllMenus() { $query = "SELECT sm.`id` as subMenuId, sm.`subMenuName`, sm.`subMenuMod`, sm.`subMenuCode`, sm.`subMenuShowForm`, sm.`xaction`, sm.`jumpform`, sm.`subform` , m.* FROM `accessSubMenus` sm, `accessMenus` m WHERE sm.`menuId` = m.`id` GROUP BY sm.`id` ORDER BY m.`menuName`,sm.`subMenuName`"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) $menus[ $row["subMenuId"] ] = $row; return $menus; } } function user_Online_Add($array) { $userid=$array["id"]; $query3="SELECT MAX(datetime) as maxdatum FROM usersHistory WHERE `userid`='$userid'"; $result=mysql_query($query3) OR DIE(mysql_error()); $aktdatum=time()-(30 * 59); $fromDate = date("Y-m-d H:i:s",$aktdatum); $query2="SELECT * FROM usersHistory WHERE `userid`='$userid' AND `datetime`>'$fromDate' "; $result2=mysql_query( $query2 ) or die(mysql_error()); $szam=mysql_num_rows($result2); $date=date("Y-m-d"); $query5="SELECT * FROM `user_online` WHERE `userid`='".$array["id"]."'"; $res=mysql_query($query5); if($res) $szamuser=mysql_num_rows($res); if($szam!=0 && $szam!=NULL && ( $szamuser==0 ) ) { $query="INSERT INTO `user_online` (`id` ,`userid` ,`cnp`,`username`,`forname`,`lastname`,`date` ) VALUES ( NULL , '".$array["id"]."' , '".$array["cnp"]."', '".$array["username"]."', '".$array["forname"]."', '".$array["lastname"]."','".$date."' );"; mysql_query( $query ) or die(mysql_error()); } } function getUsers_Online() { $aktdatum=time()-(30 * 59); $fromDate = date("Y-m-d H:i:s",$aktdatum); $query2="SELECT DISTINCT `userid` FROM usersHistory WHERE `datetime`>'$fromDate' "; $result=mysql_query( $query2 ) or die(mysql_error()); return $result; } function users_updateAccess( $userid , $array ) { //kiuritem az adatbazist $queryEmpty = "DELETE FROM `accessForUsers` WHERE `userid` = '".$userid."';"; $resultsEmpty = mysql_query( $queryEmpty ); //beszurom az uj menuket $menusList = getAllMenus(); $counter=0; $subCounter=0; $menuId=""; if($menusList) { foreach( $menusList as $menuKey => $menuValue) { $menuId = $menuValue["id"]; if($oldMenuId!=$menuId) { $subCounter=0; } $subCounter++; $valueSum = 'access_'.$menuValue["id"].'_'.$subCounter; if( $array["$valueSum"] == $menuValue["subMenuId"] ) { //inserting $query=""; $query="INSERT INTO `accessForUsers` (`id` ,`subMenuId` ,`userId` ) VALUES ( NULL , '".$menuValue["subMenuId"]."' , '".$userid."' );"; $results = mysql_query( $query ) or die(mysql_error()); } $oldMenuId = $menuId; } } } //ordinDeplasare function decont_getPartnerDecont( $clientid, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `decont` WHERE `clientid`=$clientid AND `active` ='1' ORDER BY numberSerial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function decont_getDecont( $pageno = -1, $orderby ) { $query = "SELECT * FROM `decont` WHERE `active` ='1' ORDER BY firstserial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function stats_decontGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `decont` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function decont_delete( $facturaId ) { $query = "DELETE FROM `decont` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } //nincs kijavitva!!!!!!!!!!!!!!!!!1 function decont_addDecont( $hrid , $userid , $defstock , $nrDocument , $delegatPentru , $content , $fromorasid , $toorasid , $datadela , $datala , $alteLocatii , $diurna , $diurnaPret , $comments , $distance , $fuelTax , $fuelPrice , $carid , $fromActId , $fazaId , $fuelTax , $fuelPrice, $carid ) { $content = addslashes ($content); $insertQ = "INSERT INTO `decont` ( `id` , `hrId` , `userid` , `stockid` , `firstserial` , `content` , `active` , `printed` , `closed` , `ondate` , `cursValutar` , `comments` , `fromActId` , `fazaId` ) VALUES ( NULL , '$hrid', '$userid', '$defstock', '$nrDocument', '$content', '1', '0', '0', NOW() , '1', '$comments', '$fromActId', '$fazaId' );"; $result = mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function decont_registerItems( $factid , $idBon ) { $query = "INSERT INTO decontItems VALUES (NULL, '$factid', NOW() , '$idBon');"; mysql_query( $query ) or die(mysql_error()); } function decont_unRegisterItems( $factid ) { $query = "DELETE FROM `decontItems` WHERE `decontItems`.`documentid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); } function decont_setActiveNess( $factid , $state ) { $update = "UPDATE `decont` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ); } function decont_modFactura( $id , $hrid , $userid , $defstock , $nrDocument , $content , $comments ) { $content = addslashes ($content); $updateQ = "UPDATE `decont` SET `hrId` = '$hrid', `content` = '$content', `comments` = '$comments' WHERE `id` = '$id' LIMIT 1;" ; $result=mysql_query( $updateQ ) or die(mysql_error()); } function decont_setPrinted( $id , $value ) { $updateQ = "UPDATE `decont` SET `printed` = '$value' WHERE `id` = '$id' LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function decont_setClosed( $id , $value ) { $updateQ = "UPDATE `decont` SET `closed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function decont_setSerial( $id , $serial ) { $update = "UPDATE `decont` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function decont_getFacturi() { $select = "SELECT * FROM `decont`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function decont_getFactura( $id ) { $select = "SELECT * FROM `decont` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function dispozitie_getFactura( $id ) { $select = "SELECT * FROM `dispozitie` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function decont_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "platite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`firstserial` = '$searchval'"; else $plus_search="AND (`p`.`forname` LIKE '%$searchval%' OR `p`.`lastname` LIKE '%$searchval%')"; $query = "SELECT `f`.*, `p`.`name` FROM `decont` f, `hr` p WHERE `p`.`id` = `f`.`hrId` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; $result = mysql_query( $query ) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { if(convertNumber($pais[ $row["id"] ]["paid"])==convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`name` FROM `decont` f, `hr` p WHERE `p`.`id` = `f`.`hrId` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1' ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu != "platite" && $filter_menu != "neplatite" && $filter_menu != "expirate") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial" && $searchval!=NULL) $query = "SELECT `f`.*, `p`.`forname` FROM `decont` f, `hr` p WHERE `f`.`firstserial` = '$searchval' AND `p`.`id` = `f`.`hrId` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; else $query = "SELECT `f`.*, `p`.`forname` FROM `decont` f, `hr` p WHERE (`p`.`forname` LIKE '%$searchval%' OR `p`.`lastname` LIKE '%$searchval%') AND `p`.`id` = `f`.`hrId` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; } return $query; } function decont_searchGenerateQueryFromActId( $fromActId ) { $query = "SELECT `f`.*, `p`.`forname` FROM `decont` f, `hr` p WHERE fromActId = '$fromActId' AND `p`.`id` = `f`.`hrId` ORDER BY ondate DESC"; return $query; } function decont_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function decont_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function getDecontRegisteredItems ($commandId) { $query = "SELECT * FROM `decontItems` WHERE `documentid` = '$commandId';"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getDecontRegisteredItemsForExpens($expensId) { $query = "SELECT * FROM `decontItems` WHERE `idBon` = '$expensId' ORDER BY `id` DESC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; $row = mysql_fetch_array( $result ); return $row; } function getDecontRegisteredItemsCount ($commandId) { $query = "SELECT * FROM `decontItems` WHERE `documentid` = '$commandId';"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function dateInverter( $date ) { $newYear = substr($date,0,4); $newMonth = substr($date,5,2); $newDay = substr($date,8,2); $newRest = substr($date,11,100); return $newDay."-".$newMonth."-".$newYear." ".$newRest; } //decizie function decizie_delete( $facturaId ) { $query = "DELETE FROM `decizie` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function command_adddecizie( $userid , $stockid , $number, $content , $nemotivate , $hrid , $inceputData , $nrArt , $cfs , $contractNr , $contractData ) { $content = addslashes ($content); $insertQ = "INSERT INTO `decizie` ( `id` , `userid` , `stockid` , `secondSerial` , `hrid` , `content` , `ondate` , `active` , `printed` , `closed` , `demisie`, `incepandData`, `nrContract`, `nrArt`, `dataContract`, `cfs`, `nemotivate` ) VALUES (NULL , '$userid', '$stockid' , '$number', '$hrid', '$content', NOW(), '1', '0', '0', '','$inceputData' ,'$contractNr', '$nrArt' , '$contractData' , '$cfs' , '$nemotivate');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function command_getdecizie( $pageno = -1, $orderby , $hrid ) { $query = "SELECT * FROM `decizie` WHERE `active` ='1' AND `hrid` = '$hrid' ORDER BY secondserial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function decizie_setActiveNess( $factid , $state ) { $update = "UPDATE `decizie` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ); } function decizie_modFactura( $id, $userid , $stockid , $number, $content , $nemotivate , $hrid , $inceputData , $nrArt , $cfs , $contractNr , $contractData ) { $content = addslashes ($content); $updateQ = "UPDATE `decizie` SET `userid` = '$userid', `stockid` = '$stockid', `secondserial` = '$number', `content` = '$content', `hrid` = '$hrid', `nemotivate` = '$nemotivate', `incepandData` = '$inceputData', `nrArt` = '$nrArt', `cfs` = '$cfs', `nrContract` = '$contractNr', `dataContract` = '$contractData' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ); } function decizie_setPrinted( $id , $value ) { $updateQ = "UPDATE `decizie` SET `printed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function decizie_setClosed( $id , $value ) { $updateQ = "UPDATE `decizie` SET `closed` = '$value' WHERE `id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function decizie_setSerial( $id , $serial ) { $update = "UPDATE `decizie` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function decizie_getFacturi() { $select = "SELECT * FROM `decizie`"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function generateDataFromdecizie( $id ) { $select = "SELECT * FROM `decizie` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function decizie_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $firstserial, $secondserial, $serial) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "platite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`secondserial` = '$searchval'"; else $plus_search="AND `p`.`forname` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `decizie` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; $result = mysql_query( $query ) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { if(convertNumber($pais[ $row["id"] ]["paid"])==convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `decizie` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1' ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu == "neplatite") { //behozom a kifizeteseket $pais = factura_getPaidValues(); if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`secondserial` = '$searchval'"; else $plus_search="AND `p`.`forname` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `decizie` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; $result = mysql_query( $query ) or die(mysql_error()); $paidQuery=""; while($row = mysql_fetch_array( $result )) { //fizetve if(convertNumber($pais[ $row["id"] ]["paid"])!=convertNumber($row["value"] * $row["cursValue"])) $paidQuery.=" OR `f`.id = ".$row["id"]." "; } $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `decizie` f, `hr` p WHERE `p`.`id` = `f`.`hrid` ".$plus_search." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND (`f`.id = '0'".$paidQuery.") AND `f`.active = '1' ORDER BY $orderby $ordermode LIMIT $from, $count"; } if($filter_menu != "platite" && $filter_menu != "neplatite" && $filter_menu != "expirate") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial") { if($serial!=NULL) $serialFilter.= " AND `f`.`seconderial` = '$serial'"; $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `decizie` f, `hr` p WHERE `p`.`id` = `f`.`hrid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$serialFilter.$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; } else { $query = "SELECT `f`.*, `p`.`forname`, `p`.`lastname` FROM `decizie` f, `hr` p WHERE `p`.`forname` LIKE '%$searchval%' AND `p`.`id` = `f`.`hrid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; } } return $query; } function decizie_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function decizie_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function decizie_getFactura( $id ) { $select = "SELECT * FROM `decizie` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } //commandForClientAdv function factura_getCommandForClientAdvFacturi( $commandId, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `facturi` WHERE `fromActAdvId`='$commandId' AND `active` ='1' AND `type`='1' ORDER BY ondate $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getCommandById($id){ $query = "SELECT * FROM `comandaForClientAdv` WHERE `id`='$id'"; $result=mysql_query( $query ) or die(mysql_error()); if ($result) return mysql_fetch_array($result); else return NULL; } function factura_getCommandForClientAdvFacturiProforma( $commandId, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `facturi` WHERE `fromActAdvId`='$commandId' AND `active` ='1' AND `type`='0' ORDER BY ondate $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getCommandForClientAdvOferte( $commandId, $pageno = -1, $orderby = "desc" ) { $query0 = "SELECT * FROM `comandaForClientAdv` WHERE `id`='$commandId' AND `active` ='1' AND `firstserial`='0'"; $results0 = mysql_query( $query0 ); if( mysql_num_rows($results0) <= 0 )return NULL; $row0 = mysql_fetch_array( $results0 ); $ofertaId = $row0["numberSerial"]; $query = "SELECT * FROM `comandaForClientAdv` WHERE `id`='$ofertaId' AND `active` ='1' AND `firstserial`='1'"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_num_rows($results) <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function factura_getCommandForClientAdvFacturiTotalAndPaid( $commandId ) { $query = "SELECT * FROM `facturi` WHERE `fromActAdvId`='$commandId' AND `active` ='1' AND `type`='1'"; $results = mysql_query( $query ) or die(mysql_error()); $pais = factura_getPaidValues(); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $totalValue["value"]+=convertNumber($row["value"]*$row["cursValue"]); $totalValue["paid"]+=convertNumber($pais[ $row["id"] ]["paid"]); } return $totalValue; } function command_getPartnerCommandForClientAdv( $clientid, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `comandaForClientAdv` WHERE `clientid`=$clientid AND `active` ='1' ORDER BY numberSerial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getCommandForClientAdv( $pageno = -1, $orderby , $firstserial) { $query = "SELECT * FROM `comandaForClientAdv` WHERE `firstserial` = '$firstserial' ORDER BY secondserial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, 1"; } $results = mysql_query( $query ) or die(mysql_error()); if( !$results )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } //contractForComanda function contractForComanda_unRegisterItems($id) { $qu="DELETE FROM `contractForComandaItems` WHERE `contractId`='$Id' "; $result2=mysql_query($qu) or die(mysql_error()); } function contractForComanda_delete( $Id ) { $qu="DELETE FROM `contractForComandaItems` WHERE `contractId`='$Id' "; $result2=mysql_query($qu) or die(mysql_error()); $query = "DELETE FROM `contractForComanda` WHERE `id`='$Id' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } //nincs kesz function contractForComanda_registerItems111( $contractid,$comandaid,$ondate,$serviceid , $stokid,$name,$price,$quantity,$sellType,$period){ $query = "INSERT INTO comandaForClientAdvItems(`id`,`comandaid`,`ondate`,`prodid`,`stockid`,`name`,`unitPrice`,`moneyType`,`um`,`quantity`,`sellType`,`period`,`priceWithoutTva`,`tva`,`editTva`,`startDate`,`endDate`,`ziua`,`data`,`textDinGrafica`,`suport`,`cromatica`,`dimensiuniX`,`dimensiuniY`,`format`,`finisare`,`finisarePrice`,`termenDeRealizare`,`facturat`, `comment`) VALUES (NULL, '$factid', NOW() , '$productid', '$stockid', '$productname', '$unitprice' , '$moneytype', '$um' , '$quantity', '$sellType' , '$period' , '$pricewithouttva' , '$tva' , '$TVAcalculare', '$startdate', '$enddate', '$ziua', '$data', '$textDinGrafica', '$suport', '$cromatica', '$dimensiuniX', '$dimensiuniY', '$format', '$finisare', '$finisarePrice', '$termenDeRealizare','$facturat','$comments');"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function insertContractForComandaRegisteredItems($contractId,$comandaId,$items){ for ($i=0;$i 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getCommandForClientAdvPunct( $defStockId , $pageno = -1, $orderby ) { $query = "SELECT * FROM `comandaForClientAdv` command, `users` users WHERE command.`active` ='1' AND command.`userid`=users.`id` AND users.`defstock` = '$defStockId' ORDER BY command.`id` ASC"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $counter=0; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; $counter++; } return $counter; } function getCommandForClientAdv($commandid) { $query="SELECT * FROM comandaForClientAdv WHERE `id`='$commandid'"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } function getCommandForClientAdvItems($commandid) { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$commandid'"; $result=mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) { $list[ $row["id"] ] = $row; } return $list; } function getCommandForClientAdvItemsCount($commandid) { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$commandid'"; $i=0; $result=mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) { $i++; } return $i; } function stats_commandForClientAdvGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `comandaForClientAdv` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function commandForClientAdv_delete( $facturaId ) { $query = "DELETE FROM `comandaForClientAdv` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function command_addcommandForClientAdv( $clientid , $userid , $stockid , $rawvalue , $value , $serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei, $onValuta , $cursValue, $shipperinfo,$directDelivery,$dangerous,$truckerinfo,$truckerAmountCurrency,$truckerAmount,$loadingPlace,$loadingDate,$dischargePlace,$dischargeDate,$addFacturaClient,$facturaAmount,$facturaAmountCurrency,$_comments,$lastSerial,$facturaAmountTva,$cursValue,$truckerAmountTva,$truckerPartnerInfo,$comments,$adr,$driversName,$driversTel,$profit,$shippername,$mawb,$hawb, $clientPunctLucru, $termenExecutiei, $contactPerson,$comanda_numarar1,$location,$telemarketing,$contact,$vanzare,$executare,$telemarketingPro,$contactPro,$vanzarePro,$executarePro,$nrTemplate,$scadenta,$observatii,$suplimentPages,$suplimentContent,$depid,$contentWP,$ondate) { $content = addslashes ($content); $contentWP = addslashes ($contentWP); $insertQ = "INSERT INTO `comandaForClientAdv` ( `id` , `clientid` , `userid` , `stockid` , `firstserial` , `secondserial` , `itemForClient` , `numberSerial` , `clientShipperAddressId` , `clientLoadingAddressId` , `loadingDate` , `directDelivery` , `dangerousGood` , `facturaForClientId` , `facturaForClientRawValue` , `FacturaForClientValue` , `FacturaForClientInfo` , `facturaForClientPayMode` , `facturaForClientTermen` , `content` , `ondate` , `active` , `printed` , `closed` , `cursValutar`, `truckerId`, `dischargeDate`, `dischargePlace`, `truckerAmount`, `truckerAmountCurrency`, `truckerAmountTva`, `truckerPartnerInfo`, `comments`, `adr`, `driversName`, `driversTel`, `profit`, `shippername`, `mawb`, `hawb`, `clientPunctLucru`, `termenExecutiei`, `contactPerson`, `plata`, `locationId`, `telemarketing`, `contact`, `vanzare`, `executare`, `telemarketingPro`, `contactPro`, `vanzarePro`, `executarePro`, `nrTemplate`, `scadenta`, `observatii`, `suplimentPages`, `suplimentContent`, `departament`, `contentWithoutPrices` ) VALUES (NULL , '$clientid', '$userid', '$stockid' , '$serial', '$number', '', '$lastSerial', '$shipperinfo', '$loadingPlace', '$loadingDate', '$directDelivery', '$dangerous', '$addFacturaClient', '$facturaAmount', '$facturaAmountTva', '$facturaAmountCurrency', '', '' , '$content', '$ondate', '1', '0', '0', '$cursValue','$truckerinfo','$dischargeDate','$dischargePlace','$truckerAmount','$truckerAmountCurrency','$truckerAmountTva','$truckerPartnerInfo','$comments','$adr','$driversName','$driversTel','$profit','$shippername','$mawb','$hawb', '$clientPunctLucru', '$termenExecutiei','$contactPerson','$comanda_numarar1','$location','$telemarketing','$contact','$vanzare','$executare','$telemarketingPro','$contactPro','$vanzarePro','$executarePro','$nrTemplate','$scadenta','$observatii','$suplimentPages','$suplimentContent','$depid','$contentWP');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } //ide jon meg egy fugveny, ha lejart egy megrendelolap szolgaltatasainak megrendelese... function command_ExpiredCommands() { $query = "SELECT * FROM `comandaForClientAdv` where `active`='1' AND `firstserial`='0'"; $result = mysql_query( $query ) or die(mysql_error()); $j=0; while( $row = mysql_fetch_array($result) ) { $registeredItems = getCommandForPartnerAdvRegisteredItemsForAvertizare ($row["id"]); $registeredItemsCount = getCommandForPartnerAdvRegisteredItemsCountForAvertizare ($row["id"]); $counter=1; for($i=1;$i<=$registeredItemsCount;$i++) { $nowDate = date("Y-m-d"); $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareComandaDate"] * 24 * 60 * 59); $fromDateNextWeek = date("Y-m-d",$nextWeek); $mustFacturat=0; if($registeredItems[$i]["startDate"]=="0000-00-00") { if($registeredItems[$i]["termenDeRealizare"]!="0000-00-00") $registeredItems[$i]["startDate"]=$registeredItems[$i]["termenDeRealizare"]; } if($registeredItems[$i]["startDate"]!="0000-00-00") { //megnezem, hogy mi volt az utolso szamlazasi datum $facturaLastDate = factura_getFacturaItemsLastDate( $row["id"] , $registeredItems[$i]["prodid"] ); if($registeredItems[$i]["period"]!="unic") { //es megnezem, hogy a mai nappal szamolva kell szamlazni vagy sem? if($facturaLastDate["endDate"]!=NULL && subtract_dates($registeredItems[$i]["endDate"],$fromDateNextWeek)<0) { //megnezem a mai datum es az utolso szamlazasi datum kozti kulonbseget (ha nincs szamlazasi datum akkor a megrendeles elso napja) if(subtract_dates($facturaLastDate["endDate"],$fromDateNextWeek)>0) { $mustFacturat=1; $row["deFacturatDeLaDataDe"]=$facturaLastDate["endDate"]; } } if($facturaLastDate["endDate"]==NULL && subtract_dates($registeredItems[$i]["endDate"],$fromDateNextWeek)<0) { if(subtract_dates($registeredItems[$i]["startDate"],$fromDateNextWeek)>0) { $mustFacturat=1; $row["deFacturatDeLaDataDe"]=$registeredItems[$i]["endDate"]; } } } else { // ebben az esetben meg kell nezzem, hogy van e olyan datum ami nem volt kiszamlazva // megkeresem a datumokat $commandDates = commandForClientAdv_getItemsDates( $row["id"], $registeredItems[$i]["prodid"] , $registeredItems[$i]["id"]); if($commandDates) while($dates=mysql_fetch_array($commandDates)) { if($dates["onFactura"]!=1) { if(subtract_dates($dates["date"],$fromDateNextWeek)>0) { $mustFacturat=1; $row["deFacturatDeLaDataDe"]=$dates["date"]; } } } } } if($mustFacturat==1) { // ez a resz ha kell szamlazni a megrendelot, tehat beteszem az avertizare listaba $id_=$row["id"]; // megnezem, hogy bent van e esetleg mar az avertizare a listaban $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=9;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) { $list[$j++]=$row; } } else { $list[$j++]=$row; } } } } return $list; } function command_ExpiredCommandsTime() { $query = "SELECT * FROM `comandaForClientAdv` where `active`='1' AND `firstserial`='1'"; $result = mysql_query( $query ) or die(mysql_error()); $j=0; while( $row = mysql_fetch_array($result) ) { $registeredItems = getCommandForPartnerAdvRegisteredItems ($row["id"]); $registeredItemsCount = getCommandForPartnerAdvRegisteredItemsCount ($row["id"]); $counter=1; for($i=1;$i<=$registeredItemsCount;$i++) { $nowDate = date("Y-m-d"); $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareComandaDateExpire"] * 24 * 60 * 59); $fromDateNextWeek = date("Y-m-d",$nextWeek); $mustFacturat=0; //megnezem hogy a lejarati datum nagyobb-e mint a mai nap if($registeredItems[$i]["endDate"]!="0000-00-00" && subtract_dates($registeredItems[$i]["endDate"],$fromDateNextWeek)>0 && $registeredItems[$i]["period"]!="unic") { $mustFacturat=1; } if($mustFacturat==1) { // ez a resz ha kell szamlazni a megrendelot, tehat beteszem az avertizare listaba $id_=$row["id"]; // megnezem, hogy bent van e esetleg mar az avertizare a listaban $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=11;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) { $list[$j++]=$row; } } else { $list[$j++]=$row; } } } } return $list; } function command_addcontractForComanda($nrTemplate, $secondserial,$clientid ,$commandid, $userid , $content , $FaraTVA,$CuTVA,$stockid,$termenExecutiei, $contactPerson,$depid) { $content = addslashes ($content); $insertQ = "INSERT INTO `contractForComanda` ( `id` , `secondserial`, `clientid` , `FromActAdvId`, `userid` , `content` , `TotalFaraTVA` , `TotalCuTVA` , `ondate` , `active` , `printed` , `closed` , `stockid`, `termenExecutie`, `contactPerson`, `departament`, `nrTemplate` ) VALUES (NULL , '$secondserial' , '$clientid','$commandid', '$userid', '$content', '$FaraTVA' , '$CuTVA' , NOW(), '1', '0', '0', '$stockid', '$termenExecutiei','$contactPerson','$depid','$nrTemplate');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function commandForClientAdv_registerItems( $factid , $productid, $productname , $unitprice , $moneytype, $um, $sellType, $quantity, $period , $pricewithouttva , $tva, $TVAcalculare, $startdate, $enddate, $ziua, $data, $stockid , $facturat,$comments) { $query = "INSERT INTO comandaForClientAdvItems(`id`,`comandaid`,`ondate`,`prodid`,`stockid`,`name`,`unitPrice`,`moneyType`,`um`,`quantity`,`sellType`,`period`,`priceWithoutTva`,`tva`,`editTva`,`startDate`,`endDate`,`ziua`,`data`,`textDinGrafica`,`suport`,`cromatica`,`dimensiuniX`,`dimensiuniY`,`format`,`finisare`,`finisarePrice`,`termenDeRealizare`,`facturat`, `comment`) VALUES (NULL, '$factid', NOW() , '$productid', '$stockid', '$productname', '$unitprice' , '$moneytype', '$um' , '$quantity', '$sellType' , '$period' , '$pricewithouttva' , '$tva' , '$TVAcalculare', '$startdate', '$enddate', '$ziua', '$data', '$textDinGrafica', '$suport', '$cromatica', '$dimensiuniX', '$dimensiuniY', '$format', '$finisare', '$finisarePrice', '$termenDeRealizare','$facturat','$comments');"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function commandForClientAdv_registerItemsSpecial( $factid , $productid, $productname , $unitprice , $moneytype, $um, $quantity, $pricewithouttva , $tva, $TVAcalculare, $stockid , $textDinGrafica, $suport, $cromatica, $dimensiuniX, $dimensiuniY, $format, $finisare, $finisarePrice, $termenDeRealizare , $facturat,$comments) { $query = "INSERT INTO comandaForClientAdvItems VALUES (NULL, '$factid', NOW() , '$productid', '$stockid', '$productname', '$unitprice' , '$moneytype', '$um' , '$quantity', '$sellType' , '$period' , '$pricewithouttva' , '$tva' , '$TVAcalculare', '$startdate', '$enddate', '$ziua', '$data', '$textDinGrafica', '$suport', '$cromatica', '$dimensiuniX', '$dimensiuniY', '$format', '$finisare', '$finisarePrice', '$termenDeRealizare','$facturat','$comments');"; mysql_query( $query ) or die($query." ".mysql_error()); return mysql_insert_id(); } function commandForClientAdv_registerItemsDates ( $command, $serviceid, $date, $fact , $rowId) { $query = "INSERT INTO comandaForClientAdvItemsDates VALUES (NULL, '$command', '$serviceid', '$date' , NOW(), '$fact','$rowId');"; $result = mysql_query( $query ) or die($query." ".mysql_error()); } function commandForClientAdv_getItemsDates($commandid, $serviceid , $itemsId) { $query=" SELECT * FROM comandaForClientAdvItemsDates WHERE `commandid`='$commandid' AND `serviceid`='$serviceid' AND `itemsId` = '$itemsId' order by `id` "; //echo $query; $result=mysql_query( $query ) or die(mysql_error()); if( mysql_num_rows($result)!=0 ) { return $result; } else if($itemsId==NULL) { $query=" SELECT * FROM comandaForClientAdvItemsDates WHERE `commandid`='$commandid' AND `serviceid`='$serviceid'"; $result=mysql_query( $query ) or die(mysql_error()); //echo $query; if( mysql_num_rows($result)!=0 )return $result; else return NULL; } } function commandForClientAdv_getItemsDatesOnlyToFacture($commandid) { $query=" SELECT * FROM comandaForClientAdvItemsDates WHERE `commandid`='$commandid' AND `onFactura`='' order by `date` ASC"; $result=mysql_query( $query ) or die(mysql_error()); if( mysql_num_rows($result)!=0 ) { return $result; } else return NULL; } function commandForClientAdv_getItemsForFisa5($datum,$orasid) { $query="SELECT * FROM comandaForClientAdv order by `id`"; $comanda=mysql_query( $query ) or die(mysql_error()); if($comanda) while($comandak=mysql_fetch_array($comanda)) { $punct=$comandak["clientPunctLucru"]; $query2="SELECT * FROM partners_punctDeLucru WHERE `id`=$punct"; $oras=mysql_query( $query2 ) or die(mysql_error()); if($oras) while($szitik=mysql_fetch_array($oras)) { if($szitik["oras"]==$orasid) { $comandaid=$comandak["id"]; $query=" SELECT * FROM comandaForClientAdvItems WHERE `prodid` BETWEEN 22 AND 31 AND `comandaid`='$comandaid'"; $result=mysql_query( $query ) or die(mysql_error()); if( mysql_num_rows($result)!=0 ) while( $row = mysql_fetch_array( $result ) ) { $servicse=getServiceEntry($row["prodid"]); if( $datum == $row["endDate"]) { if($servicse["durata"]!=0) $items[ $row["id"] ] = $row; } } } } } return $items; } function commandForClientAdv_getItemsForFisa1($datum,$orasid) { $query="SELECT * FROM comandaForClientAdv order by `id`"; $comanda=mysql_query( $query ) or die(mysql_error()); if($comanda) while($comandak=mysql_fetch_array($comanda)) { $punct=$comandak["clientPunctLucru"]; $query2="SELECT * FROM partners_punctDeLucru WHERE `id`=$punct"; $oras=mysql_query( $query2 ) or die(mysql_error()); if($oras) while($szitik=mysql_fetch_array($oras)) { if($szitik["oras"]==$orasid) { $comandaid=$comandak["id"]; $query2=" SELECT * FROM comandaForClientAdvItems WHERE period='zilnic' AND `comandaid`='$comandaid'"; $result=mysql_query( $query2 ) or die(mysql_error()); if( mysql_num_rows($result)!=0 ) while( $row = mysql_fetch_array( $result ) ) { $servicse=getServiceEntry($row["prodid"]); if($datum >= $row["startDate"] && $datum <= $row["endDate"]) { if($servicse["durata"]!=0) $items[ $row["id"] ] = $row; } } } } } return $items; } function commandForClientAdv_getItemsForFisa11($datum,$orasid) { $query="SELECT * FROM comandaForClientAdv order by `id`"; $comanda=mysql_query( $query ) or die(mysql_error()); if($comanda) while($comandak=mysql_fetch_array($comanda)) { $punct=$comandak["clientPunctLucru"]; $query2="SELECT * FROM partners_punctDeLucru WHERE `id`=$punct"; $oras=mysql_query( $query2 ) or die(mysql_error()); if($oras) while($szitik=mysql_fetch_array($oras)) { if($szitik["oras"]==$orasid) { $comandaid=$comandak["id"]; $query2=" SELECT * FROM comandaForClientAdvItems WHERE period='zilnic' AND `comandaid`='$comandaid'"; $result=mysql_query( $query2 ) or die(mysql_error()); if( mysql_num_rows($result)!=0 ) while( $row = mysql_fetch_array( $result ) ) { $servicse=getServiceEntry($row["prodid"]); if($datum >= $row["startDate"] && $datum <= $row["endDate"]) { if($servicse["durata"]!=0) $items[ $row["id"] ] = $row; } } } } } return $items; } function commandForClientAdv_getItemsForFisa2($datum,$orasid) { $query="SELECT * FROM comandaForClientAdv order by `id`"; $comanda=mysql_query( $query ) or die(mysql_error()); if($comanda) while($comandak=mysql_fetch_array($comanda)) { $punct=$comandak["clientPunctLucru"]; $query2="SELECT * FROM partners_punctDeLucru WHERE `id`=$punct"; $oras=mysql_query( $query2 ) or die(mysql_error()); if($oras) while($szitik=mysql_fetch_array($oras)) { if($szitik["oras"]==$orasid) { $comandaid=$comandak["id"]; $query=" SELECT * FROM comandaForClientAdvItems WHERE period='lunar' AND `comandaid`='$comandaid'"; $result=mysql_query( $query ) or die(mysql_error()); $day=substr($datum,8,2); if( mysql_num_rows($result)!=0 ) while( $row = mysql_fetch_array( $result ) ) { $servicse=getServiceEntry($row["prodid"]); if(($datum >= $row["startDate"] && $datum <= $row["endDate"]) && ($day==$row["data"] || $day=="0".$row["data"])) { if($servicse["durata"]!=0) $items[ $row["id"] ] = $row; } } } } } return $items; } function commandForClientAdv_getItemsForFisa3($datum,$orasid) { $query="SELECT * FROM comandaForClientAdv order by `id`"; $comanda=mysql_query( $query ) or die(mysql_error()); if($comanda) while($comandak=mysql_fetch_array($comanda)) { $punct=$comandak["clientPunctLucru"]; $query2="SELECT * FROM partners_punctDeLucru WHERE `id`=$punct"; $oras=mysql_query( $query2 ) or die(mysql_error()); if($oras) while($szitik=mysql_fetch_array($oras)) { if($szitik["oras"]==$orasid) { $comandaid=$comandak["id"]; $query3=" SELECT * FROM comandaForClientAdvItems WHERE period='unic' AND `comandaid`='$comandaid'"; $result=mysql_query( $query3 ) or die(mysql_error()); $day=substr($datum,8,2); if( mysql_num_rows($result)!=0 ) while( $row = mysql_fetch_array( $result ) ) { $comandaid=$row["comandaid"]; $service=$row["prodid"]; $query4=" SELECT * FROM comandaForClientAdvItemsDates WHERE commandid='$comandaid'"; $result2=mysql_query( $query4 ); if($result2) while( $row2 = mysql_fetch_array( $result2 ) ) { $servicse=getServiceEntry($row["prodid"]); if($datum==$row2["date"] ) { if($servicse["durata"]!=0) $items[ $row["id"] ] = $row; } } } } } } return $items; } function commandForClientAdv_getItemsForFisa33($datum,$orasid) { $query="SELECT * FROM comandaForClientAdv order by `id`"; $comanda=mysql_query( $query ) or die(mysql_error()); if($comanda) while($comandak=mysql_fetch_array($comanda)) { $punct=$comandak["clientPunctLucru"]; $query2="SELECT * FROM partners_punctDeLucru WHERE `id`=$punct"; $oras=mysql_query( $query2 ) or die(mysql_error()); while($szitik=mysql_fetch_array($oras)) { if($szitik["oras"]==$orasid) { $comandaid=$comandak["id"]; $query3=" SELECT * FROM comandaForClientAdvItems WHERE period='unic' AND `comandaid`='$comandaid'"; $result=mysql_query( $query3 ) or die(mysql_error()); $day=substr($datum,8,2); if( mysql_num_rows($result)!=0 ) while( $row = mysql_fetch_array( $result ) ) { $comandaid=$row["comandaid"]; $service=$row["prodid"]; $query4=" SELECT * FROM comandaForClientAdvItemsDates WHERE commandid='$comandaid'"; $result2=mysql_query( $query4 ); if($result2) while( $row2 = mysql_fetch_array( $result2 ) ) { $servicse=getServiceEntry($row["prodid"]); if($datum==$row2["date"] ) { if($servicse["durata"]!=0) $items[ $row["id"] ] = $row; } } } } } } return $items; } function commandForClientAdv_getItemsForFisa4($datum,$orasid) { $query="SELECT * FROM comandaForClientAdv order by `id`"; $comanda=mysql_query( $query ) or die(mysql_error()); if($comanda) while($comandak=mysql_fetch_array($comanda)) { $punct=$comandak["clientPunctLucru"]; $query2="SELECT * FROM partners_punctDeLucru WHERE `id`=$punct"; $oras=mysql_query( $query2 ) or die(mysql_error()); if($oras) while($szitik=mysql_fetch_array($oras)) { if($szitik["oras"]==$orasid) { $comandaid=$comandak["id"]; $query=" SELECT * FROM comandaForClientAdvItems WHERE period='saptamanal' AND `comandaid`='$comandaid'"; $result=mysql_query( $query ) or die(mysql_error()); if($result) while($row=mysql_fetch_array($result)) { if($row["ziua"]!=NULL && $row["ziua"]!="Selectati" && $row["ziua"]!="") { $day=$row["ziua"]; if($day==luni) $day=1; if($day==marti) $day=2; if($day==miercuri) $day=3; if($day==joi) $day=4; if($day==vineri) $day=5; if($day==sambata) $day=6; if($day==duminica) $day=0; $year1=substr($datum,0,4); $month1=substr($datum,5,2); $day1=substr($datum,8,2); $weekday = date("w", mktime(0,0,0,$month1,$day1,$year1)); $servicse=getServiceEntry($row["prodid"]); if(($datum > $row["startDate"] && $datum < $row["endDate"]) && ($weekday==$day)) { if($servicse["durata"]!=0) $items[ $row["id"] ] = $row; } } else { $year2=substr($datum,0,4); $month2=substr($datum,5,2); $day2=substr($datum,8,2); $user_date = $year1.'-01-01'; $user_date = strtotime($$user_date); $firstday = date('w', $user_date); if( $firstday==1) { $weeknum = strftime("%W",mktime(0,0,0,$month2,$day2,$year2)); } else { $weeknum = strftime("%W",mktime(0,0,0,$month2,$day1,$year2))+1; } $servics=$row["prodid"]; $client=$comandak["clientid"]; $query="SELECT * FROM fisaZilnicadeLucru_items WHERE `serviciiid`='$servics' AND `clientid`='$client' AND `weeknum`='$weeknum' AND `realizat`=0"; $servicse=getServiceEntry($row["prodid"]); $result6=mysql_query( $query ) or die(mysql_error()); if($result6) { if(mysql_num_rows($result6)==0) { if($servicse["durata"]!=0) $items[ $row["id"] ] = $row; } } } } } } } return $items; } function commandForClientAdv_unRegisterItems( $factid ) { $query = "DELETE FROM `comandaForClientAdvItems` WHERE `comandaForClientAdvItems`.`comandaid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); $_SESSION["commandForClientAdv"]["edited"]=1; } function commandForClientAdv_unRegisterItemsDates( $factid ) { $query = "DELETE FROM `comandaForClientAdvItemsDates` WHERE `commandid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); $_SESSION["commandForClientAdv"]["edited"]=0; } function commandForClientAdv_unRegisterItemsDatesOnlyDate( $factid , $produsid , $rowid) { $query = "DELETE FROM `comandaForClientAdvItemsDates` WHERE `commandid` = '$factid'"; mysql_query( $query ) or die(mysql_error()); $_SESSION["commandForClientAdv"]["edited"]=0; } function commandForClientAdv_setActiveNess( $factid , $state ) { $update = "UPDATE `comandaForClientAdv` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function commandForClientAdv_modFactura( $id , $clientid , $userid , $stockid , $rawvalue , $value ,$serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei , $onValuta , $cursValue, $shipperinfo,$directDelivery,$dangerous,$truckerinfo,$truckerAmountCurrency,$truckerAmount,$loadingPlace,$loadingDate,$dischargePlace,$dischargeDate,$addFacturaClient,$facturaAmount,$facturaAmountCurrency,$_comments, $lastSerial,$facturaAmountTva,$cursValue,$truckerAmountTva,$truckerPartnerInfo,$comments,$adr,$driversName,$driversTel,$profit,$shippername,$mawb,$hawb,$punctdelucru,$termenexecutiei,$contactperson,$location,$telemarketing,$contact,$vanzare,$executare,$telemarketingPro,$contactPro,$vanzarePro,$executarePro,$nrTemplate,$scadenta,$observatii,$suplimentPages,$suplimentContent,$depid,$contentWP,$secondserial) { $content = addslashes ($content); $contentWP = addslashes ($contentWP); $updateQ = "UPDATE `comandaForClientAdv` SET `clientid` = '$clientid', `numberSerial` = '$lastSerial', `secondserial`='$secondserial', `clientShipperAddressId` = '$shipperinfo', `clientLoadingAddressId` = '$loadingPlace', `loadingDate` = '$loadingDate', `directDelivery` = '$directDelivery', `dangerousGood` = '$dangerous', `content` = '$content', `contentWithoutPrices` = '$contentWP', `facturaForClientId` = '$addFacturaClient', `facturaForClientRawValue` = '$facturaAmount', `FacturaForClientValue` = '$facturaAmountTva', `FacturaForClientInfo` = '$facturaAmountCurrency', `truckerId` = '$truckerinfo', `dischargeDate` = '$dischargeDate', `dischargePlace` = '$dischargePlace', `truckerAmount` = '$truckerAmount', `truckerAmountCurrency` = '$truckerAmountCurrency', `truckerAmountTva` = '$truckerAmountTva', `truckerPartnerInfo` = '$truckerPartnerInfo', `comments` = '$comments', `adr` = '$adr', `driversName` = '$driversName', `driversTel` = '$driversTel', `profit` = '$profit', `shippername` = '$shippername', `mawb` = '$mawb', `hawb` = '$hawb', `clientPunctLucru` = '$punctdelucru', `termenExecutiei` = '$termenexecutiei', `contactPerson` = '$contactperson', `locationId` = '$location', `telemarketing` = '$telemarketing', `contact` = '$contact', `vanzare` = '$vanzare', `executare` = '$executare', `telemarketingPro` = '$telemarketingPro', `contactPro` = '$contactPro', `vanzarePro` = '$vanzarePro', `executarePro` = '$executarePro', `nrTemplate` = '$nrTemplate', `scadenta` = '$scadenta', `observatii` = '$observatii', `suplimentPages` = '$suplimentPages', `suplimentContent` = '$suplimentContent', `departament` = '$depid', `cursValutar` = '$cursValue' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die($updateQ." ".mysql_error()); } function contractForComanda_setActiveNess( $factid , $state ) { $update = "UPDATE `contractForComanda` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function contractForComanda_registerItems( $factid , $comandaid,$productid, $productname , $unitprice , $sellType, $quantity, $period , $pricewithouttva , $tva, $TVAcalculare, $startdate, $enddate, $ziua, $data, $stockid ) { $query = "INSERT INTO contractForComanda VALUES (NULL, '$factid','$comandaid', NOW() , '$productid', '$stockid', '$productname', '$unitprice' , '$quantity', '$sellType' , '$period' , '$pricewithouttva' , '$tva' , '$TVAcalculare', '$startdate', '$enddate', '$ziua', '$data');"; mysql_query( $query ) or die(mysql_error()); } function contractForComanda_modFactura($nrTemplate, $secondserial , $id , $clientid , $fromActId, $userid , $content ,$FaraTVA,$CuTVA, $stockid ,$termenexecutiei,$contactperson,$depid) { $content = addslashes ($content); $updateQ = "UPDATE `contractForComanda` SET `clientid` = '$clientid', `secondserial` = '$secondserial', `fromActAdvId`= '$fromActId', `userid`= '$userid', `content` = '$content', `TotalFaraTVA` = '$FaraTVA', `TotalCuTVA` = '$cuTVA', `stockid` = '$stockid', `termenExecutie` = '$termenexecutiei', `contactPerson` = '$contactperson', `departament` = '$depid', `nrTemplate`='$nrTemplate' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function commandForClientAdv_setPrinted( $id , $value ) { $updateQ = "UPDATE `comandaForClientAdv` SET `printed` = '$value' WHERE `id` ='$id' LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function commandForClientAdv_setClosed( $id , $value ) { $updateQ = "UPDATE `comandaForClientAdv` SET `closed` = '$value' WHERE `id` ='$id' LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function commandForClientAdv_setSerial( $id , $serial ) { $update = "UPDATE `comandaForClientAdv` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function commandForClientAdv_getFacturi() { $select = "SELECT * FROM `comandaForClientAdv`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function commandForClientAdv_getFactura( $id ) { $select = "SELECT * FROM `comandaForClientAdv` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function contractForComanda_getFactura( $id ) { $select = "SELECT * FROM `contractForComanda` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function contractForComanda_FromComandaGetFactura( $comandaId ) { $select = "SELECT * FROM `contractForComanda` WHERE `fromActAdvId`='$comandaId' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function contractForComandaContract_GetFactura( $comandaId ) { $select = "SELECT * FROM `contractForComanda` WHERE `clientid`='$comandaId' AND `fromActAdvId`='0' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function generateDataFromComandaForClientAdv( $id ) { $select = "SELECT * FROM `comandaForClientAdv` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } //////////////////////////////////////////////////////////////////////////////// ///////////////////// TODO Szuro fuggvenyek //////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Az entry_lister php-ban alkalmazott fuggveny // // ugyanazt vegzi, mint a commandForClientAdv_searchGenerateQuery() csak // kevesbbe komplex kell legyen // egyelore az elozonek a masolata TODO enrtyListerSearchProduct() function enrtyListerSearchProduct() { //hanyat akar egy oldarra megjeleniteni $count = $_SESSION["settings"]["searchcount"]; ///honnan kezdje $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); // filter menut a linkbol kapja valtozokent vagy a cautare postolasakor // itt kezelunk le kulonbozo esteket //filter_menu if($filter_menu == NULL) $filterMenuSql=""; return $query; } // Kigeneralja a lekerdezest egy csomo mindeent figyelembe veve function commandForClientAdv_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $firstserial, $secondserial, $serial, $dataLabel, $location , $locationId, $serviciiId, $typeDocument,$viewall=1,$userid=0) { //hanyat akar egy oldarra megjeleniteni $count = $_SESSION["settings"]["searchcount"]; ///honnan kezdje $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); if($viewall!="1") { $viewquery= " AND ( ( f.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid') "; $viewquery.=" OR f.`id` IN (SELECT `comandaid` FROM `comandaForClientAdvItems` WHERE (`sellType`='cumparare' OR `sellType`='inchiriere') AND `prodid` IN (SELECT `id` FROM `container` WHERE `modelid` IN (SELECT `id` FROM `models` WHERE ( `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid')) ) ) )"; } //location if($location!=0) { $selectedStock = stock_getStockFromLocation($location); $selectedId = $selectedStock["id"]; $locationSql = " AND f.`stockid` = '$selectedId'"; } else { $locationSql = ""; } //location if($locationId!=0) { $locationIdSql = " AND f.`locationId` = '$locationId'"; } else { $locationIdSql = ""; } //serviciiId if($serviciiId!=0) { //servici kategoriat kapjuk meg $query = "SELECT s.* FROM service_models sm, services s WHERE sm.id = s.modelid AND `modelid`='$serviciiId'"; $serviciiSql = " AND ( `ci`.`prodid` != `ci`.`prodid` "; $result = mysql_query( $query ) or die(mysql_error()); while($row=mysql_fetch_array($result)) { $serviciiSqlId = $row["id"]; $serviciiSql .= " OR `ci`.`prodid` = '$serviciiSqlId'"; } $serviciiSql .= " ) "; $serviciiSql .=" AND `ci`.`period`!=''"; } else { $serviciiSql = ""; } //datumszuro be ki kapcsolasa if($searchval!=NULL && $searchcriteria!="serial" && $serviciiId==0) $dateFilter=""; else $dateFilter = "AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; // filter menut a linkbol kapja valtozokent vagy a cautare postolasakor // itt kezelunk le kulonbozo esteket //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "nefacturate") { $query = "SELECT `f`.* FROM `comandaForClientAdv` f, `facturi` fact WHERE `f`.`id` <> `fact`.`fromActAdvId` ".$plus_search.$locationSql.$locationIdSql." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND f.`firstserial`='$typeDocument'".$viewquery." GROUP BY `f`.`id` ORDER BY `f`.`ondate` LIMIT $from, $count"; $result = mysql_query($query) or die(mysql_error()); } if($filter_menu != "nefacturate" && $filter_menu != "faraprofit") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial") { if($firstserial!=NULL) $serialFilter.= " AND `f`.`firstserial` = '$firstserial'"; if($secondserial!=NULL) $serialFilter.= " AND `f`.`secondserial` = '$secondserial'"; if($serial!=NULL) $serialFilter.= " AND `f`.`numberSerial` = '$serial'"; if($dataLabel!=NULL) { $yearActual = substr($dataLabel,0,2); $monthActual = substr($dataLabel,2,2); $startDate = "20".$yearActual."-".$monthActual."-01"; $endDate = "20".$yearActual."-".$monthActual."-31"; $serialFilter.= " AND `f`.`ondate` BETWEEN '$startDate' AND '$endDate'"; } $query = "SELECT `f`.*, `p`.`name` FROM `comandaForClientAdv` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND f.`firstserial`='$typeDocument' ".$serialFilter.$filterMenuSql.$locationSql.$locationIdSql.$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } ///ha nics szurve else { $query = "SELECT `f`.*, `p`.`name` FROM `comandaForClientAdv` f, `partners` p, `comandaForClientAdvItems` ci WHERE `p`.`name` LIKE '%$searchval%' AND `p`.`id` = `f`.`clientid` AND `f`.`id`=`ci`.`comandaid` AND f.`firstserial`='$typeDocument' ".$dateFilter.$filterMenuSql.$locationSql.$locationIdSql.$serviciiSql.$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } } return $query; } // Kigeneralja a lekerdezest egy csomo mindeent figyelembe veve function commandForClientAdv_searchGenerateQuery2( $searchval ,$servicename, $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $firstserial, $secondserial, $serial, $dataLabel, $location , $locationId, $serviciiId, $typeDocument,$viewall=1,$userid=0) { //hanyat akar egy oldarra megjeleniteni $count = $_SESSION["settings"]["searchcount"]; ///honnan kezdje $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //location if($locationId!=0) { $locationIdSql = " AND f.`locationId` = '$locationId'"; } else { $locationIdSql = ""; } $serviciiSql = ""; //datumszuro be ki kapcsolasa if($searchval!=NULL && $searchcriteria!="serial" && $serviciiId==0) $dateFilter=""; else $dateFilter = "AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; // filter menut a linkbol kapja valtozokent vagy a cautare postolasakor // itt kezelunk le kulonbozo esteket //filter_menu if($viewall!="1") { $viewquery= " AND ( ( f.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid') "; $viewquery.=" OR f.`id` IN (SELECT `comandaid` FROM `comandaForClientAdvItems` WHERE (`sellType`='cumparare' OR `sellType`='inchiriere') AND `prodid` IN (SELECT `id` FROM `container` WHERE `modelid` IN (SELECT `id` FROM `models` WHERE ( `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid')) ) ) )"; } $servicequery=" AND f.`id` IN (SELECT `comandaid` FROM `comandaForClientAdvItems` WHERE `name` LIKE '%$servicename%' AND `quantity` !='0') "; if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "nefacturate") { $query = "SELECT `f`.* FROM `comandaForClientAdv` f, `facturi` fact WHERE `f`.`id` <> `fact`.`fromActAdvId` ".$plus_search.$locationSql.$locationIdSql." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND f.`firstserial`='$typeDocument' $viewquery $servicequery GROUP BY `f`.`id` ORDER BY `f`.`ondate` LIMIT $from, $count"; $result = mysql_query($query) or die(mysql_error()); } $noww=date("Y-m-d"); if($filter_menu != "nefacturate" && $filter_menu != "faraprofit") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if($filter_menu == "factval") $filterMenuSql =" AND `f`.`id` IN (SELECT `comandaid` FROM `comandaForClientAdvItems` WHERE `endDate`>='$noww') "; if ($searchcriteria == "serial") { if($firstserial!=NULL) $serialFilter.= " AND `f`.`firstserial` = '$firstserial'"; if($secondserial!=NULL) $serialFilter.= " AND `f`.`secondserial` = '$secondserial'"; if($serial!=NULL) $serialFilter.= " AND `f`.`numberSerial` = '$serial'"; if($dataLabel!=NULL) { $yearActual = substr($dataLabel,0,2); $monthActual = substr($dataLabel,2,2); $startDate = "20".$yearActual."-".$monthActual."-01"; $endDate = "20".$yearActual."-".$monthActual."-31"; $serialFilter.= " AND `f`.`ondate` BETWEEN '$startDate' AND '$endDate'"; } $query = "SELECT `f`.* FROM `comandaForClientAdv` f WHERE f.`firstserial`='$typeDocument' ".$serialFilter.$filterMenuSql.$locationSql.$locationIdSql.$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } ///ha nics szurve else { $query = "SELECT `f`.* FROM `comandaForClientAdv` f WHERE f.clientid IN(SELECT id FROM partners WHERE `name` LIKE '%$searchval%' OR `cui` LIKE '%$searchval%' OR `cnp` LIKE '%$searchval%') AND f.`firstserial`='$typeDocument' ".$dateFilter.$filterMenuSql.$locationSql.$locationIdSql.$serviciiSql.$viewquery.$servicequery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } } return $query; } // Kigeneralja a lekerdezest egy csomo mindeent figyelembe veve function commandForClientAdv_searchGenerateQueryForAngajatComission( $page , $orderby , $ordermode , $fromDate , $toDate , $hrid) { //hanyat akar egy oldarra megjeleniteni $count = $_SESSION["settings"]["searchcount"]; ///honnan kezdje $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //egyszer leszurjuk a lehetseges megrendelesek listajat, tehat csakis olyan //megrendeloket ellenorzunk amelyek a userhez hozza vannak kotve $queryComandaList="SELECT `c`.* FROM `comandaForClientAdv` c WHERE (`c`.`telemarketing`='$hrid' || `c`.`contact`='$hrid' || `c`.`vanzare`='$hrid' || `c`.`executare`='$hrid') AND `c`.`active`='1';"; //echo $queryComandaList; $resultComandaList=mysql_query($queryComandaList); if($resultComandaList) { $commandFilter = "(`f`.`id`= '0' "; $facturiFilter = "(`fact`.`id`='0' "; while($commandRow=mysql_fetch_array($resultComandaList)) { $selectedId=$commandRow["id"]; //kivalasztjuk az osszes szamlat amelyek a megrendelobol voltak keszitve $queryFacturiList="SELECT `f`.* FROM `facturi` f WHERE (`f`.`fromActAdvId` LIKE '%$selectedId, %' || `f`.`fromActAdvId`='$selectedId')"; //echo $queryFacturiList; $resultFacturiList=mysql_query($queryFacturiList); if($resultFacturiList) { while($facturiRow=mysql_fetch_array($resultFacturiList)) { $selectedFacturiId = $facturiRow["id"]; $facturiFilter.=" || `fact`.`id` = '$selectedFacturiId' "; } } $commandFilter.=" || `f`.`id` = '$selectedId' "; } $commandFilter.=")"; $facturiFilter.=")"; $dateFilter = "AND (`o`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND `o`.`value`!=0 AND `o`.`factid`=`fact`.`id`)"; //muszaly ezt a queryt is feldarabolni, mert lassu facturi -> ops vagy bills vagy kulon bills es kulon ops? $query = "SELECT `fact`.`id` as facturaId, `fact`.`fromActAdvId` as fromActAdvId, `o`.`factid` as opFacturaId, `o`.`value` as opValue, `o`.`ondate` as opOndate FROM `facturi` fact, `op` o WHERE ".$facturiFilter." ".$dateFilter." AND `fact`.`type`='1' GROUP BY `fact`.`id`"; //echo $query; //most letrehozunk egy id alapu comanda listat $resultFinalComandaList=mysql_query($query); $finalComandaList="(`f`.`id`=0 "; while($commandFinalRow=mysql_fetch_array($resultFinalComandaList)) { //megvan a szamla lista amit at kell konvertaljunk comanda id listaba $comandaIdSplit = split(",",$commandFinalRow["fromActAdvId"]); foreach($comandaIdSplit as $value) { $finalSelectedId=$value; $finalComandaList.=" || `f`.`id`='$finalSelectedId'"; } } //billek $dateFilter = "AND (`b`.`ondate` BETWEEN '$fromDate' AND '$toDate' AND `b`.`value`!=0 AND `b`.`factid`=`fact`.`id`)"; //muszaly ezt a queryt is feldarabolni, mert lassu facturi -> ops vagy bills vagy kulon bills es kulon ops? $query = "SELECT `fact`.`id` as facturaId, `fact`.`fromActAdvId` as fromActAdvId, `b`.`factid` as billFacturaId, `b`.`value` as billValue, `b`.`ondate` as billOndate FROM `facturi` fact, `bills` b WHERE ".$facturiFilter." ".$dateFilter." AND `fact`.`type`='1' GROUP BY `fact`.`id`"; //echo $query; //most letrehozunk egy id alapu comanda listat $resultFinalComandaList=mysql_query($query); while($commandFinalRow=mysql_fetch_array($resultFinalComandaList)) { //megvan a szamla lista amit at kell konvertaljunk comanda id listaba $comandaIdSplit = split(",",$commandFinalRow["fromActAdvId"]); foreach($comandaIdSplit as $value) { $finalSelectedId=$value; $finalComandaList.=" || `f`.`id`='$finalSelectedId'"; } } $finalComandaList.=")"; $query="SELECT `f`.* FROM `comandaForClientAdv` f WHERE ".$finalComandaList."ORDER BY `f`.$orderby $ordermode LIMIT $from, $count"; return $query; } else return NULL; } // Kigeneralja a lekerdezest egy megrendelesre a szamla utan egy csomo mindeent figyelembe veve function commandForClientAdv_searchComandaFromFactura( $factid ) { $query = "SELECT `f`.*, `fact`.`id` as facturaId FROM `comandaForClientAdv` f, `facturi` fact WHERE `fact`.`fromActAdvId` = `f`.`id` AND `fact`.`id`='$factid' "; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; $row = mysql_fetch_array( $result ); return $row; } function commandForClientAdv_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } // Lefuttatja a lekerdezest, amit a commandForClientAdv_searchGenerateQuery() fuggveny generalt (TODO) function commandForClientAdv_searchFactura( $query ) { $result = mysql_query( $query ) or die($query." ".mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } //negotiated prices function stock_getNegotiatedPrices( $clientid, $itemId ) { $query = "SELECT * FROM `negotiatedPrice` WHERE `clientid` = '$clientid' AND `priceId` = '$itemId'"; $result = mysql_query( $query ) or die(mysql_error()); if($result) { $row = mysql_fetch_array( $result ); return $row; } else { return NULL; } } function stock_modNegotiatedPrice( $clientid, $itemId , $price, $rate , $finalClientPrice) { $query = "UPDATE `negotiatedPrice` SET `newPrice` = '$price', `newRate` = '$rate', `newFinalClientPrice` = '$finalClientPrice' WHERE `clientid` = '$clientid' AND `priceId` = '$itemId'"; $result = mysql_query( $query ) or die(mysql_error()); if($result) return 1; else return 0; } function stock_insertNegotiatedPrice( $clientid, $itemId , $price, $rate, $finalClientPrice ) { $query = "INSERT INTO `negotiatedPrice` VALUES (NULL ,'$clientid','$itemId','$price','$rate','$finalClientPrice')"; $result = mysql_query( $query ) or die(mysql_error()); if($result) return 1; else return 0; } function dateDifference($startDate, $endDate) { $startDate = strtotime($startDate); $endDate = strtotime($endDate); if ($startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 || $startDate > $endDate) return false; $years = date('Y', $endDate) - date('Y', $startDate); $endMonth = date('m', $endDate); $startMonth = date('m', $startDate); // Calculate months $months = $endMonth - $startMonth; if ($months <= 0) { $months += 12; $years--; } if ($years < 0) return false; // Calculate the days $offsets = array(); if ($years > 0) $offsets[] = $years . (($years == 1) ? ' year' : ' years'); if ($months > 0) $offsets[] = $months . (($months == 1) ? ' month' : ' months'); $offsets = count($offsets) > 0 ? '+' . implode(' ', $offsets) : 'now'; $days = $endDate - strtotime($offsets, $startDate); $days = date('z', $days); return array($years, $months, $days); } function completeTemplateAdv($templateId,$documentSeries,$documentNumber,$addressHC,$countyHC,$addressPlHC,$countyPlHC,$cifHC,$registruHC,$bankHC,$ibanHC,$telfaxHC,$emailHC,$webHC,$nameC,$addessC,$countyC,$cifC,$registruC,$bankC,$ibanC,$invoiceDate,$lastDate,$elementsList,$invoiceWithoutTVA,$invoiceonlyTVA,$invoiceTotalSum,$rootFolder,$codDeValidare,$deLaStoc,$mergeLaStoc,$contraValoarea,$intocmitDe,$modDePlata,$data,$nravizmarfii,$dataex,$telfaxCumparator,$emailCumparator,$webCumparator,$capitalSocial,$adica,$cursValutar,$shipperinfo,$directDelivery,$dangerous,$truckerinfo,$truckerPartnerInfo,$truckerAmount,$loadingPlace,$loadingDate,$dischargePlace,$dischargeDate,$addFacturaClient,$facturaAmount,$facturaAmountCurrency,$comments,$otherinfo,$kmplini,$kmgol,$pretplini,$pretgol,$plinitotal,$goltotal,$kmprettotal,$tipcamion,$adr,$driversName,$driversTel,$profit,$dataExecutiei,$mawb,$hawb,$reprezentant='') { $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); // berakni az $adica valtozot a declarational... // 34 elements on function declaration $loadedTemplate = loadTemplate($templateId); //changing the images for real text $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/seria_documentului.jpg",$documentSeries); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_sediu.jpg",$addressHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_sediu.jpg",$countyHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_punct_de_lucru.jpg",$countyPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/CIF.jpg",$cifHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/Registru.jpg",$registruHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/banca.jpg",$bankHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/cod_iban.jpg",$ibanHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/tel_fax.jpg",$telfaxHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/email.jpg",$emailHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/web.jpg",$webHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cumparator.jpg",$nameC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/adresa_cumparator.jpg",$addessC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/judet_cumparator.jpg",$countyC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cif_cumparator.jpg",$cifC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/registru_cumparator.jpg",$registruC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/banca_cumparator.jpg",$bankC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/iban_cumparator.jpg",$ibanC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/termen_de_plata.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/termen_de_plata.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataExecutiei); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"lista_elemente.jpg",$elementsList); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/fara_TVA.jpg",$invoiceWithoutTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/din_care_TVA.jpg",$invoiceonlyTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/cod_de_validare.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/de_la_stoc.jpg",$deLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/merge_la_stoc.jpg",$mergeLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/contravaloarea.jpg",$contraValoarea); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/mod_de_plata.jpg",$modDePlata); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/curs_de_schimb.jpg",$cursValutar); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"aviz/cod_generat.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/adica.jpg",$adica); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_aviz_a_marfii.jpg",$nravizmarfii); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/telfax_cumparator.jpg",$telfaxCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/email_cumparator.jpg",$emailCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/web_cumparator.jpg",$webCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/capital_social.jpg",$capitalSocial); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/seria_documentului.jpg",$documentSeries); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_sediu.jpg",$addressHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_sediu.jpg",$countyHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_punct_de_lucru.jpg",$countyPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/CIF.jpg",$cifHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/Registru.jpg",$registruHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/banca.jpg",$bankHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/cod_iban.jpg",$ibanHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/tel_fax.jpg",$telfaxHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/email.jpg",$emailHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/web.jpg",$webHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cumparator.jpg",$nameC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/adresa_cumparator.jpg",$addessC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/judet_cumparator.jpg",$countyC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cif_cumparator.jpg",$cifC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/registru_cumparator.jpg",$registruC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/banca_cumparator.jpg",$bankC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/iban_cumparator.jpg",$ibanC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/termen_de_plata.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataExecutiei); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"lista_elemente.jpg",$elementsList); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/fara_TVA.jpg",$invoiceWithoutTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/din_care_TVA.jpg",$invoiceonlyTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/cod_de_validare.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/de_la_stoc.jpg",$deLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/merge_la_stoc.jpg",$mergeLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/contravaloarea.jpg",$contraValoarea); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/mod_de_plata.jpg",$modDePlata); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/curs_de_schimb.jpg",$cursValutar); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"aviz/cod_generat.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/adica.jpg",$adica); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_aviz_a_marfii.jpg",$nravizmarfii); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/telfax_cumparator.jpg",$telfaxCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/email_cumparator.jpg",$emailCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/web_cumparator.jpg",$webCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/capital_social.jpg",$capitalSocial); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/shipper.jpg",$shipperinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/delivery.jpg",$directDelivery); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dangerous.jpg",$dangerous); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/trucker.jpg",$truckerinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/truckerinfo.jpg",$truckerPartnerInfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/truckeramount.jpg",$truckerAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingplace.jpg",$loadingPlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingdate.jpg",$loadingDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargeplace.jpg",$dischargePlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargedate.jpg",$dischargeDate); if($durata=="") { $durata1=dateDifference($loadingDate,$dischargeDate); if($durata1[0]!=""&&$durata1[0]!=0) $durata.=$durata1[0].($durata1[0]=="1"?" an":" ani "); if($durata1[1]!=""&&$durata1[1]!=0) $durata.=$durata1[1].($durata1[1]=="1"?" luna":" luni "); } $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/durata.jpg",$durata); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaforclient.jpg",$addFacturaClient); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamount.jpg",$facturaAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamountcurrency.jpg",$facturaAmountCurrency); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamount.jpg",$facturaAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamountcurrency.jpg",$facturaAmountCurrency); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/otherinfo.jpg",$otherinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/profit.jpg",$profit); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/driverstel.jpg",$driversTel); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/driversname.jpg",$driversName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/adr.jpg",$adr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/mawb.jpg",$mawb); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/hawb.jpg",$hawb); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/kmplini.jpg",$kmplini); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/kmgol.jpg",$kmgol); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/pretplini.jpg",$pretplini); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/pretgol.jpg",$pretgol); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/plinitotal.jpg",$plinitotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/goltotal.jpg",$goltotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/total.jpg",$kmprettotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/tipcamion.jpg",$tipcamion); $loadedTemplate = loadTemplate($templateId); //changing the images for real text $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/reprezentant.jpg",$reprezentant); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/seria_documentului.jpg",$documentSeries); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_sediu.jpg",$addressHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_sediu.jpg",$countyHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_punct_de_lucru.jpg",$countyPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/CIF.jpg",$cifHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/Registru.jpg",$registruHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/banca.jpg",$bankHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/cod_iban.jpg",$ibanHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/tel_fax.jpg",$telfaxHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/email.jpg",$emailHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/web.jpg",$webHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cumparator.jpg",$nameC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/adresa_cumparator.jpg",$addessC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/judet_cumparator.jpg",$countyC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cif_cumparator.jpg",$cifC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/registru_cumparator.jpg",$registruC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/banca_cumparator.jpg",$bankC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/iban_cumparator.jpg",$ibanC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/termen_de_plata.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/termen_de_plata.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataExecutiei); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"lista_elemente.jpg",$elementsList); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/fara_TVA.jpg",$invoiceWithoutTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/din_care_TVA.jpg",$invoiceonlyTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/cod_de_validare.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/de_la_stoc.jpg",$deLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/merge_la_stoc.jpg",$mergeLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/contravaloarea.jpg",$contraValoarea); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/mod_de_plata.jpg",$modDePlata); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/curs_de_schimb.jpg",$cursValutar); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"aviz/cod_generat.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/adica.jpg",$adica); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_aviz_a_marfii.jpg",$nravizmarfii); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/telfax_cumparator.jpg",$telfaxCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/email_cumparator.jpg",$emailCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/web_cumparator.jpg",$webCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/capital_social.jpg",$capitalSocial); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/seria_documentului.jpg",$documentSeries); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_documentului.jpg",$documentNumber); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_sediu.jpg",$addressHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_sediu.jpg",$countyHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/adresa_punct_de_lucru.jpg",$addressPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/judet_punct_de_lucru.jpg",$countyPlHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/CIF.jpg",$cifHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/Registru.jpg",$registruHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/banca.jpg",$bankHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/cod_iban.jpg",$ibanHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/tel_fax.jpg",$telfaxHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/email.jpg",$emailHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"date_firma/web.jpg",$webHC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cumparator.jpg",$nameC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/adresa_cumparator.jpg",$addessC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/judet_cumparator.jpg",$countyC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cif_cumparator.jpg",$cifC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/registru_cumparator.jpg",$registruC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/banca_cumparator.jpg",$bankC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/iban_cumparator.jpg",$ibanC); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_facturarii.jpg",$invoiceDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/termen_de_plata.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataExecutiei); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"lista_elemente.jpg",$elementsList); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/fara_TVA.jpg",$invoiceWithoutTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/din_care_TVA.jpg",$invoiceonlyTVA); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/cu_TVA.jpg",$invoiceTotalSum); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/cod_de_validare.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/de_la_stoc.jpg",$deLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"bon_de_comanda/merge_la_stoc.jpg",$mergeLaStoc); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/contravaloarea.jpg",$contraValoarea); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/intocmit_de.jpg",$intocmitDe); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/mod_de_plata.jpg",$modDePlata); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/curs_de_schimb.jpg",$cursValutar); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"data.jpg",$data); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"aviz/cod_generat.jpg",$codDeValidare); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"chitanta/adica.jpg",$adica); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/nr_aviz_a_marfii.jpg",$nravizmarfii); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/data_executiei.jpg",$dataex); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/telfax_cumparator.jpg",$telfaxCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/email_cumparator.jpg",$emailCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/web_cumparator.jpg",$webCumparator); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"factura/capital_social.jpg",$capitalSocial); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/shipper.jpg",$shipperinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/delivery.jpg",$directDelivery); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dangerous.jpg",$dangerous); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/trucker.jpg",$truckerinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/truckerinfo.jpg",$truckerPartnerInfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/truckeramount.jpg",$truckerAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingplace.jpg",$loadingPlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/loadingdate.jpg",$loadingDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargeplace.jpg",$dischargePlace); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/dischargedate.jpg",$dischargeDate); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaforclient.jpg",$addFacturaClient); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamount.jpg",$facturaAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamountcurrency.jpg",$facturaAmountCurrency); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamount.jpg",$facturaAmount); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturaamountcurrency.jpg",$facturaAmountCurrency); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/facturacomments.jpg",$comments); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/otherinfo.jpg",$otherinfo); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/profit.jpg",$profit); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/driverstel.jpg",$driversTel); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/driversname.jpg",$driversName); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/adr.jpg",$adr); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/mawb.jpg",$mawb); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForClient/hawb.jpg",$hawb); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/kmplini.jpg",$kmplini); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/kmgol.jpg",$kmgol); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/pretplini.jpg",$pretplini); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/pretgol.jpg",$pretgol); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/plinitotal.jpg",$plinitotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/goltotal.jpg",$goltotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/total.jpg",$kmprettotal); $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"commandForPartner/tipcamion.jpg",$tipcamion); if($durata=="") { $durata1=dateDifference($loadingDate,$dischargeDate); if($durata1[0]!=""&&$durata1[0]!=0) $durata.=$durata1[0].($durata1[0]=="1"?" an":" ani "); if($durata1[1]!=""&&$durata1[1]!=0) $durata.=$durata1[1].($durata1[1]=="1"?" luna":" luni "); } $loadedTemplate = imageReplaceToText($rootFolder,$loadedTemplate,"proiectManagement/durata.jpg",$durata); return $loadedTemplate; } function factura_getFacturaGeneratedCount( $fromActId ) { $select = "SELECT COUNT(*) AS counting FROM `facturi` WHERE (`fromActAdvId`='$fromActId' || `fromActAdvId` LIKE '% $fromActId,%') AND `active` = '1' AND `type`='1';"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $result ); return $row["counting"]; } function factura_getComandaGeneratedCount( $fromActId ) { $select = "SELECT COUNT(*) AS counting FROM `comandaForClientAdv` WHERE (`numberSerial`='$fromActId') AND `active` = '1' AND `firstserial`='0';"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $result ); return $row["counting"]; } function factura_getFacturaItemsLastDate( $fromActId , $elementId) { $select = "SELECT fi.*, f.ondate FROM `facturi` f, `facturi_items` fi WHERE (f.`fromActAdvId`='$fromActId' || `fromActAdvId` LIKE '% $fromActId,%') AND f.`id` = fi.`factid` AND fi.`modelid` = '$elementId' AND f.`active` = '1' AND f.`type`='1' ORDER BY `endDate` DESC;"; //echo $select; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while($row = mysql_fetch_array( $result )) { if(factura_getStornedFactura($row["factid"])==NULL) return $row; } } function factura_getFacturaItemsLastDateCalculare( $fromActId , $elementId) { $select = "SELECT fi.*, f.ondate FROM `facturi` f, `facturi_items` fi WHERE (f.`fromActAdvId`='$fromActId' || `fromActAdvId` LIKE '% $fromActId,%') AND f.`id` = fi.`factid` AND fi.`modelid` = '$elementId' AND f.`active` = '1' AND f.`type`='1' ORDER BY `endDate` DESC;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_num_rows($result) <= 0 ) return NULL; $row = mysql_fetch_array( $result ); return $row; } function getCommandForPartnerAdvRegisteredItems ($commandId) { $query = "SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid` = '$commandId' AND `sellType`!='necesar' order by id ASC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerAdvRegisteredItemsNecesar ($commandId) { $query = "SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid` = '$commandId' AND `sellType`='necesar' order by id ASC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerAdvRegisteredItemsForMassiveFacture ($commandId) { $query = "SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid` = '$commandId' AND `sellType`!='necesar' AND `facturat`='0' order by stockid, prodid ASC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerAdvRegisteredItemsForAvertizare ($commandId) { $query = "SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid` = '$commandId' AND `sellType`!='necesar' AND `facturat`='0' order by id ASC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerAdvRegisteredItemsCount ($commandId) { $query = "SELECT * FROM comandaForClientAdvItems WHERE `comandaid` = '$commandId' AND `sellType`!='necesar';"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function getCommandForPartnerAdvRegisteredItemsCountForAvertizare ($commandId) { $query = "SELECT * FROM comandaForClientAdvItems WHERE `comandaid` = '$commandId' AND `facturat`='0' AND `sellType`!='necesar';"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function getCommandForPartnerAdvRegisteredItemsCountone ($commandId) { $query = "SELECT * FROM `comandaForClientAdvItems` WHERE id = '$commandId' AND `sellType`!='necesar'; "; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $result ) ; return $row; } function getCommandForPartnerAdvPartnerRegisteredItems ($commandId) { $query = "SELECT * FROM comandaForPartnerItems WHERE comandaid = $commandId order by id ASC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandForPartnerAdvPartnerRegisteredItemsCount ($commandId) { $query = "SELECT * FROM comandaForPartnerItems WHERE comandaid = $commandId"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function getCommandForPartnerAdvPartnerRegisteredItemsCountone ($commandId) { $query = "SELECT * FROM `comandaForPartnerItems` WHERE id = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $result ) ; return $row; } function getFreqvencyText($freqvencyRate) { if($freqvencyRate=="unic") return "zi"; if($freqvencyRate=="lunar") return "luna"; if($freqvencyRate=="saptamanal") return "saptamana"; if($freqvencyRate=="zilnic") return "zi"; if($freqvencyRate=="ora") return "ora"; } function getFreqvencyRate($freqvencyRate) { if($freqvencyRate=="unic") return 1; if($freqvencyRate=="lunar") return 30; if($freqvencyRate=="saptamanal") return 7; if($freqvencyRate=="zilnic") return 1; } function avizOut_delete( $avizId ) { $query = "DELETE FROM `avizeOut` WHERE `id`='$avizId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function avizOut_rollbackSerialNumber( $avizId ) { $aviz = avizOut_getAviz( $avizId ); $serial = $aviz["serial"]; $serialNumber = $aviz["number"]; $lockQ = "LOCK TABLES `serials` WRITE"; $result = mysql_query( $lockQ ); $selectQ = "SELECT * FROM `serials` WHERE `serial`='$serial' LIMIT 1;"; $result = mysql_query( $selectQ ) or die(mysql_error()); $row = mysql_fetch_array( $result ); $lastSerialNumber = $row["current"]; if( $lastSerialNumber == $serialNumber + 1 ) { $updateQ = "UPDATE `serials` SET `current` = '$serialNumber' WHERE `serial`='$serial' LIMIT 1"; mysql_query( $updateQ ) or die(mysql_error()); } $unlockQ = "UNLOCK TABLES;"; mysql_query( $unlockQ ); } function avizOut_addAviz( $clientid , $userid , $stockid , $rawvalue , $value , $serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei, $onValuta , $cursValue, $commandId, $fromActAdvId) { $content = addslashes ($content); $insertQ = "INSERT INTO `avizeOut` ( `id` , `clientid` , `userid` , `stockid` , `rawvalue` , `value` , `serial`,`number`,`content` , `printed` , `closed` ,`ondate`,`active`,`paymode`, `termenDePlata`, `dataExecutiei`, `onValuta` , `cursValue` , `fromActId` , `fromActAdvId`) VALUES ( NULL , '$clientid', '$userid', '$stockid', '$rawvalue', '$value', '$serial','$number','$content', '0', '0',NOW(),'1','$paymode' , '$termenDePlata', '$dataExecutiei' , '$onValuta' , '$cursValue' , '$commandId', '$fromActAdvId'); "; mysql_query( $insertQ ) or die(mysql_error()); $avizid = mysql_insert_id (); return $avizid; } function avizOut_registerItems( $factid , $modelid , $price , $natprice , $quantity , $type, $rowName , $inchiriere , $stock_item ) { $query = "INSERT INTO `avizeOutItems` VALUES (NULL, '$factid', '$modelid', '$price', '$natprice' , '$quantity', '$type' , '$rowName', NOW(),'$stock_item', '$inchiriere');"; mysql_query( $query ) or die(mysql_error()); } function avizOut_setActiveNess( $factid , $state ) { $update = "UPDATE `avizeOut` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function avizOut_modAviz( $id , $clientid , $userid , $stockid , $rawvalue , $value ,$serial , $number, $content , $paymode , $termenDePlata, $dataExecutiei , $onValuta , $cursValue) { if($termenDePlata==NULL) $termenDePlata="0000-00-00"; if($dataExecutiei==NULL) $dataExecutiei="0000-00-00"; $content = addslashes ($content); $updateQ = "UPDATE `avizeOut` SET `clientid` = '$clientid', `userid` = '$userid', `stockid` = '$stockid', `rawvalue` = '$rawvalue', `value` = '$value', `serial` = '$serial', `number` = '$number', `paymode` = '$paymode', `termenDePlata` = '$termenDePlata', `dataExecutiei` = '$dataExecutiei', `onValuta` = '$onValuta', `cursValue` = '$cursValue', `content` = '$content' WHERE `avizeOut`.id ='$id' LIMIT 1;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function avizOut_setPrinted( $id , $value ) { $updateQ = "UPDATE `avizeOut` SET `printed` = '$value' WHERE `avizeOut`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function avizOut_setClosed( $id , $value ) { $updateQ = "UPDATE `avizeOut` SET `closed` = '$value' WHERE `avizeOut`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function avizOut_setRemovedFromStock( $id , $value ) { $updateQ = "UPDATE `avizeOut` SET `removedFromStock` = '$value' WHERE `avizeOut`.`id` =$id LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function avizOut_setSerial( $id , $serial ) { $update = "UPDATE `avizeOut` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function avizOut_getAvize() { $select = "SELECT * FROM `avizeOut`"; $result = mysql_query( $select ); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function avizOut_getAviz( $id ) { $select = "SELECT * FROM `avizeOut` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function avizOut_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial" && $searchval!=NULL) $query = "SELECT `f`.*, `p`.`name` FROM `avizeOut` f, `partners` p WHERE `f`.`number` = '$searchval' AND `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; else $query = "SELECT `f`.*, `p`.`name` FROM `avizeOut` f, `partners` p WHERE `p`.`name` LIKE '%$searchval%' AND `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ".$filterMenuSql." ORDER BY $orderby $ordermode LIMIT $from, $count"; return $query; } function avizOut_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function avizOut_searchAviz( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function avizOut_getLatestAvizItems () { $query = "SELECT f1.rowName AS rowName, f1.modelid as modelid, f1.type AS type, f1.id AS id, p.name AS clientname, p.id as clientid, m.name AS modelname, f2.ondate AS ondate, f1.price as price, f2.id as factid FROM avizeOutItems f1, avizeOut f2, models m, partners p, services s WHERE f2.clientid = p.id AND f1.factid = f2.id ORDER BY f2.ondate DESC LIMIT 0, 5"; $result = mysql_query( $query ) or die(mysql_error()); while ($row = mysql_fetch_array ($result)) $list [$row ["id"]] = $row; return $list; } function generateDataFromAvizOut( $id ) { $select = "SELECT * FROM `avizeOut` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function getAvizOutRegisteredItems ($commandId) { $query = "SELECT * FROM `avizeOutItems` WHERE factid = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getAvizOutRegisteredItemsCount ($commandId) { $query = "SELECT * FROM `avizeOutItems` WHERE `factid` = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function aviz_getAvizGeneratedCount( $fromActId ) { $select = "SELECT COUNT(*) AS counting FROM `avizeOut` WHERE `fromActAdvId`='$fromActId' AND `active` = '1';"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $result ); return $row["counting"]; } function aviz_getAvizGenerated( $fromActId ) { $select = "SELECT * FROM `avizeOut` WHERE `fromActAdvId`='$fromActId' AND `active` = '1';"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $result ); return $row; } ////////////////////// Weboldal fuggvenyek //////////////// /////////////////////////// Tagfelho ///////////////////////// // Kiveszem az osszes taget es feldolgozom// // Ha a $cluod valtozonak 1-et kuldok, a $tagnak a "notag"-attributumot // kell bekuldjem (ezt a tagfelho megjelenitesehez hasznalom) // Ha a $cloud valtozonak "nocloud" erteket adok, akkor a $tag-be az adott tag // frissen generalt id-jat kell bekuldjem es a fuggveny az adott taghez tartozo // linkeket listazza ki function getAllTags () { // minden taget kiszedek $query='SELECT * FROM `keywords`'; $lekerdezes=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($lekerdezes)) { $result1[$listAll["id"]]=$listAll; } // berakom egy stringbe foreach($result1 as $temp=>$linkek) { $nyers.=" ".$linkek['keywords']; } // szetdarabolom $darabonkent=explode(" ", $nyers); // meagdom az alapertekeket a rendezendo listaban $indexLista[0]=$darabonkent[0]; // beallitok egy szamlalot $indexCount[0]=1; // szetszedem a tombot, ugy, hogy figyelem, melyik szo hanyszor van benne for ($i=1; $i<=count($darabonkent); $i++) { if (in_array($darabonkent[$i], $indexLista)) { // novelem a megfelelo szamlalot, ha mar benne van a listaban $indexCount[array_search($darabonkent[$i], $indexLista)]++; } else { // ha nincs benne a listaban, hozzaadom $indexLista[(count($indexLista))+1]=$darabonkent[$i]; // beallitom a hozza tartozo szamlalot $indexCount[(count($indexLista))+1]=1; } } // ha a fuggveny igy van meghivva, akkor azt a cimkefelhoben hasznalom for ($i=0; $i<40; $i++) { // generalok egy szamot aszerint, hogy hany elem van a listaban $rand=mt_rand(0,count($indexLista)); // megadom a cimke meretet, aszerint, hogy mennyire gyakori $meret=$indexCount[$rand]; // ha kevesebb, mint nyolcszor fordul elo, akkor generalok neki egy // meretet if ($meret<=8) $meret=mt_rand(10,16); // ha tobb mint 18X jelenik meg, akkor 18-as meretre allitom if ($meret>18) $meret=16; // kirakom a taget es linket csinalok belole, ami a tag sorszamat // tartalmazza echo ' '.$indexLista[$rand].''; echo " "; } } //////////////////////////// Tagfelho vege ////////////////// //////////////// JavaScripthez talalomra ///////////////////////// function getallPromoProduct() { $modellek=model_getModels(1,1); $darabszam=sizeof($modellek); $i=0; foreach ($modellek as $temp=>$szetszedve) { // Kiszedi az akcios termekeket, ha vannak $ertek=getForFlashRandomly($szetszedve['id']); // Ellenorzi, hogy minden rendben van-e (van-e fokep, van-e minden ertek // az adott termekhez) if ($ertek!=0) { $modeltoimagine[$i]=$ertek; $i++; } } return $modeltoimagine; } function returnFlashElement () { // ha a fooldalon vagyunk, akkor barmelyik modelbol barmilyen termeket visszaadhat $lista=getForFlashRandomly(); return $lista; } // Kiszedi a fomodellek neveit function getModelName ($modelid) { $query="SELECT * FROM `models` WHERE `id`=".$modelid; $lekerdezes=mysql_query( $query ) or die(mysql_error()); $listAll=mysql_fetch_array($lekerdezes); return $listAll['name']; } // futtasd le a http://www.deltaterm.ro/forFlash.php-t es ott meglatod, hogy mit terit vissza a fuggveny. // Remelem, jo! function getForFlashRandomly ($modelid) { if ($modelid) { $query="SELECT * FROM `container` WHERE image!='NULL' AND `pret_promo`!=0 AND `modelid`=".$modelid; $lekerdezes=mysql_query( $query ) or die(mysql_error()); $i=1; while ($listAll=mysql_fetch_array($lekerdezes)) { $result[$i]=$listAll; $i++; } if (!$result) { return 0; } $maxRandom=$i-1; $randomized=mt_rand(1,$maxRandom); $imageid=$result[$randomized]['image']; $query="SELECT * FROM `container_images` WHERE `id`='$imageid'"; $lekerdezes=mysql_query( $query ) or die(mysql_error()); $imageResult=mysql_fetch_array($lekerdezes); $result[$randomized]['path']=$imageResult["path"]; return $result[$randomized]; } else { return 0; } } ////////////////////////////////////////////////////////////////// ///plusz van // Kiszedi a weboldalhoz szukseges szoveges statikus tartalmat szerkesztesre // Session id es webadmin tipus szerint function getSContent ($showform, $subform,$lang) { $query='SELECT * from '.$showform.' WHERE id='.$subform; $result=mysql_query( $query ) or die(mysql_error()); $rol = mysql_fetch_array($result); return $rol['tartalom_'.$lang]; } // Visszirjuk a modositott tartalmat // Session id es webadmin tipus szerint function writeSContent($showform, $FCKeditor1, $subform, $titlu,$lang) { $query='UPDATE ' .$showform. ' SET tartalom_'.$lang.'="'.$FCKeditor1.'" where id='.$subform; $mycucc=mysql_query( $query ) or die(mysql_error()); // Ha hireket szerkesztunk, akko cimet is kell menteni if ($showform=="stiri") { $query1='UPDATE ' .$showform. ' SET cim_'.$lang.'="'.$titlu.'" where id='.$subform; $mycucc=mysql_query($query1) or die(mysql_error()); } if ($showform=="oportunitati" || $showform=="opinion") { $query1='UPDATE ' .$showform. ' SET name_'.$lang.'="'.$titlu.'" where id='.$subform; $mycucc=mysql_query($query1) or die(mysql_error()); } if ($showform=="cuvinte_cheie" ) { $query1='UPDATE ' .$showform. ' SET cim_'.$lang.'="'.$titlu.'" where id='.$subform; $mycucc=mysql_query($query1) or die(mysql_error()); } } //a termekek lekerdezese egy kivalasztott tulajdonsag alapjan function entry_getConEntriesBycssid ($categoriid, $modelid) { $query = "SELECT * FROM `container` WHERE `modelid`='$modelid' AND (`cs1`='$categoriid' OR `cs2`='$categoriid' OR `cs3`='$categoriid' OR `cs4`='$categoriid' OR `cs5`='$categoriid' OR `cs6`='$categoriid' OR `cs7`='$categoriid' OR `cs8`='$categoriid' OR `cs9`='$categoriid' OR `cs10`='$categoriid' OR `cs11`='$categoriid' OR `cs12`='$categoriid' OR `cs13`='$categoriid' OR `cs14`='$categoriid' OR `cs15`='$categoriid' OR `cs16`='$categoriid' OR`cs17`='$categoriid' OR `cs18`='$categoriid' OR `cs19`='$categoriid' OR `cs20`='$categoriid')"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $entries[ $row["id"] ] = $row; return $entries; } else return NULL; } function entry_getConEntriesBycssid2 ($categoriid, $modelid) { if ($categoriid) { $query = "SELECT * FROM `container` WHERE `modelid`='$modelid' AND (`cs1`='$categoriid' OR `cs2`='$categoriid' OR `cs3`='$categoriid' OR `cs4`='$categoriid' OR `cs5`='$categoriid' OR `cs6`='$categoriid' OR `cs7`='$categoriid' OR `cs8`='$categoriid' OR `cs9`='$categoriid' OR `cs10`='$categoriid' OR `cs11`='$categoriid' OR `cs12`='$categoriid' OR `cs13`='$categoriid' OR `cs14`='$categoriid' OR `cs15`='$categoriid' OR `cs16`='$categoriid' OR`cs17`='$categoriid' OR `cs18`='$categoriid' OR `cs19`='$categoriid' OR `cs20`='$categoriid') AND `active`='1'"; } else { $query = "SELECT * FROM `container` WHERE `modelid`='$modelid' AND `active`='1'"; } $result = mysql_query( $query ) or die(mysql_error()); return $result; } ////////////////////// Paragrafuskezeles /////////////////////// // szoveg feldarabolasa paragrafusok szerint function format_splitText( $text ) { //szinezes // $destinationId=$this->destinationId; // $text = $this->putColorAndFormat($text,$destinationId); // //szinezes vege $partsIndex = 0; $pos_first = strpos($text, "^"); $pos_last = strpos($text, "^*"); $variable = $pos_last-$pos_first; $intro = substr( $text , $pos_first+1 , $variable-2 ); $parts[ 0 ] = $intro; $content = substr( $text , $pos_last + 2 ); for(;;) { $partsIndex ++; $pStart = false; $pEnd = false; $pStart = strpos( $content , "^"); $pEnd = strpos( $content , "^*"); if( $pStart == false || $pEnd == false )break; $length = $pEnd - $pStart; $paragraph = substr( $content , $pStart +1, $length - 2 ); $parts[ $partsIndex ] = $paragraph; $content = substr( $content , $pEnd + 2); } return $parts; } function format_splitTextWithoutColors( $text ) { //szinezes $destinationId=$this->destinationId; //szinezes vege $partsIndex = 0; $pos_first = strpos($text, "^"); $pos_last = strpos($text, "^*"); $variable = $pos_last-$pos_first; $intro = substr( $text , $pos_first+1 , $variable-2 ); $parts[ 0 ] = $intro; $content = substr( $text , $pos_last + 2 ); for(;;) { $partsIndex ++; $pStart = false; $pEnd = false; $pStart = strpos( $content , "^"); $pEnd = strpos( $content , "^*"); if( $pStart == false || $pEnd == false )break; $length = $pEnd - $pStart; $paragraph = substr( $content , $pStart +1, $length - 2 ); $parts[ $partsIndex ] = $paragraph; $content = substr( $content , $pEnd + 2); } return $parts; } // szovegben levo szavak kiemelese function putColorAndFormat($text,$destinationId) { $formatStart = ''; $formatEnd = ''; $key = array("2" ); $totalKeys = count($key); for($i=0;$i<$totalKeys;$i++) { $text = str_replace($key[$i]." ",$formatStart.$key[$i]." ".$formatEnd,$text); $text = str_replace($key[$i]."
",$formatStart.$key[$i]."
".$formatEnd,$text); $text = str_replace($key[$i].",",$formatStart.$key[$i].",".$formatEnd,$text); } return $text; } ///////////////////// Hirek fuggvenyei /////////////////// // Kiolvasom az osszes hirt (menedzsment) // Effektiv eredmenyt terit vissza function getAllStiri() { $query="SELECT * from stiri ORDER BY datum DESC"; $all=mysql_query( $query ) or die(mysql_error()); return $all; } // Kiolvasom az osszes hirt (weboldal) // Effektiv eredmenyt terit vissza function getAllStiriActive() { $query="SELECT * from stiri WHERE active=1 ORDER BY datum DESC"; $all=mysql_query( $query ) or die(mysql_error()); return $all; } // A letezo hirek kilistazasa // Feldolgozott eredmenyt terit vissza function listStiri() { $query="SELECT * from stiri ORDER BY datum DESC"; $all=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($all)) { $result[$listAll["id"]]=$listAll; } return $result; } function listStirimasodik($id) { $query="SELECT * from stiri WHERE `id`!='$id' ORDER BY datum DESC"; $all=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($all)) { $result[$listAll["id"]]=$listAll; } return $result; } // A letezo hirek kilistazasa lapozassal (menedzsment rendszer) // Feldolgozott eredmenyt terit vissza function listStiri2($order,$limit) { $query="SELECT * from stiri ORDER BY datum DESC LIMIT ".$order.",".$limit; $all=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($all)) { $result[$listAll["id"]]=$listAll; } return $result; } // A letezo hirek kilistazasa lapozassal (weboldal) // Feldolgozott eredmenyt terit vissza function listStiri3($order,$limit) { $query="SELECT * from stiri WHERE active=1 ORDER BY datum DESC LIMIT ".$order.",".$limit; $all=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($all)) { $result[$listAll["id"]]=$listAll; } return $result; } // Kiolvasom a hir cimet function getTitle($showform, $subform) { $query='SELECT * FROM '.$showform.' WHERE id='.$subform; $tartalom=mysql_query( $query ) or die(mysql_error()); $res= mysql_fetch_array($tartalom); return $res["cim"]; } // A hir aktvivva tetele function setStiriActive($showform, $aktualis) { $query='UPDATE `'.$showform.'` SET `active` = \'1\' WHERE `id` =\''.$aktualis.'\''; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } // A hir inaktvivva tetele function setStiriInactive($showform, $aktualis) { $query='UPDATE '.$showform.' SET `active` = 0 WHERE `id` =\''.$aktualis.'\''; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } // A hir torlese function stergeStiri($showform, $subform) { $query='DELETE FROM '. $showform.' WHERE id=\''.$subform.'\''; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } // Uj hir hozzaadasa az adatbazishoz //plusz van function addNewNews($FCKeditor1, $titlu,$lang) { $query='INSERT INTO stiri ( `id` , `cim_'.$lang.'` , `tartalom_'.$lang.'` , `datum` , `active` ) VALUES ( NULL , "'.$titlu.'", "'.$FCKeditor1.'", NOW( ) , "0" );'; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } ///////////////// Fajlfeltoltes //////////////////////// function fileUpload($uploaded_file, $prodid) { // Ellenorizzuk, hogy van-e fajl if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { // Ellenorizzuk, hogy az .jpg vagy .png kiterjesztesu-e es hogy kisebb 500kb-nal $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (((($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg")) || (($ext == "JPG") && ($_FILES["uploaded_file"]["type"] == "image/jpeg")) || (($ext == "Jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg")) || (($ext == "png") && ($_FILES["uploaded_file"]["type"] == "image/png")) || (($ext == "Png") && ($_FILES["uploaded_file"]["type"] == "image/png")) || (($ext == "PNG") && ($_FILES["uploaded_file"]["type"] == "image/png"))) && ($_FILES["uploaded_file"]["size"] < 1000000)) { // Hova kell feltoltsuk + generalunk egy nevet neki a tempfile alapjan es hozzafuzzuk a kiterjesztest $newname = dirname(__FILE__).'/images/uploaded/'.$kapott=str_ireplace("/","_",$_FILES['uploaded_file']['tmp_name']).".".$ext; // Ellenorizzuk, hogy letezik-e mar if (!file_exists($newname)) { // Ha nem letezik, felpakoljuk if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { fileToDB($kapott, $prodid); $mess= getTraducere("Fisierul a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=false; } else { $mess= getTraducere("Gresit! Fisierul nu prea a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=true; } } else { $mess= getTraducere("Greseala: Fisierul ",$_SESSION["settings"]["default_lang"]).$_FILES["uploaded_file"]["name"]." ".getTraducere("deja exista!",$_SESSION["settings"]["default_lang"]); $err=true; } } else { $mess= getTraducere("Greseala: Numai .jpg si .png sub 1000kb poate fi uploadat!!!",$_SESSION["settings"]["default_lang"]); $err=true; } } else { $mess= getTraducere("Greseala: Fisierul nu a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=true; } if(!$err) $MessageHelpDialog=$mess; else $errorMessageHelpDialog=$mess; include("global_helpDialog.php"); } // Fajl adatbazisregisztracioja function fileToDB($picname, $prodid) { $query='INSERT INTO container_images (`id`, `prodid`, `path`) VALUES (NULL, "'.$prodid.'", "'.$picname.'");'; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } // Az adott termekhez tartozo kepek kiolvasasa function fileFromDB($prodid) { $query="SELECT * FROM container_images WHERE prodid='$prodid'"; $lekerdezes=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($lekerdezes)) { $result[$listAll["id"]]=$listAll; } return $result; } // Alapkep beallitasa egy termekhez function fileToDef($picid, $prodid) { $query1="SELECT * FROM `container_images` WHERE id='$picid'"; $lekerdezes1=mysql_query($query1) or die(mysql_error()); while ($listAll=mysql_fetch_array($lekerdezes1)) { $result[$listAll["id"]]=$listAll; } foreach($result as $temp=>$imageiddef) { } $path="images/uploaded/".$imageiddef["path"]; $imagesizes=getimagesize($path); $query="UPDATE container SET image ='".$picid. "' WHERE id ='$prodid'"; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } function whichIsTheDefault($prodid) { $query="SELECT image FROM container WHERE id='$prodid'"; $lekerdezes=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($lekerdezes)) { $result[$listAll["id"]]=$listAll; } foreach($result as $temp=>$imageiddef) { if ($imageiddef['image']) { return $imageiddef['image']; } else { echo getTraducere("Nu ati selectat imaginea principala pentru acest produs sau nu ati uploadat nici o imagine!",$_SESSION["settings"]["default_lang"]); } } } // Fajl torlese (adatbazis + fizikai); function deleteFile($picid,$prodid) { $query="SELECT * FROM `container_images` WHERE `path`='".$picid."' AND `prodid`='$prodid';"; $lekerdezes=mysql_query($query) or die(mysql_error()); if($lekerdezes) { $adatok=mysql_fetch_array($lekerdezes); $filelista='images/uploaded/'.$picid; if(is_file($filelista)) { unlink($filelista); return true; } getPath($picid,$prodid); } return false; } // Kitorlom a kep informacioit az adatbazisbol function getPath($picid,$prodid) { $query2="DELETE FROM `container_images` WHERE `path` ='".$picid."' AND `prodid`='$prodid';"; $lekerdezes2=mysql_query($query2) or die(mysql_error()); } /////////////////////////regisztracio//////////////////////////////////////////////////////////////////////////////////////// //letezike az az user amikor akar regisztralni function getUserexist($str) { $query = "SELECT * FROM `users_website` WHERE username='$str' "; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return $result; } function getemailexist($str) { $query = "SELECT * FROM `partners` WHERE xemail='$str' "; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return $result; } function cuiDB($cui) { $query=('SELECT * FROM partners WHERE cui='.$cui); $lekerdezes=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($lekerdezes)) { $result[$listAll["id"]]=$listAll; } if ($result) { foreach($result as $temp=>$cuidef) { if ($cuidef['cui']) { return 1; } else return 0; } } else return 0; } // CUI ellenorzese (getCuiValidity.php) function getCuiExist($valtozo) { // Lefuttatom a sitetot es visszateritem a forraskodjat $argumentum='http://www.mfinante.ro/contribuabili/link.jsp?cod='.$valtozo.'&body=/cod.do'; $bar = file_get_contents($argumentum); // Ellenorzom, hogy mukodik-e a weboldal $siteworks="Ministerul Finantelor"; if (!($iplace = strstr($bar, $siteworks))) { $nemmegy='nemmegy'; return $nemmegy; } else { // Elenorzom, hogy a kovetkezo stringek benne vannak-e $inexsistent='Nu exista agent economic'; $iplace = strstr($bar, $inexsistent); $legatura='Legatura la baza de date este temporar'; $ilegat= strstr($bar, $legatura); // TODO a J szam kiszedese // $jstring='Comertului:'; // $jhelye=substr($jstring, 0, strpos($jstring, '')); // Osszefuzom az eredmenyt $final=$iplace.$ilegat; // Visszateritem az eredmenyt return $final; } } ///uj user beszurasa function partners_addUsersWeb($array , $web_client_id, $email, $code) { $insertQ = "INSERT INTO `users_website` ( `id` , `username` , `upassworld` , `clientid` , `email` , `active` , `code` ) VALUES ( NULL,'".$array["username"]."', PASSWORD('".$array["passworld"]."'), '$web_client_id' , '".$email."', '0' , '$code');"; mysql_query( $insertQ ) or die(mysql_error()); return mysql_insert_id(); } function partners_CodeUsersWeb($id) { $authQ = "SELECT * FROM `users_website` WHERE `clientid`='$id' LIMIT 1"; $authR = mysql_query( $authQ ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $auth = mysql_fetch_array( $authR ); return $auth; } //logiolas a websitera function loginweb( $username , $password ) { $authQ = "SELECT * FROM `users_website` WHERE `username`='$username' AND `upassworld`=PASSWORD('$password') LIMIT 1"; $authR = mysql_query( $authQ ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $auth = mysql_fetch_array( $authR ); return $auth; } //user aktivalasa function userActiv( $clientid ) { $query = "UPDATE `users_website` SET `active`= '1' WHERE `clientid`='$clientid' "; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } //user blokkolasa function partners_BlokUsersWeb($id) { $authQ = "UPDATE `users_website` SET `active`= '0' WHERE `clientid`='$id' "; $authR = mysql_query( $authQ ) or die(mysql_error()); return $auth; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////kepek kezelese a site-on///////////////////////////////////////////////////////////////////////////// ///kepek generalasa function data_getPhotos( $contid , $maxX , $maxY ,$imagepri) { if ($imagepri) { $query = "select * from container_images where prodid='$contid' AND id!='$imagepri' order by id ASC"; } else { $query = "select * from container_images where prodid='$contid' order by id ASC"; } $result=mysql_query( $query ) or die(mysql_error()); $szam=mysql_num_rows( $result ); if( $szam>0 ) { $picIndex = 0; while( $row = mysql_fetch_array( $result ) ) { $size=GetImageSize("management/images/uploaded/".$row["path"]); $fulllink=$row["path"]; $arany=$size[1]/80; $picture_size=$maxX; $picture_height=$maxY; $img_src_c='management/images/uploaded/'.$fulllink; $result_picture = mysql_query("select * from image_convert where old_src='$img_src_c' and thumb_size='$picture_size'"); $rw_picture = mysql_fetch_array( $result_picture ); if( $rw_picture["id"] != NULL ) { $pics[ $picIndex ]["src"] = $rw_picture["new_src"]; $pics[ $picIndex ]["path"] = $img_src_c; } else { $pics[ $picIndex ]["src"] = "image_print.php?&x=$picture_size&y=$picture_height&img_src=$fulllink"; $pics[ $picIndex ]["path"] = $img_src_c; } $picIndex ++; } return $pics; } return NULL; } ///letazik kep vagy nem function hasKep($id , $imagepri) { $result = mysql_query("SELECT * FROM `container_images` WHERE `prodid`='$id' AND `id`!='$imagepri' order by id ASC") or die(mysql_error()); return mysql_num_rows( $result ); } ///kepek generalasa function img_getThumb( $id , $random , $index , $maxX , $maxY , $imagepri ) { if ($imagepri) { $query = "select * from container_images where prodid='$id' AND id!='$imagepri' order by id ASC"; } else { $query = "select * from container_images where prodid='$id' order by id ASC"; } $result=mysql_query( $query ) or die(mysql_error()); $szam=mysql_num_rows( $result ); if( $szam>0 ) { if( $random ) { $randNum = rand( 0 , mysql_num_rows( $result ) - 1 ); if ($randNum>0) mysql_data_seek( $result , $randNum ); } $row = mysql_fetch_array( $result ); $size = GetImageSize("management/images/uploaded/".$row["path"]); $fulllink = $row["path"]; $arany = $size[1]/80; $picture_size=$maxX; $picture_height=$maxY; $img_src_c = 'management/images/uploaded/'.$fulllink; $result_picture = mysql_query("select * from image_convert where id!='$imagepri' AND old_src='$img_src_c' and thumb_size='$picture_size'"); $rw_picture = mysql_fetch_array( $result_picture ); if( $rw_picture["id"] != NULL ) { return $rw_picture["new_src"]; } else { return $picLink="image_print.php?&x=$picture_size&y=$picture_height&img_src=$fulllink"; } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////comandak listaja/////////// function command_getCommandForClientAdv2( $pageno = -1, $orderby ) { $query = "SELECT * FROM `comandaForClientAdv` WHERE `active` ='1' ORDER BY secondserial $orderby"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } /////////////////////////////////////////////// //egy termek kivevese a megrendeltek kozul function getCommandForPartnerAdvRegisteredItemNoStock( $id ) { $select = "SELECT * FROM `comandaForClientAdvItems` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } ///kuvekek egy bizonyos id punkt de lucrut function partners_getpunctedelucru_id11($punctid) { $query="SELECT * FROM `partners_punctDeLucru` WHERE `id`='$punctid'"; $result=mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return $row; } ///hagyanlatogattak meg az a termeket function Update_contenet_visit($szam,$contentid) { $query="UPDATE container SET visited=$szam WHERE id=$contentid"; mysql_query( $query ) or die(mysql_error()); } function entry_getConEntriesBycssidPage ($categoriid, $modelid, $mitol,$orderby) { if ($categoriid) { $query = "SELECT * FROM `container` WHERE `modelid`='$modelid' AND (`cs1`='$categoriid' OR `cs2`='$categoriid' OR `cs3`='$categoriid' OR `cs4`='$categoriid' OR `cs5`='$categoriid' OR `cs6`='$categoriid' OR `cs7`='$categoriid' OR `cs8`='$categoriid' OR `cs9`='$categoriid' OR `cs10`='$categoriid' OR `cs11`='$categoriid' OR `cs12`='$categoriid' OR `cs13`='$categoriid' OR `cs14`='$categoriid' OR `cs15`='$categoriid' OR `cs16`='$categoriid' OR`cs17`='$categoriid' OR `cs18`='$categoriid' OR `cs19`='$categoriid' OR `cs20`='$categoriid') AND `active`='1' order by price $orderby LIMIT $mitol,10 "; } else { $query = "SELECT * FROM `container` WHERE `modelid`='$modelid' AND `active`='1' order by price $orderby LIMIT $mitol,10 "; } $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $entries[ $row["id"] ] = $row; return $entries; } else return NULL; } //////////////////cautare/////////////////////// function model_getModelCsValuescautare( $modelCs, $keyword ) { $query = "SELECT * FROM `models_cs_values` WHERE `modelcsid`='$modelCs' and `name` LIKE '%$keyword%' ORDER BY `modelcsid` "; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCsValues[ $row["id"] ] = $row; return $modelCsValues; } function entry_getConEntrysortbykeyword($entryid, $keyword ) { $query = "SELECT * FROM `container` WHERE `id`='$entryid' and `name` LIKE '%$keyword%' LIMIT 1 ;"; $result = mysql_query( $query ) or die(mysql_error()); return ( $entry = mysql_fetch_array( $result )); } //////////////////////////////////////////////////////////////////////// ///////promotii////////////////// function entry_getConEntriespromotii ($mitol , $hany, $orderby ) { $query = " SELECT c.* ,m.name as modelname FROM `container` c , `models` m WHERE c.modelid = m.id and `pret_promo` != 0 and `active`=1 ORDER BY price $orderby LIMIT $mitol,$hany"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $entries[ $row["id"] ] = $row; return $entries; } else return NULL; } function entry_getConEntriespromotiiszamol1 () { $query = " SELECT * FROM `container` WHERE `pret_promo` != 0 AND `active`=1 ORDER BY ondate DESC"; $result = mysql_query( $query ) or die(mysql_error()); return $result ; } function entry_getConEntriespromotiiall () { $query = "SELECT * FROM `container` WHERE `pret_promo` !=0 AND (`modelid`=1 OR `modelid`=2 OR `modelid`=3 OR `modelid`=8) AND `active`=1 ORDER BY ondate DESC"; $cunt1=0; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) { $cunt1=$cunt1+1; $entries[$cunt1 ] = $row; } return $entries; } else return NULL; } /////////////////////////////////////legeladottab termekek//////////////////////////////////////////// function entry_getandcomandforclientadvitems ($modelid,$orderby) { $query = "SELECT p.id , f.prodid FROM container p, comandaForClientAdvItems f WHERE p.id = f.prodid AND p.active='1' GROUP BY p.id "; $result = mysql_query( $query ) or die(mysql_error()); if($result) while ($row = mysql_fetch_array ($result)) $total [$row ["id"]] = $row; if($total) { $oszszam=sizeof($total); $count=0; foreach( $total as $key => $value ) { $query1 = 'SELECT * FROM `comandaForClientAdvItems` WHERE `prodid`='.$value["id"].';' ; $result1 = mysql_query ($query1) or die(mysql_error()); unset($total1); while ($row1 = mysql_fetch_array ($result1)) $total1 [$row1 ["id"]] = $row1; $quantity=0; foreach( $total1 as $key => $value2 ) { $quantity=$quantity+$value2["quantity"]; } if ($result1) { $counter[$count]["count"]=$quantity; $counter[$count]["id"]=$value["id"]; $count=$count+1; } } } return $counter ; } ///////////////////banc cont////////////////// function partners_updatePartnerBankAccount2( $compid , $array ) { $result2=partners_getPartnerBankAccount( $compid ); $bank = htmlspecialchars($array["bank"]); $iban = htmlspecialchars($array["iban"]); $bankid = $row["id"]; $query = "UPDATE `bankaccounts` SET `bank`='$bank', `iban`='$iban' WHERE `compid`='$compid' AND `id`='$bankid'"; mysql_query( $query ) or die(mysql_error()); } ////////////////////szures//////////////////////////////////// function entry_getConEntriesBycssid3 ($categoriid, $modelid) { $query = "SELECT * FROM `container` WHERE `modelid`='$modelid' AND (`cs1`='$categoriid' OR `cs2`='$categoriid' OR `cs3`='$categoriid' OR `cs4`='$categoriid' OR `cs5`='$categoriid' OR `cs6`='$categoriid' OR `cs7`='$categoriid' OR `cs8`='$categoriid' OR `cs9`='$categoriid' OR `cs10`='$categoriid' OR `cs11`='$categoriid' OR `cs12`='$categoriid' OR `cs13`='$categoriid' OR `cs14`='$categoriid' OR `cs15`='$categoriid' OR `cs16`='$categoriid' OR`cs17`='$categoriid' OR `cs18`='$categoriid' OR `cs19`='$categoriid' OR `cs20`='$categoriid')"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $entries[ $row["id"] ] = $row; return $entries; } else return NULL; } function model_getModelCsValues12( $modelCs ) { $query = "SELECT id FROM `models_cs_values` WHERE `modelcsid`='$modelCs' ORDER BY `modelcsid` "; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCsValues[ $row["id"] ] = $row; return $modelCsValues; } function entry_getConEntriesBycssid_value($i , $cssid, $modelid) { $query2="SELECT DISTINCT `cs$i`,active,id FROM container WHERE `cs$i` LIKE '% $cssid;%' AND `modelid`='$modelid' AND `active`=1 "; $result=mysql_query( $query2 ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else return $result; } function entry_getConEntriesBycssid_valueWithProducts($i , $cssid,$modelcs, $modelid, $productQuery) { $productQuery=$productQuery." AND `cs$i` LIKE '% $cssid;%' AND `cont`.`modelid`='$modelid'" ; $result=mysql_query($productQuery) or die(mysql_error()); if(mysql_num_rows($result)>0) { return 1; } else return 0; } function entry_getConEntriesBycssid_valueWithProductsOnlySupliments($i , $cssid,$modelcs, $modelid, $productQuery) { $prodquery=str_replace("SELECT `cont`.* FROM container cont WHERE","SELECT `cont`.* , `sup`.* FROM container cont , model_cs_supliment sup WHERE",$productQuery); $productQuery=$prodquery." AND `cont`.`modelid`='$modelid' AND `cont`.`active`='1' AND `sup`.`modelcsid`='$cssid' AND `sup`.`csid`='$modelcs' AND `cont`.`id`=`sup`.`containerid`"; $result=mysql_query($productQuery) or die(mysql_error()); if(mysql_num_rows($result)>0) { return 1; } else return 0; } function entry_getConEntriesBycssid_value1($i,$modelid ) { $query2="SELECT DISTINCT `cs$i`,active FROM container WHERE `modelid`='$modelid' AND `active`=1"; $result=mysql_query( $query2 ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCsValues[ $row["cs$i"] ] = $row["cs$i"]; return $modelCsValues; } //////////////////////////////////////////////////////////////////////////////////////////////// function getcontainerimage ($imageid) { $query = " SELECT * FROM `container_images` WHERE `id` = '$imageid'"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return $row["path"] ; } ////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////a teljes nev es ccs osszeszedese egy valtozoba function getcontainercss ($contid) { $query = "SELECT * FROM `container` WHERE `id` = '$contid'"; $result = mysql_query( $query ) or die(mysql_error()); $value = mysql_fetch_array( $result ); if( $lastModelId != $value["modelid"] ) { // lekerdezem a termeknek a modelid -et $model = model_getModel($value["modelid"] ); } $counter++; // kiolvasom a ccskenek a neveit for( $i = 1 ; $i <=20 ; $i ++ ) { if($model["cs".$i]!=NULL ) { $vals[ $i ] = model_getModelCsValues( $model["cs".$i]); } } // kiolvasom a tulajdonsagait a ccseknek $modelCss = model_getModelCss(); // kiiratom a tartalmat egy termeknek $szam=0; for( $i = 1 ; $i <=20 ; $i ++ ) { if($model["cs".$i]!=NULL) { $szam=$szam+1; if($model["cs".$i]==12) { $marka=$i; } } } for( $i = 1 ; $i <=$szam ; $i ++ ) { if ($i==1) { $findme = ';'; $pos = strpos($value["cs".$marka], $findme); $cssElsoResz = substr($value["cs".$marka],0, $pos+1); $letterscss = array(" ",";"); $markanamename=str_replace($letterscss,"", $cssElsoResz); $cssnamenameossz=str_replace($cssElsoResz,"", $value["cs".$marka]); $teljesnevcss=$vals[$marka][ $markanamename ]["name"]." ".$value["name"]." "; } if ( $i != $marka) { $findme = ';'; $pos = strpos($value["cs".$i], $findme); $cssElsoResz = substr($value["cs".$i],0, $pos+1); $letterscss = array(" ",";"); $cssnamename=str_replace($letterscss,"", $cssElsoResz); $cssnamenameossz=str_replace($cssElsoResz,"", $value["cs".$i]); $teljesnevcss=$teljesnevcss.$modelCss[ $model["cs".$i] ]["name"].":"; if ($modelCss[ $model["cs".$i] ]["type"]==1) { $teljesnevcss=$teljesnevcss.$cssnamename." "; } else { $teljesnevcss=$teljesnevcss.$vals[$i][ $cssnamename ]["name"]." "; while ($cssnamenameossz) { $findme = ';'; $pos = strpos($cssnamenameossz, $findme); $cssElsoResz = substr($cssnamenameossz,0, $pos+1); $letterscss = array(" ",";"); $cssnamename=str_replace($letterscss,"", $cssElsoResz); $teljesnevcss=$teljesnevcss.$cssnamename." "; $cssnamenameossz=str_replace($cssElsoResz,"", $cssnamenameossz); } } } } return $teljesnevcss; } //////////////////////////////szures model css//////////////////////////////////// function model_getModelCsszures( $modelCsId ) { $query = "SELECT * FROM `models_cs` WHERE `id`='$modelCsId' AND `active`='1' "; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $modelCs = mysql_fetch_array( $result ); return $modelCs; } function setFilerActive($showform, $aktualis,$id) { $query='UPDATE '.$showform.' SET `cs'.$id.'active` = 1 WHERE `id` ="'.$aktualis.'"'; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } // A hir inaktvivva tetele function setFilerInactive($showform, $aktualis,$id) { $query='UPDATE '.$showform.' SET `cs'.$id.'active` = 0 WHERE `id` ="'.$aktualis.'"'; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } //////////////////////////////a cshez hozzaadott txt///////////////////////////////////////////////////////////// function setcCssText($text, $id) { $query = "UPDATE `models_cs` SET `textcss`='$text' WHERE `id`='$id' LIMIT 1;"; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } //////////////////////////////a model cs supliment fugvenyei///////////////////////////////////////////////////////////// function addcsssupliment( $entryid,$csid,$cs ) { $query="insert into `model_cs_supliment` values(null, 0, '$entryid' ,'$csid')"; mysql_query( $query ) or die(mysql_error()); } function getcsssupliment($id) { $query2="SELECT * FROM model_cs_supliment WHERE `containerid`='$id'"; $result=mysql_query( $query2 ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCssupliment[ $row["id"] ] = $row; return $modelCssupliment; } function getcsssupliment2($id) { $query2="SELECT * FROM model_cs_supliment WHERE `containerid`='$id'"; $result=mysql_query( $query2 ) or die(mysql_error()); return $result; } function csssuplimentupdate( $entryid , $array ) { $result2=getcsssupliment2( $entryid ); while( $row=mysql_fetch_array($result2) ) { $j = $row["id"]; $cssspecid = htmlspecialchars($array["cssupliment$j"]); $query = "UPDATE `model_cs_supliment` SET `modelcsid`='$cssspecid' WHERE `containerid`='$entryid' AND `id`='$j'"; mysql_query( $query ) or die(mysql_error()); } } function model_getModelCssbyid($cssid) { $query = "SELECT * FROM `models_cs_values` WHERE `id`='$cssid'"; $result = mysql_query( $query ) or die(mysql_error()); $modelCs = mysql_fetch_array( $result ); return $modelCs; } function getcsssuplimentallWheremodelcsid($csid) { $query2="SELECT * FROM model_cs_supliment WHERE `modelcsid`='$csid'"; $result=mysql_query( $query2 ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCssuplimentmodelid[ $row["id"] ] = $row; return $modelCssuplimentmodelid; } function getcssbycontyid($i,$cssid,$modelid) { $query = "SELECT DISTINCT p.cs$i, p.id , f.containerid FROM container p, model_cs_supliment f WHERE p.id = f.containerid AND p.cs$i='$cssid' AND p.modelid='$modelid' AND p.active='1' "; } function getcsssupliment21($id,$modelid) { $query2="SELECT * FROM model_cs_supliment WHERE `containerid`='$id' AND `csid`='$modelid'"; $result=mysql_query( $query2 ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $modelCssuplimentmodelid[ $row["id"] ] = $row; return $modelCssuplimentmodelid; } function getcssbycsid($cssid) { $query = "SELECT DISTINCT `modelcsid`, `id` FROM `model_cs_supliment` WHERE `csid`='$cssid'"; $result=mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $cssbycsid[ $row["id"] ] = $row; return $cssbycsid; } function cssuplimantdelte($cssid) { $query = "DELETE FROM model_cs_supliment WHERE id='$cssid' "; $result=mysql_query( $query ) or die(mysql_error()); } ////////////////////////////////////////////////////////////////////////////////// function entry_getConEntrycautare( $entryid ) { $query = "SELECT * FROM `container` WHERE `id`='$entryid' AND `active`='1' LIMIT 1 ;"; $result = mysql_query( $query ) or die(mysql_error()); return ( $entry = mysql_fetch_array( $result )); } function entry_getConEntriescautare () { $query = " SELECT c.* ,m.name as modelname FROM `container` c , `models` m WHERE c.modelid = m.id AND c.active=1 ORDER BY `c`.modelid"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $entries[ $row["id"] ] = $row; return $entries; } else return NULL; } function entry_getConEntriesmodelid ($modelid) { if (!$modelid) { $query = " SELECT c.* ,m.name as modelname FROM `container` c , `models` m WHERE c.modelid = m.id ORDER BY `c`.modelid"; } else { $query = " SELECT c.* ,m.name as modelname FROM `container` c , `models` m WHERE c.modelid = m.id AND c.modelid=$modelid ORDER BY `c`.modelid"; } $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $entries[ $row["id"] ] = $row; return $entries; } else return NULL; } ////////////////////update css/////////////////// function updatecss($r,$cssid,$entryid) { $query="UPDATE `container` SET `cs$r` = '".$cssid."' WHERE `container`.`id` =$entryid LIMIT 1 ;"; $result = mysql_query( $query ) or die(mysql_error()); } function getcssbycsidscript($cssid) { $query = "SELECT * FROM `model_cs_supliment` "; $result=mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $cssbycsid[ $row["id"] ] = $row; return $cssbycsid; } ///////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// function atiuitatparolaweb($email) { $query2="SELECT * FROM users_website WHERE `email`='$email' LIMIT 1"; $result=mysql_query( $query2 ) or die(mysql_error()); $row = mysql_fetch_array( $result ); if( mysql_affected_rows() <= 0 ) { return NULL; } else { $codeatiuitat=generateCode(8); $idrezut=$row["id"]; $query = "UPDATE `users_website` SET `upassworld`=PASSWORD('$codeatiuitat') WHERE `id`='$idrezut' "; $result2=mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 ) { return NULL; } $returnatiuitat["user"]=$row["username"]; $returnatiuitat["email"]=$row["email"]; $returnatiuitat["code"]=$codeatiuitat; return $returnatiuitat; } } function users_updatePasswordSite( $userid , $password ,$username) { if( $password != NULL ) { $query = "UPDATE `users_website` SET `upassworld`=PASSWORD('$password') WHERE `clientid`='$userid' AND `username`='$username'"; $Result = mysql_query( $query ) or die(mysql_error()); } } function insertintowishlist( $userid , $entryid ) { $query="insert into wishlist values(null,'$userid', '$entryid' ,'0')"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function osszeswishlistkiovasasa($clientid) { $query = "SELECT DISTINCT `entryid` FROM `wishlist` WHERE `clientid`='$clientid'"; $result=mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $cssbycsid[ $row["entryid"] ] = $row; return $cssbycsid; } ////////////////////////////egy modelnek a leirasa//////////////////////////// function modelAddDescription ($modelId) { $query='UPDATE `models` SET `description` ="'.$_POST['modeldesc'].'" WHERE `id` ='.$modelId; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } // Leiras kiolvasasa letezo modelbol function modelGetDescription ($modelId) { $query='SELECT * FROM `models` WHERE `id`='.$modelId; $lekerdezes=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($lekerdezes)) { $result[$listAll["id"]]=$listAll; } foreach($result as $temp=>$linkek) { $alaptartalom=$linkek['description']; } return $alaptartalom; } ////////////////////////////egyfajta termeknek ha van mas tulajdonsaga is//////////////////////// function getEntryColor ($entryid,$codprodus) { $query="SELECT * FROM `container` WHERE `id`!='$entryid' AND `code_produs`='$codprodus' AND `active`='1'"; $lekerdezes=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($lekerdezes)) { $result[$listAll["id"]]=$listAll; } return $result; } function getEntryColorfilter ($cscolor,$entryid,$codprodus) { $query="SELECT * FROM `container` WHERE `$cscolor` LIKE '%$entryid%' AND `code_produs`='$codprodus' AND `active`='1'"; $lekerdezes=mysql_query( $query ) or die(mysql_error()); while ($listAll=mysql_fetch_array($lekerdezes)) { $result[$listAll["id"]]=$listAll; } return $result; } function getEntryColorfilter1 ($codprodus) { $query="SELECT * FROM `container` WHERE `code_produs`='$codprodus' AND `active`='1' LIMIT 1"; $lekerdezes=mysql_query( $query ) or die(mysql_error()); $listAll=mysql_fetch_array($lekerdezes); return $listAll; } function entry_getConEntriesBymodelid ( $modelid) { $query = "SELECT * FROM `container` WHERE `modelid`='$modelid' AND `active`='1' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); return ( $entrymodel = mysql_fetch_array( $result )); } // valami sztorno function factura_getStornedFactura( $facturaId ) { $query = "SELECT * FROM `facturi` WHERE `id`=$facturaId AND `active` ='1' AND `type`='1'"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $results ); $questFacturaRawValue = $row["rawvalue"]; $questFacturaClientId = $row["clientid"]; $questFacturaRonValue = convertNumber( ($row["rawvalue"] * $row["cursValue"])*(-1) ); $hossz = strlen($questFacturaRonValue); $questFacturaRonValueFinal1 = $questFacturaRonValue+0.01; $questFacturaRonValueFinal2 = $questFacturaRonValue-0.01; $questFacturaCursValue = $row["cursValue"]; $questFacturaId = $row["id"]; $questFacturaFromCommandForClientId = $row["fromActId"]; $questFacturaFromCommandAdvForClientId = $row["fromActAdvId"]; $questFacturaDate = $row["ondate"]; $negativeQuestFacturaRawValue = 0 - $questFacturaRawValue; $paidFactura = factura_getPaidValueWithoutCurrency($questFacturaId); $queryFactura = "SELECT * FROM `facturi` WHERE `rawvalue`<0 AND `clientid`='$questFacturaClientId' AND (`fromActId`='$questFacturaFromCommandForClientId' OR `fromActAdvId`='$questFacturaFromCommandAdvForClientId') AND (`rawvalue` = '$negativeQuestFacturaRawValue' OR `rawvalue` = ('$negativeQuestFacturaRawValue'*'$questFacturaCursValue') OR `rawvalue` = ('$negativeQuestFacturaRawValue'/'$questFacturaCursValue') ) AND `rawvalue` * `cursValue` > '$questFacturaRonValueFinal2' AND `rawvalue` * `cursValue` < '$questFacturaRonValueFinal1' AND `ondate`>='$questFacturaDate' AND `active` ='1' AND `type`='1'"; $resultsFactura = mysql_query( $queryFactura ) or die(mysql_error()); if( mysql_affected_rows() <= 0 ) { return NULL; } else { if($paidFactura==0) return 1; else return NULL; } } //kiszedi RON ba a teljes tartozast, atszamolva a szamlakat es a fizeteseket is lejbe, az aktualis arfolyamon function factura_getPaidValueWithoutCurrency( $factid ) { $select = "SELECT SUM(`value`) as `sum` FROM `bills` WHERE `factid`='$factid' AND `active`='1'"; $result = mysql_query( $select ) or die(mysql_error()); $sum = 0; if( mysql_affected_rows() > 0 ) { $row = mysql_fetch_array( $result ); $sum = $row["sum"]; } $select = "SELECT SUM(`value`) as `sum` FROM `op` WHERE `factid`='$factid'"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() > 0 ) { $row = mysql_fetch_array( $result ); $sum += $row["sum"]; } return $sum; } //kigeneralja az osszes koltseget a kliensnek function expens_queryGeneratorClient( $clientid , $page = 1 , $orderby , $ordermode , $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; $query = "SELECT * FROM `expenses` WHERE `provider` = '$clientid' AND `expdate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; return $query; } function insertPlata( $factid, $number, $value, $clientid, $userid, $onValuta, $cursValue , $fromFullValue , $fromFullValueCurrency , $date, $type) { $plusDate = " ".date("H:i:s"); $query = "INSERT INTO pais VALUES( NULL, '$number' , '$value' , '$date$plusDate', '$factid' , '$clientid' , '$userid' , '$onValuta' , '$cursValue' , '$fromFullValue' , '$fromFullValueCurrency' , '$type')"; $result = mysql_query( $query ) or die(mysql_error()); } function factura_getFacturaPlata( $expensid ) { $query = "SELECT * FROM `pais` WHERE `factid`='$factid'"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; } return NULL; } function specialCharacterDelete($str) { $from=array("�f®", "�Z", "î", "Î","î" , "ș", "ț", "%", " ", "Ă", "ă", "Â", "â", "Î", "î", "Ș", "ș", "Ş", "Ț", "ț", "Ţ", "ţ", "à", "ő", "ó", "ö", "ó","'", "�f¡", "�f³", "�f¶", "�f©", "�f¼"); $to=array("i", "I" ,"i", "I" ,"i", "s", "t", "lasuta", "_" ,"A", "a", "A", "a", "I", "i", "S", "s", "S", "T", "t", "T", "t", "a", "o", "o","o", "o", "", "a", "o", "o", "e", "u"); $firstString=str_replace($from, $to, $str); $newString=str_replace("�f", "i", $firstString); return $newString; } //expens plussz fuggvenyek + pais fuggvenyek function partner_getTotalSell( $clientid,$toDate="" ) { if($toDate=="") $toDate=date("Y-m-d"); //facturi $facturiQ = "SELECT sum(`value` * `cursValue`) as totalFact FROM `facturi` WHERE `clientid`='$clientid' AND `active`='1' AND `type`='1' AND `ondate`<='$toDate'"; $facturiR = mysql_query( $facturiQ ) or die(mysql_error()); if( mysql_result( $facturiR , 0 , 0 ) > 0 )$factValue = mysql_result( $facturiR , 0 , 0 ); else $factValue = 0; return $factValue; } function partner_getTotalExpens( $clientid,$toDate="" ) { if($toDate=="") $toDate=date("Y-m-d"); $expensQ = "SELECT sum( (`value`+`tva`) * `cursValue`) as totalExpens FROM `expenses` WHERE `provider`='$clientid' AND `ondate`<='$toDate'"; $expensR = mysql_query( $expensQ ) or die(mysql_error()); if( mysql_result( $expensR , 0 , 0 ) > 0 )$expensValue = mysql_result( $expensR , 0 , 0 ); else $expensValue = 0; return $expensValue; } function factura_getPlata( $orderby, $ordermode , $pagetoshow = -1 , $from , $to , $searchval , $searchCriteria ) { $to = mysql_nextDay( $to ); if( $searchCriteria == "name") { $query = "SELECT pais.id AS id, pais.type AS type, p.name AS clientname, u.username AS username, pais.value , pais.onValuta AS onValuta, pais.fromFullValue AS fromFullValue, pais.fromFullValueCurrency AS fromFullValueCurrency, pais.number AS number, pais.ondate AS ondate , pais.expensid as factid FROM pais, users u, partners p WHERE u.id = pais.userid AND p.id = pais.partnerid AND p.name LIKE '%$searchval%' AND `pais`.`ondate` BETWEEN '$from' AND '$to' ORDER BY $orderby $ordermode"; } if( $searchCriteria == "serial") { $query = "SELECT pais.id AS id, pais.type AS type, p.name AS clientname, u.username AS username, pais.value , pais.onValuta AS onValuta, pais.fromFullValue AS fromFullValue, pais.fromFullValueCurrency AS fromFullValueCurrency, pais.number AS number, pais.ondate AS ondate , pais.expensid as factid FROM pais, users u, partners p WHERE u.id = pais.userid AND p.id = pais.partnerid AND pais.number LIKE '%$searchval%' ORDER BY $orderby $ordermode"; } if( $searchCriteria == "") { $query = "SELECT pais.id AS id, pais.type AS type, p.name AS clientname, u.username AS username, pais.value , pais.onValuta AS onValuta, pais.fromFullValue AS fromFullValue, pais.fromFullValueCurrency AS fromFullValueCurrency, pais.number AS number, pais.ondate AS ondate , pais.expensid as factid FROM pais, users u, partners p WHERE u.id = pais.userid AND p.id = pais.partnerid AND pais.number LIKE '%$searchval%' ORDER BY $orderby $ordermode"; } if( $pagetoshow != -1 ) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pagetoshow - 1) * $count; $query .= " LIMIT $from, $count"; } $result = mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) $list[ $row ["id"] ] = $row; return $list; } function factura_getPlataCounter( $orderby, $ordermode = "desc", $pagetoshow = -1 , $from , $to , $searchval , $searchCriteria ) { $to = mysql_nextDay( $to ); if( $searchCriteria == "name") { $query = "SELECT pais.id AS id, p.name AS clientname, u.forname AS username, pais.value , pais.onValuta AS onValuta, pais.fromFullValue AS fromFullValue, pais.fromFullValueCurrency AS fromFullValueCurrency, pais.number AS number, pais.ondate AS ondate , pais.expensid as factid FROM pais, users u, partners p WHERE u.id = pais.userid AND p.id = pais.partnerid AND p.name LIKE '%$searchval%' AND `pais`.`ondate` BETWEEN '$from' AND '$to' ORDER BY $orderby $ordermode"; } if( $searchCriteria == "serial") { $query = "SELECT pais.id AS id, p.name AS clientname, u.forname AS username, pais.value , pais.onValuta AS onValuta, pais.fromFullValue AS fromFullValue, pais.fromFullValueCurrency AS fromFullValueCurrency, pais.number AS number, pais.ondate AS ondate , pais.expensid as factid FROM pais, users u, partners p WHERE u.id = pais.userid AND p.id = pais.partnerid AND pais.number LIKE '%$searchval%'"; } if( $searchCriteria == "") { $query = "SELECT pais.id AS id, p.name AS clientname, u.forname AS username, pais.value , pais.onValuta AS onValuta, pais.fromFullValue AS fromFullValue, pais.fromFullValueCurrency AS fromFullValueCurrency, pais.number AS number, pais.ondate AS ondate , pais.expensid as factid FROM pais, users u, partners p WHERE u.id = pais.userid AND p.id = pais.partnerid AND pais.number LIKE '%$searchval%'"; } $result = mysql_query( $query ) or die(mysql_error()); $count=0; while( $row = mysql_fetch_array( $result ) ) $count++; return $count; } function expens_queryGeneratorPais( $clientid ) { $query = "SELECT e.* FROM `expenses` e WHERE e.`provider` = '$clientid' ORDER BY e.`expdate` ASC"; return $query; } function expens_getPaid( $expensid ) { $query = "SELECT SUM(p.value*p.cursValue) as paid FROM `pais` p WHERE p.`expensid` = '$expensid' ORDER BY p.`ondate` ASC"; $results = mysql_query( $query ) or die(mysql_error()); if( $results ) { $row = mysql_fetch_array( $results ); return $row["paid"]; } return NULL; } function expens_getPaidInterval( $expensid , $from , $to ) { $query = "SELECT SUM(p.value*p.cursValue) as paid FROM `pais` p WHERE p.`expensid` = '$expensid' AND `p`.`ondate` BETWEEN '$from' AND '$to' ORDER BY p.`ondate` ASC"; $results = mysql_query( $query ) or die(mysql_error()); if( $results ) { $row = mysql_fetch_array( $results ); return $row["paid"]; } return NULL; } function expens_getPaidWithCurrency( $expensid ) { $query = "SELECT SUM(p.value) as paid FROM `pais` p WHERE p.`expensid` = '$expensid' ORDER BY p.`ondate` ASC"; $results = mysql_query( $query ) or die(mysql_error()); if( $results ) { $row = mysql_fetch_array( $results ); return $row["paid"]; } return NULL; } function expens_getPaidValueForTimeInterval( $from , $to ) { $paid = 0; $toDate = mysql_nextDay( $to ); $query = "SELECT SUM(`rawvalue`*`cursValue`) as total FROM `facturi` WHERE `active`='1' AND `type`='1' AND `ondate` BETWEEN '$from' and '$toDate'"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); $paid = $row["total"]; return convertNumber($paid); } function expens_getPaidValueTvaForTimeInterval( $from , $to ) { $paid = 0; $toDate = mysql_nextDay( $to ); $query = "SELECT SUM(`value`*`cursValue`) as total FROM `facturi` WHERE `active`='1' AND `type`='1' AND `ondate` BETWEEN '$from' and '$toDate'"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); $paid = $row["total"]; return convertNumber($paid); } function expens_getExpensesForTimeInterval( $from , $to ) { $to = mysql_nextDay( $to ); $query = "SELECT SUM(`value`*`cursValue`) as total FROM `expenses` WHERE `expdate` BETWEEN '$from' AND '$to' AND `payed` != '1'"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return convertNumber($row["total"]); } function expens_getTvaExpensesForTimeInterval( $from , $to ) { $to = mysql_nextDay( $to ); $query = "SELECT SUM(`tva`*`cursValue`) as total FROM `expenses` WHERE `expdate` BETWEEN '$from' AND '$to' AND `payed` != '1'"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return convertNumber($row["total"]); } //expenses graphs function stats_howmanyExpenses( $from, $to ) { $query = stats_expensesGenerateQuery( $from , $to ); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { $counter++; foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; $facturiValueWithTva += $value; } } return $facturiValueWithTva; } function stats_howmanyOutExpenses( $from, $to ) { $query = stats_expensesOutGenerateQuery( $from , $to ); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { $counter++; foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; $facturiValueWithTva += $ExpValue; } } return $facturiValueWithTva; } function stats_howmanyOutRestantaExpenses( $from, $to ) { $query = stats_expensesOutGenerateQuery( $from , $to ); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { $counter++; foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; $paidTotal = convertNumber(expens_getPaidInterval( $id , $from, $to)); $facturiValueWithTva += convertNumber($ExpValue-$paidTotal); } } return $facturiValueWithTva; } function stats_howmanyPaisExpenses( $from, $to ) { $query = stats_expensesPaisGenerateQuery( $from , $to ); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { $counter++; foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; $facturiValueWithTva += $PayValue; } } return $facturiValueWithTva; } function stats_expensesGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `expenses` f, `partners` p WHERE `p`.`id` = `f`.`provider` AND `payed`!='1' AND `expdate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function stats_expensesOutGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name`, ((`f`.`value`+`f`.`tva`)*`f`.`cursValue`) as ExpValue FROM `expenses` f, `partners` p WHERE `p`.`id` = `f`.`provider` AND `payed`!='1' AND `expdate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function stats_expensesPaisGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `e`.*, `p`.`name`, (`f`.`value`*`f`.`cursValue`) as PayValue FROM `pais` f, `partners` p, `expenses` e WHERE `p`.`id` = `f`.`partnerid` AND `e`.`id`=`f`.`expensid` AND `e`.`payed`!='1' AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function convertNumberInt( $x ) { if (($pos = strpos ($x, '.')) == false) $whole = $x; else { $whole = substr ($x, 0, $pos); return $whole; } } function stats_howmanyExpensesCategory( $from, $to , $categoryid ) { $query = stats_expensesCategoryGenerateQuery( $from , $to , $categoryid ); $invoices = factura_searchBill( $query ); if( $invoices ) { foreach( $invoices as $key => $xvalue ) { $counter++; foreach( $xvalue as $kkey => $vvalue ) $$kkey = $vvalue; $facturiValueWithTva += $value; } } return $facturiValueWithTva; } function stats_expensesCategoryGenerateQuery( $fromDate , $toDate , $categoryid ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `expenses` f, `partners` p WHERE `p`.`id` = `f`.`provider` AND `f`.`catid` = '$categoryid' AND `expdate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } //xls generalashoz kell function partners_searchTotalInfoPartnerGenerateQuery( $searchval , $iscomp , $page , $orderby , $ordermode , $ispartner, $clientstate=1 ) { $count = 10000000; $from = ($page - 1) * $count; if($page=='-1') $limitQuery=""; else $limitQuery = " LIMIT $from , $count"; if( $iscomp == 0 ) $query = "SELECT * FROM `partners` WHERE `cnp` is not NULL AND (`name` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `address` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `forname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `lastname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) ) AND `clientstate`='$clientstate' ORDER BY $orderby $ordermode".$limitQuery; else if( $iscomp == 1 ) $query = "SELECT * FROM `partners` WHERE `cnp` is NULL AND `ispartner`='$ispartner' AND (`name` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `address` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `forname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `lastname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) ) AND `clientstate`='$clientstate' ORDER BY $orderby $ordermode".$limitQuery; else if( $iscomp == 2 ) $query = "SELECT * FROM `partners` WHERE `cnp` is NULL AND `ispartner`='1' AND (`name` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `address` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `forname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `lastname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 )) AND `clientstate`='$clientstate' ORDER BY $orderby $ordermode".$limitQuery; else if( $iscomp == 3 ) $query = "SELECT * FROM `partners` WHERE `cnp` is NULL AND (`name` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `address` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `forname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `lastname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 )) AND `clientstate`='$clientstate' AND `partnersIsPartner`='1' ORDER BY $orderby $ordermode".$limitQuery; else if( $iscomp ==4) $query = "SELECT * FROM `partners` WHERE (`name` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `address` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `forname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 ) OR `lastname` LIKE CONVERT( _utf8 '%$searchval%' USING latin1 )) AND `clientstate`='$clientstate' ORDER BY $orderby $ordermode".$limitQuery; return $query; } function partner_getBalanceForPartner( $clientid,$toDate="" ) { if($toDate=="") $toDate=date("Y-m-d"); //facturi $facturiQ = "SELECT sum(`value` * `cursValue`) as totalFact FROM `facturi` WHERE `clientid`='$clientid' AND `active`='1' AND `type`='1' AND `ondate`<='$toDate'"; $facturiR = mysql_query( $facturiQ ) or die(mysql_error()); if( mysql_result( $facturiR , 0 , 0 ) > 0 )$factValue = mysql_result( $facturiR , 0 , 0 ); else $factValue = 0; //bills $billQ = "SELECT sum(`value`) as totalBill FROM `bills` WHERE `clientid`='$clientid' AND `active`=1 AND `ondate`<='$toDate'"; $billR = mysql_query( $billQ ) or die(mysql_error()); if( mysql_result( $billR , 0 , 0 ) > 0 )$billValue = mysql_result( $billR , 0 , 0 ); else $billValue = 0; //ops $opQ = "SELECT sum(`value` * `cursValue`) as totalOp FROM `op` WHERE `clientid`='$clientid' AND `ondate`<='$toDate'"; $opR = mysql_query( $opQ ) or die(mysql_error()); if( mysql_result( $opR , 0 , 0 ) > 0 )$opValue = mysql_result( $opR , 0 , 0 ); else $opValue = 0; //beleszamoljuk a koltseg szamlakat is (partnerek) $expensQ = "SELECT sum( (`value`+`tva`) * `cursValue`) as totalExpens FROM `expenses` WHERE `provider`='$clientid' AND `ondate`<='$toDate'"; $expensR = mysql_query( $expensQ ) or die(mysql_error()); if( mysql_result( $expensR , 0 , 0 ) > 0 )$expensValue = mysql_result( $expensR , 0 , 0 ); else $expensValue = 0; $paisQ = "SELECT sum( `value` * `cursValue`) as totalPais FROM `pais` WHERE `partnerid`='$clientid' AND `ondate`<='$toDate'"; $paisR = mysql_query( $paisQ ); if( mysql_result( $paisR , 0 , 0 ) > 0 )$paisValue = mysql_result( $paisR , 0 , 0 ); else $paisValue = 0; $difference = 0; $difference = ( convertNumber($expensValue) - convertNumber($paisValue) ) - (convertNumber($factValue) - convertNumber($billValue + $opValue)); return $difference; } function partner_getBalanceForPartnerToDay( $clientid, $date ) { //facturi $facturiQ = "SELECT sum(`value` * `cursValue`) as totalFact FROM `facturi` WHERE `clientid`='$clientid' AND `active`='1' AND `type`='1' AND `ondate`<='$date'"; $facturiR = mysql_query( $facturiQ ); if( mysql_result( $facturiR , 0 , 0 ) > 0 )$factValue = mysql_result( $facturiR , 0 , 0 ); else $factValue = 0; //bills $billQ = "SELECT sum(`value`) as totalBill FROM `bills` WHERE `clientid`='$clientid' AND `active`=1 AND `ondate`<='$date'"; $billR = mysql_query( $billQ ); if( mysql_result( $billR , 0 , 0 ) > 0 )$billValue = mysql_result( $billR , 0 , 0 ); else $billValue = 0; //ops $opQ = "SELECT sum(`value` * `cursValue`) as totalOp FROM `op` WHERE `clientid`='$clientid' AND `ondate`<='$date'"; $opR = mysql_query( $opQ ); if( mysql_result( $opR , 0 , 0 ) > 0 )$opValue = mysql_result( $opR , 0 , 0 ); else $opValue = 0; //beleszamoljuk a koltseg szamlakat is (partnerek) $expensQ = "SELECT sum( (`value`+`tva`) * `cursValue`) as totalExpens FROM `expenses` WHERE `provider`='$clientid' AND `ondate`<='$date'"; $expensR = mysql_query( $expensQ ); if( mysql_result( $expensR , 0 , 0 ) > 0 )$expensValue = mysql_result( $expensR , 0 , 0 ); else $expensValue = 0; $paisQ = "SELECT sum( `value` * `cursValue`) as totalPais FROM `pais` WHERE `partnerid`='$clientid' AND `ondate`<='$date'"; $paisR = mysql_query( $paisQ ); if( mysql_result( $paisR , 0 , 0 ) > 0 )$paisValue = mysql_result( $paisR , 0 , 0 ); else $paisValue = 0; $difference = 0; $difference = ( convertNumber($expensValue) - convertNumber($paisValue) ) - (convertNumber($factValue) - convertNumber($billValue + $opValue)); return $difference; } //szerzodes kivalaszto fuggveny - kulcsszo utan function selectTemplateFromKeywors($serviceid,$viewall,$userid) { $services=service_getService($serviceid); //megnezem, hogy az osszes templateben van e olyan kulcsszo ami a //szolgaltatasban is benne van, pld "hosting" $serviceName = $services["name"]; if($viewall!="1") { $viewquery= " AND ( `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) ) "; } if($serviceid==NULL) $serviceName = "Contract general"; $query = "SELECT * FROM `documents_template` where `keyword`!='' $viewquery"; $result=mysql_query( $query ) or die(mysql_error()); if($result) while($row=mysql_fetch_array($result)) { if(strpos(strtolower($serviceName),strtolower($row["keyword"]))!==FALSE) return $row["id"]; } } function days_between($fyear, $fmonth, $fday, $tyear, $tmonth, $tday) { return abs((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, $tmonth, $tday, $tyear))/(60*60*24)); } //Newsletter rendszer fuggvenyek - eloszor az email adatbazis function newsletter_getNewsletterClients( $type = 0 ) { $query = "SELECT * FROM `newsletterClients` WHERE `ispartner`='$type' ORDER BY name"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $providers[ $row["id"] ] = $row; return $providers; } function newsletter_getNewsletterClientsCategories() { $query = "SELECT * FROM `newsletterClients_category` WHERE `active`=1 ORDER BY id"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $providers[ $row["id"] ] = $row; return $providers; } function getAllNewsletterCats() { $query="SELECT * FROM `newsletterClients_category`"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function ActivareDezactivareNewsletterCat($act,$id) { $query="UPDATE `newsletterClients_category` SET `active`='$act' WHERE `id`='$id'"; $result=mysql_query($query) or die(mysql_error()); } function editNewsletterCategory($id,$name) { $query="UPDATE `newsletterClients_category` SET `categoryName`='$name' WHERE `id`='$id'"; $result=mysql_query($query) or die(mysql_error()); } function addNewsletterCategory($name) { $query="INSERT INTO `newsletterClients_category`(`categoryName`,`active`) VALUES('$name','1')"; $result=mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function getNewsletterCategory($id) { $query="SELECT * FROM `newsletterClients_category` WHERE `id`='$id'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row; } function newsletter_getNewsletterClientsCategory($categoryId) { $query = "SELECT * FROM `newsletterClients_category` WHERE `id`='$categoryId' ORDER BY id"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $providers[ $row["id"] ] = $row; return $providers; } function newsletter_getNewsletterClientsAll( $type = 0 ) { $query = "SELECT * FROM `newsletterClients` ORDER BY `name`"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $providers[ $row["id"] ] = $row; return $providers; } function newsletter_getNewsletterClient( $partnerId ) { $query = "SELECT * FROM `newsletterClients` WHERE `id`='$partnerId'"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $partner = mysql_fetch_array( $result ) ); } function newsletter_delNewsletterClients( $partnerid ) { $query = "DELETE FROM newsletterClients WHERE id = '$partnerid'"; mysql_query( $query ) or die(mysql_error()); } function newsletter_searchNewsletterClientsGenerateQuery( $searchval , $iscomp , $page , $orderby , $ordermode , $categoryId , $citiri , $clickuri , $newsletterId) { if($page!=-1) { $count = $_SESSION["settings"]["searchcount"]; $from = ($page - 1) * $count; } else { $count = 10000000; $from=0; } if($categoryId) { $categoryFilter = " AND `n`.`categoryId`='$categoryId'"; } else { $categoryFilter = ""; } if($newsletterId) { $newsletterFilter = " AND `s`.`newsletter_id`='$newsletterId'"; } else { $newsletterFilter = ""; } $toFilter=0; if($newsletterId!=0 && $newsletterId!=NULL) $toFilter=1; if($citiri!=0 && $citiri!=NULL) $toFilter=1; if($clickuri!=0 && $clickuri!=NULL) $toFilter=1; if($clickuri!=0) { $clickuriSql=" AND `s`.`from_link`!='' AND `s`.`move`='2'"; $clickuriSqlGroup = "HAVING COUNT(`s`.`from_link`) >= '$clickuri'"; } else { if($citiri!=0) { $citiriSql=" AND (`s`.`move`='1' OR `s`.`move`='2')"; $citiriSqlGroup = "HAVING COUNT(`s`.`id`) >= '$citiri'"; } else { $citiriSql=""; } $clickuriSql=""; } if($toFilter==0) { $query = "SELECT `n`.* FROM `newsletterClients` n WHERE (`n`.`name` LIKE '%$searchval%' OR `n`.`address` LIKE '%$searchval%' OR `n`.`forname` LIKE '%$searchval%' OR `n`.`lastname` LIKE '%$searchval%' OR `n`.`xemail` LIKE '%$searchval%') ".$categoryFilter." ORDER BY `n`.$orderby $ordermode LIMIT $from , $count"; } else { $query = "SELECT `n`.*, COUNT(`s`.`id`) AS totalMove, COUNT(`s`.`from_link`) AS totalClick FROM `newsletterClients` n, `newsletter_stats` s WHERE (`n`.`name` LIKE '%$searchval%' OR `n`.`address` LIKE '%$searchval%' OR `n`.`forname` LIKE '%$searchval%' OR `n`.`lastname` LIKE '%$searchval%' OR `n`.`xemail` LIKE '%$searchval%') ".$categoryFilter." AND `n`.`id`=`s`.`abonat_id` ".$newsletterFilter.$citiriSql.$clickuriSql." GROUP BY `n`.`id` ".$citiriSqlGroup.$clickuriSqlGroup." ORDER BY `n`.$orderby $ordermode LIMIT $from , $count"; } return $query; } function newsletter_searchNewsletterClients($query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $partners[ $row["id"] ] = $row; return $partners; } function newsletter_addNewsletterClients( $array ) { if( $array["sold"] == NULL )$array["sold"] = 0; $array["name"] = htmlspecialchars($array["name"]); $array["forname"] = htmlspecialchars($array["forname"]); $array["lastname"] = htmlspecialchars($array["lastname"]); $array["contactperson"] = htmlspecialchars($array["contactperson"]); $array["phone"] = htmlspecialchars($array["phone"]); $array["fax"] = htmlspecialchars($array["fax"]); $array["mobile"] = htmlspecialchars($array["mobile"]); $array["address"] = htmlspecialchars($array["address"]); $array["web"] = htmlspecialchars($array["web"]); $array["city"] = htmlspecialchars($array["city"]); $array["tags"] = htmlspecialchars($array["tags"]); $array["xemail"] = htmlspecialchars($array["xemail"]); $array["country"] = htmlspecialchars($array["country"]); $array["state"] = htmlspecialchars($array["state"]); $array["tags"] = htmlspecialchars($array["tags"]); $query = "INSERT INTO `newsletterClients` ( `id` , `name` , `contactperson` , `country` ,`state`, `city` , `address` , `phone` , `fax` , `mobile` , `xemail` , `web` , `active` , `forname` , `lastname`,`ondate`,`categoryId`,`tags`) VALUES ( NULL , '".$array["forname"]." ".$array["lastname"]."', '".$array["contactperson"]."', '".$array["country"]."', '".$array["state"]."','".$array["city"]."', '".$array["address"]."', '".$array["phone"]."', '".$array["fax"]."', '".$array["mobile"]."', '".$array["xemail"]."' , '".$array["web"]."', 1 ,'".$array["forname"]."' , '".$array["lastname"]."', NOW(), '".$array["categoryId"]."', '".$array["tags"]."' );"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function newsletter_updateNewsletterClients( $partnerId , $array) { $array["name"] = htmlspecialchars($array["name"]); $array["forname"] = htmlspecialchars($array["forname"]); $array["lastname"] = htmlspecialchars($array["lastname"]); $array["contactperson"] = htmlspecialchars($array["contactperson"]); $array["phone"] = htmlspecialchars($array["phone"]); $array["fax"] = htmlspecialchars($array["fax"]); $array["mobile"] = htmlspecialchars($array["mobile"]); $array["address"] = htmlspecialchars($array["address"]); $array["web"] = htmlspecialchars($array["web"]); $array["city"] = htmlspecialchars($array["city"]); $array["tags"] = htmlspecialchars($array["tags"]); $array["xemail"] = htmlspecialchars($array["xemail"]); $array["country"] = htmlspecialchars($array["country"]); $array["state"] = htmlspecialchars($array["state"]); $array["tags"] = htmlspecialchars($array["tags"]); if($array["name"]=="") $array["name"]=$array["forname"]." ".$array["lastname"]; $query = "UPDATE `newsletterClients` SET `name` = '".$array["name"]."', `contactperson` = '".$array["contactperson"]."', `country` = '".$array["country"]."', `state` = '".$array["state"]."', `city` = '".$array["city"]."', `address` = '".$array["address"]."', `phone` = '".$array["phone"]."', `fax` = '".$array["fax"]."', `mobile` = '".$array["mobile"]."', `xemail` = '".$array["xemail"]."', `web` = '".$array["web"]."', `forname` = '".$array["forname"]."', `lastname` = '".$array["lastname"]."', `tags` = '".$array["tags"]."', `categoryId` = '".$array["categoryId"]."' WHERE `id` =$partnerId LIMIT 1 ;"; mysql_query( $query ) or die(mysql_error()); } //newsletter letrehozasi fuggvenyek function getNewsletter($commandid) { $query="SELECT * FROM newsletter_group WHERE `id`='$commandid'"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } function getNewsletterItems($commandid) { $query="SELECT * FROM `newsletter_ads` WHERE `comandaid`='$commandid'"; $result=mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) { $list[ $row["id"] ] = $row; } return $list; } function getNewsletterItemsCount($commandid) { $query="SELECT * FROM `newsletter_ads` WHERE `comandaid`='$commandid'"; $i=0; $result=mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) { $i++; } return $i; } function stats_newsletterGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `newsletter_group` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function newsletter_delete( $facturaId ) { $query = "DELETE FROM `newsletter_group` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function newsletter_addNewsletter( $userid , $stockid , $number, $dateNow , $dateNowMonth , $clienti, $abonati, $comments, $comments2, $lang, $titlu, $news_link ) { $dateNow = date("Y-m-d"); $dateNowMonthTemp = time() + ( 30 * 24 * 60 * 59); $dateNowMonth = date("Y-m-d",$dateNowMonthTemp); $insertQ = "INSERT INTO `newsletter_group` ( `id` , `number` , `date` , `exp_date` , `tipus1` , `tipus2` , `sent` , `sentdate` , `firstreceive` , `head` , `down` , `up_image` , `lang` , `title` , `news_link` , `special` , `to_send` , `paused`, `userid`, `stockid` ) VALUES (NULL , '$number', '$dateNow' , '$dateNowMonth' , '$clienti', '$abonati', '0', '0000-00-00', '0000-00-00', '$comments', '$comments2', NULL, '$lang', '$titlu', '$news_link', NULL, '0', '0','$userid','$stockid');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function newsletter_addAbonatCategory( $categoryName ) { //megnezni van-e mar a categoria $query="SELECT * FROM `newsletterClients_category` WHERE `categoryName`='$categoryName'"; $result=mysql_query( $query ) or die(mysql_error()); if($result) { $row=mysql_fetch_array($result); if($row["id"]) $categoryName=$categoryName."_".date("Y-m-d H:i:s"); } $insertQ = "INSERT INTO `newsletterClients_category` ( `id` , `categoryName` ) VALUES (NULL ,'$categoryName');"; mysql_query( $insertQ ) or die(mysql_error()); $categoryid = mysql_insert_id (); return $categoryid; } function newsletter_registerItems( $factid , $content ) { $content = addslashes ($content); $query = "INSERT INTO `newsletter_ads` VALUES (NULL, '$factid', '$content');"; mysql_query( $query ) or die(mysql_error()); } function newsletter_unRegisterItems( $factid ) { $query = "DELETE FROM `newsletter_ads` WHERE `newsletter_ads`.`news_id` = '$factid';"; mysql_query( $query ) or die(mysql_error()); $_SESSION["commandForClientAdv"]["edited"]=1; } function newsletter_modFactura( $id , $userid , $stockid , $number, $dateNow , $dateNowMonth , $clienti, $abonati, $comments, $comments2, $lang, $titlu, $news_link) { $content = addslashes ($content); $updateQ = "UPDATE `newsletter_group` SET `userid` = '$userid', `stockid` = '$stockid', `tipus1` = '$clienti', `tipus2` = '$abonati', `head` = '$comments', `down` = '$comments2', `lang` = '$lang', `title` = '$titlu', `news_link` = '$news_link' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function newsletter_getNewsletter( $pageno = -1, $orderby ) { $query = "SELECT * FROM `newsletter_group` ORDER BY id $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function generateDataFromNewsletter( $id ) { $select = "SELECT * FROM `newsletter_group` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function getNewsletterRegisteredItems ($commandId) { $query = "SELECT * FROM `newsletter_ads` WHERE `news_id` = '$commandId' order by id ASC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getNewsletterRegisteredItemsCount ($commandId) { $query = "SELECT * FROM `newsletter_ads` WHERE `news_id` = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function newsletter_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $abonatCategory, $firstserial, $secondserial, $serial, $dataLabel, $location) { //hanyat akar egy oldarra megjeleniteni $count = $_SESSION["settings"]["searchcount"]; ///honnan kezdje $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); //location if($abonatCategory!=0) { $abonatCategorySql = " AND (n.`tipus2` = '$abonatCategory' || n.`tipus3` = '$abonatCategory' || n.`tipus4` = '$abonatCategory' || n.`tipus5` = '$abonatCategory' || n.`tipus6` = '$abonatCategory' || n.`tipus7` = '$abonatCategory')"; } else { $abonatCategorySql = ""; } //$fromDate='2014.07.31'; // filter menut a linkbol kapja valtozokent vagy a cautare postolasakor // itt kezelunk le kulonbozo esteket $query = "SELECT `n`.* FROM `newsletter_group` n WHERE `n`.`title` LIKE '%$searchval%' AND `date` BETWEEN '$fromDate' AND '$toDate' ".$abonatCategorySql." ORDER BY $orderby $ordermode LIMIT $from, $count"; return $query; } function newsletter_searchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows();//$row ["nrFactura"]; } function newsletter_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function getNewsletterSends($newsletter_id) { $query="SELECT DISTINCT to_abonatid FROM `newsletter_sending` WHERE `newsletterId`='$newsletter_id'"; $i=0; $result=mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) { $i++; } return $i; } function newsletter_getNewsletterDestinations( $type1 , $type2 , $ondate ) { $ondate = mysql_nextDay($ondate); if($type1!=1) { $query = "SELECT * FROM `newsletterClients` WHERE `ondate` < '$ondate' AND `categoryId` = '$type2' ORDER BY `name`"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $counter=0; while( $row = mysql_fetch_array( $result ) ) $counter++; } if($type1==1) { $query = "SELECT `p`.*, `e`.* FROM `partners` p, `partners_email` e WHERE `e`.`email`!='' AND `p`.`id` = `e`.`clientid` ORDER BY `p`.`id`"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $counter++; } return $counter; } function newsletter_statsSimple($newsletter_id) { $res = mysql_query("select * from newsletter_stats where move='1' and newsletter_id='$newsletter_id' order by abonat_id ASC"); if ($res) { $readuri=0; while($rw = mysql_fetch_array($res)) { $abonat_id=$rw["abonat_id"]; if($abonat_id!=$regi_abonat_id) $readuri++; $regi_abonat_id=$abonat_id; } } $regi_abonat_id=NULL; $res = mysql_query("select * from newsletter_stats where move='1' and newsletter_id='$newsletter_id' order by abonat_id ASC"); if ($res) { $afisari=0; while($rw = mysql_fetch_array($res)) { $abonat_id=$rw["abonat_id"]; $afisari++; } } $regi_abonat_id=NULL; $res = mysql_query("select * from newsletter_stats where move='2' and newsletter_id='$newsletter_id' order by abonat_id ASC"); if ($res) { $clickuri=0; while($rw = mysql_fetch_array($res)) { $abonat_id=$rw["abonat_id"]; $clickuri++; } } $stat["readuri"]=$readuri; $stat["afisari"]=$afisari; $stat["clickuri"]=$clickuri; return $stat; } function newsletter_statsSimpleForAbonat($abonat_id,$newsletterId) { if($newsletterId!=0) $newsletterIdSql=" AND `newsletter_id`='$newsletterId'"; else $newsletterIdSql=""; $res = mysql_query("select * from newsletter_stats where move='1' and abonat_id='$abonat_id'".$newsletterIdSql." order by abonat_id ASC"); if ($res) { $readuri=0; while($rw = mysql_fetch_array($res)) { $abonat_id_while=$rw["newsletter_id"]; if($abonat_id_while!=$regi_abonat_id) $readuri++; $regi_abonat_id=$abonat_id_while; } } $regi_abonat_id=NULL; $res = mysql_query("select * from newsletter_stats where move='1' and abonat_id='$abonat_id'".$newsletterIdSql." order by abonat_id ASC"); if ($res) { $afisari=0; while($rw = mysql_fetch_array($res)) { $abonat_id_while=$rw["newsletter_id"]; $afisari++; } } $regi_abonat_id=NULL; $res = mysql_query("select * from newsletter_stats where move='2' and abonat_id='$abonat_id'".$newsletterIdSql." order by abonat_id ASC"); if ($res) { $clickuri=0; while($rw = mysql_fetch_array($res)) { $abonat_id_while=$rw["newsletter_id"]; $clickuri++; } } $stat["readuri"]=$readuri; $stat["afisari"]=$afisari; $stat["clickuri"]=$clickuri; return $stat; } function newsletter_publishNewsletter($newsletterid,$forTotalRecipients) { $updateQ = "UPDATE `newsletter_group` SET `sent` = '$forTotalRecipients' WHERE `id`='$newsletterid' LIMIT 1"; mysql_query( $updateQ ) or die(mysql_error()); $updateQ = "UPDATE `newsletter_group` SET `to_send` = '1' WHERE `id`='$newsletterid' LIMIT 1"; mysql_query( $updateQ ); } function newsletter_searchStat( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function newsletterStat_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu_tip, $firstserial, $secondserial, $serial, $filter_menu_click_tip, $newsletterId) { //hanyat akar egy oldarra megjeleniteni $count = $_SESSION["settings"]["searchcount"]; ///honnan kezdje $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); // filter menut a linkbol kapja valtozokent vagy a cautare postolasakor if($filter_menu_tip!="") { $filterTipSql = "AND `n`.`move`='$filter_menu_tip'"; } else { $filterTipSql=""; } $counterStat=0; $list = newsletter_stat_generateClickTipList($newsletterId); if( $list ) foreach( $list as $key => $xvalue ) { $counterStat++; if($counterStat==$filter_menu_click_tip) $filter_menu_click_tip_value=$xvalue["from_link"]; } if($filter_menu_click_tip_value!="") { $filterTipClickSql = "AND `n`.`from_link`='$filter_menu_click_tip_value'"; } else { $filterTipClickSql=""; } // itt kezelunk le kulonbozo esteket $query = "SELECT `n`.*, `c`.`name`, `c`.`xemail` FROM `newsletter_stats` n, `newsletterClients` c WHERE (`c`.`name` LIKE '%$searchval%' OR `c`.`forname` LIKE '%$searchval%' OR `c`.`lastname` LIKE '%$searchval%' OR `c`.`xemail` LIKE '%$searchval%') AND `date_time` BETWEEN '$fromDate' AND '$toDate' ".$filterTipSql." ".$filterTipClickSql." AND `n`.`abonat_id` = `c`.`id` AND `n`.`newsletter_id` = '$newsletterId' GROUP BY `n`.`id` ORDER BY $orderby $ordermode LIMIT $from, $count"; return $query; } function newsletter_stat_generateClickTipList($newsletterId) { $query="SELECT DISTINCT(`from_link`),`id` FROM `newsletter_stats` WHERE `move`='2' AND `newsletter_id`='$newsletterId' GROUP BY `from_link`"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $statsClick[ $row[ "id" ] ] = $row; } return $statsClick; } function newsletter_cleanDatabaseFromDezabonare() { $query = "SELECT * FROM `newsletter_stats` WHERE `from_link` LIKE CONVERT( _utf8 '%dezabonare%' USING latin1 ) COLLATE latin1_swedish_ci"; $results = mysql_query( $query ) or die(mysql_error()); if( $results ) { while( $row = mysql_fetch_array( $results ) ) { $newsletter_dezabonare_from_email = $row["from_email"]; $querySelect = "SELECT * FROM `newsletterClients` where `xemail` = '$newsletter_dezabonare_from_email'"; $resultsSelect = mysql_query( $querySelect ); if( mysql_affected_rows() > 0 ) { while( $row = mysql_fetch_array( $resultsSelect ) ) { echo "Client dezabonat, sau nedorit: ".$row["xemail"]."! Sterg din baze de date!
"; newsletter_addNewsletterClientsBlackList($row); $queryDel = "DELETE FROM `newsletterClients` where `xemail`='$newsletter_dezabonare_from_email'"; mysql_query( $queryDel ) or die(mysql_error()); } } } } } function newsletter_cleanDatabaseBlackList() { $querySelect = "SELECT `b`.*, `c`.* FROM `newsletterClientsBlackList` b, `newsletterClients` c where `b`.`xemail` = `c`.`xemail` "; $resultsSelect = mysql_query( $querySelect ); if( $resultsSelect ) { while( $row = mysql_fetch_array( $resultsSelect ) ) { $blackEmail = $row["xemail"]; echo "Client aflat la black list: ".$row["xemail"]."! Sterg din baza de date!
"; $queryDel = "DELETE FROM `newsletterClients` where `xemail`='$blackEmail'"; mysql_query( $queryDel ) or die(mysql_error()); } } } function newsletter_cleanDatabaseCategoryDouble($categoryId) { $querySelect = "SELECT DISTINCT * FROM `newsletterClients` where `categoryId`='$categoryId' group by `xemail` ASC"; $resultsSelect = mysql_query( $querySelect ) or die(mysql_error()); if( $resultsSelect ) { while( $row = mysql_fetch_array( $resultsSelect ) ) { $toCleanEmail = $row["xemail"]; $CleanId = $row["id"]; $queryCleanSelect = "SELECT * FROM `newsletterClients` where `xemail`='$toCleanEmail' and `id`!='$CleanId' and `categoryId`='$categoryId' order by `xemail` ASC"; $resultsCleanSelect = mysql_query( $queryCleanSelect ); if( mysql_affected_rows() > 0 ) { while( $rowClean = mysql_fetch_array( $resultsCleanSelect ) ) { $toClean = $rowClean["xemail"]; $toCleanId = $rowClean["id"]; echo "Client adaugat dublu: ".$rowClean["xemail"]."! Sterg dublurile!
"; $queryDel = "DELETE FROM `newsletterClients` where `id`!='$CleanId' and `categoryId`='$categoryId' and `xemail`='$toClean'"; mysql_query( $queryDel ) or die(mysql_error()); } } } } } function newsletter_cleanDatabaseSpaces() { $querySelect = "SELECT * FROM `newsletterClients` where `xemail` LIKE '% %' "; $resultsSelect = mysql_query( $querySelect ); if( $resultsSelect ) { while( $row = mysql_fetch_array( $resultsSelect ) ) { $blackEmail = $row["xemail"]; echo "Client cu email nevalid: ".$row["xemail"]."! Sterg din baza de date!
"; $queryDel = "DELETE FROM `newsletterClients` where `xemail`='$blackEmail'"; mysql_query( $queryDel ) or die(mysql_error()); } } } function newsletter_addNewsletterClientsBlackList( $array ) { $array["name"] = htmlspecialchars($array["name"]); $array["person"] = htmlspecialchars($array["person"]); $array["address"] = htmlspecialchars($array["address"]); $array["city"] = htmlspecialchars($array["city"]); $array["orcnumber"] = htmlspecialchars($array["orcnumber"]); $array["phone"] = htmlspecialchars($array["phone"]); $array["fax"] = htmlspecialchars($array["fax"]); $array["mobile"] = htmlspecialchars($array["mobile"]); $array["xemail"] = htmlspecialchars($array["xemail"]); $array["web"] = htmlspecialchars($array["web"]); $array["forname"] = htmlspecialchars($array["forname"]); $array["lastname"] = htmlspecialchars($array["lastname"]); $array["cnp"] = htmlspecialchars($array["cnp"]); $array["codpostal"] = htmlspecialchars($array["codpostal"]); $query = "INSERT INTO `newsletterClientsBlackList` ( `id` , `name` , `contactperson` , `country` ,`state`, `city` , `address` , `phone` , `fax` , `mobile` , `xemail` , `web` , `active` , `forname` , `lastname`,`ondate`,`categoryId`) VALUES ( NULL , '".$array["forname"]." ".$array["lastname"]."', '".$array["person"]."', '".$array["country"]."', '".$array["state"]."','".$array["city"]."', '".$array["address"]."', '".$array["phone"]."', '".$array["fax"]."', '".$array["mobile"]."', '".$array["xemail"]."' , '".$array["web"]."', 1 ,'".$array["forname"]."' , '".$array["lastname"]."', NOW(), '".$array["categoryId"]."' );"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } //newsletter modul vege function expenses_registerItems( $expensid , $price , $natprice , $quantity , $rowName, $cursValue, $date ) { if ($date=='') $date="NOW()"; else $date="DATE_ADD('".$date."', INTERVAL 1 SECOND)"; //price = tva nelkuli egyeduli ar - quantity nelkul //natprice = tva ertek $query = "INSERT INTO `expenses_items` VALUES (NULL, '$expensid', '$price', '$natprice' , '$quantity', '$rowName',$date, '$cursValue');"; mysql_query( $query ) or die($query." ".mysql_error()); } function expenses_getExpensesRegisteredItems( $expensid ) { $query = "SELECT * FROM `expenses_items` WHERE `expens_id`='$expensid' AND `price` > 0"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) $expenses[ $row["id"] ] = $row; return $expenses; } } function expenses_unRegisterItems( $expensid ) { $query = "DELETE FROM `expenses_items` WHERE `expenses_items`.`expens_id` = '$expensid';"; mysql_query( $query ) or die(mysql_error()); } function factura_getFacturiItems($factid) { $query=" SELECT * FROM `facturi_items` WHERE `facturi_items`.`factid`='$factid' order by `facturi_items`.`id` ASC"; $result=mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function factura_getFacturiItemsCount($factid) { $query=" SELECT * FROM `facturi_items` WHERE `facturi_items`.`factid`='$factid' order by `facturi_items`.`id` ASC"; $result=mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $counter; } ///////////nyelvek kiolvasasa////////////// function getLanguages() { $res=mysql_query("SELECT * FROM `language` WHERE active='1' order by `id`"); if($res) { while($row=mysql_fetch_array($res)) { $nyelvs[ $row["id"] ] = $row; } return $nyelvs; } else return NULL; } function model_createModellang( $name ,$lang,$depid) { if( model_modelExists( $name ) == 0 ) { $query = "INSERT INTO `models` ( `id` , `name` ,`ondate`,`lang`,`departament`) VALUES (NULL , '$name',NOW(),'$lang','$depid');"; mysql_query( $query ) or die(mysql_error()); $_SESSION["msg_stat"] = "Model ".$name."created !"; return true; } else $_SESSION["msg_err"] = getTraducere("Model name already exists",$_SESSION["settings"]["default_lang"])." !"; return false; } //CRM Modul function generate_calendar($year, $month, $days = array(), $day_name_length = 3, $month_href = NULL, $first_day = 0, $pn = array(), $dayCal, $specialColor){ $first_of_month = gmmktime(0,0,0,$month,1,$year); #remember that mktime will automatically correct if invalid dates are entered # for instance, mktime(0,0,0,12,32,1997) will be the date for Jan 1, 1998 # this provides a built in "rounding" feature to generate_calendar() $day_names = array(); #generate all the day names according to the current locale for($n=0,$t=(3+$first_day)*86400; $n<7; $n++,$t+=86400) #January 4, 1970 was a Sunday $day_names[$n] = ucfirst(gmstrftime('%A',$t)); #%A means full textual day name list($month, $year, $month_name, $weekday) = explode(',',gmstrftime('%m,%Y,%B,%w',$first_of_month)); $weekday = ($weekday + 7 - $first_day) % 7; #adjust for $first_day $title = htmlentities(ucfirst($month_name)).' '.$year; #note that some locales don't capitalize month and day names #Begin calendar. Uses a real . See http://diveintomark.org/archives/2002/07/03 @list($p, $pl) = each($pn); @list($n, $nl) = each($pn); #previous and next links, if applicable if($p) $p = ''.($pl ? ''.$p.'' : $p).' '; if($n) $n = ' '.($nl ? ''.$n.'' : $n).''; $calendar = ''."\n". '\n"; if($day_name_length){ #if the day names should be shown ($day_name_length > 0) #if day_name_length is >3, the full name of the day will be printed foreach($day_names as $d) $calendar .= ''; $calendar .= "\n"; } if($weekday > 0) $calendar .= ''; #initial 'empty' days for($day=1,$days_in_month=gmdate('t',$first_of_month); $day<=$days_in_month; $day++,$weekday++){ if($weekday == 7){ $weekday = 0; #start a new week $calendar .= "\n"; } if($day<=9) $spaces=" "; else $spaces=""; if($dayCal==$day) { $coloring1=""; $coloring2=""; } else { $coloring1=""; $coloring2=""; } if(isset($days[$day]) and is_array($days[$day])){ @list($link, $classes, $content) = $days[$day]; if(is_null($content)) $content = $day; $calendar .= ''; } else $calendar .= ''; } if($weekday != 7) $calendar .= ''; #remaining "empty" days return $calendar."\n
'.$p.($month_href ? ''.$title.'' : $title).$n."
'.htmlentities($day_name_length < 4 ? substr($d,0,$day_name_length) : $d).'
 
' : '>'). ($link ? $spaces.''.$coloring1.$content.$coloring2.'' : $content).''.$spaces.$coloring1.$day.$coloring2.' 
\n"; } //partner types function partner_getPartnerTypeId( $typeid ) { $query = "SELECT * FROM `partners_type` WHERE `id`= '$typeid' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { return $stock = mysql_fetch_array( $result ); } else return NULL; } function partner_getPartnerType() { $selectQ = "SELECT * FROM `partners_type`"; $result = mysql_query( $selectQ ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; } return NULL; } function crm_listRatingCategory() { $query = "SELECT * FROM `crm_partnerClassificationCategory` ORDER by `id` asc"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $cities[ $row["id"] ] = $row; return $cities; } function crm_insertRatingCategory($name) { //megnezem van e mar city $query = "SELECT `id` FROM `crm_partnerClassificationCategory` WHERE `name` LIKE '$name%'"; $result = mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)!=0) { $row=mysql_fetch_array($result); $ratingmax=$row["id"]; } else { $queryc="SELECT MAX(`id`) as maxid FROM `crm_partnerClassificationCategory`"; $result=mysql_query($queryc); $res=mysql_fetch_array($result); $ratingmax=$res["maxid"]+1; $query="INSERT INTO `crm_partnerClassificationCategory` values('$ratingmax','$name')"; mysql_query( $query ) or die(mysql_error()); } return $ratingmax; } function crm_getRating($ratingid,$clientid) { $query="SELECT * FROM `crm_partnerClassification` WHERE `clientid`='$clientid' AND `categoryId`='$ratingid'"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } function crm_updateRatings($POST,$clientid,$userid,$stockid) { //egyszer kitorolom az osszes ratinget a kliensrol $delQuery="DELETE FROM `crm_partnerClassification` WHERE `clientid`='$clientid'"; mysql_query($delQuery); $ratingClassification = crm_listRatingCategory(); $ratingCounter=0; if($ratingClassification) foreach( $ratingClassification as $keyRc => $valueRc ) { $categoryId = $valueRc["id"]; $value = "starry".$ratingCounter; $valueRating = $POST[$value]; $insertQuery="INSERT INTO `crm_partnerClassification` values ('','$userid','$stockid','$clientid',NOW(),'$categoryId','$valueRating');"; mysql_query($insertQuery) or die(mysql_error()); $ratingCounter++; } } //contact szemelyek function crm_addPartnerContact( $clientid, $userid, $stockid ) { $query = "INSERT INTO `partners_contact` VALUES (NULL , '$clientid','$userid','$stockid',NOW(),NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,1,'','','');"; mysql_query( $query ) or die(mysql_error()); } function crm_addPartnerContactDirect( $clientid , $userid, $stockid, $forname, $lastname) { $query = "INSERT INTO `partners_contact` VALUES (NULL , '$clientid','$userid','$stockid',NOW(),'$forname','$lastname',NULL,NULL,NULL,NULL,NULL,NULL,1,'','','');"; $result=mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function crm_addPartnerContactDirectFromFactura( $clientid , $userid, $stockid, $forname, $lastname, $buletinSeria, $buletinNr, $buletinElib) { $query = "INSERT INTO `partners_contact` VALUES (NULL , '$clientid','$userid','$stockid',NOW(),'$forname','$lastname',NULL,NULL,NULL,NULL,NULL,NULL,1,$buletinSeria,$buletinNr,$buletinElib);"; $result=mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function crm_updatePartnerContacts( $clientid , $array) { $query2="SELECT * FROM `partners_contact` WHERE `clientid`='$clientid' order by id"; $result2=mysql_query( $query2 ) or die(mysql_error()); $j=0; while( $row=mysql_fetch_array($result2) ) { $post_forname = htmlspecialchars($array["fornamePC$j"]); $post_lastname = htmlspecialchars($array["lastnamePC$j"]); $post_hrType = htmlspecialchars($array["hrTypePC$j"]); $post_decisionForce = htmlspecialchars($array["decisionForcePC$j"]); $post_departament = htmlspecialchars($array["departamentPC$j"]); $post_email = htmlspecialchars($array["xemailPC$j"]); $post_tel = htmlspecialchars($array["telPC$j"]); $post_telfix = htmlspecialchars($array["telfixPC$j"]); $post_activ = htmlspecialchars($array["activ$j"]); $post_buletinSeria = htmlspecialchars($array["buletinSeria$j"]); $post_buletinNr = htmlspecialchars($array["buletinNr$j"]); $post_buletinElib = htmlspecialchars($array["buletinElib$j"]); $mailid = $row["id"]; $query = "UPDATE `partners_contact` SET `forname`='$post_forname',`lastname`='$post_lastname',`hrType`='$post_hrType', `decisionForce`='$post_decisionForce',`activ`='$post_activ',`departament`='$post_departament',`email`='$post_email',`tel`='$post_tel',`telfix`='$post_telfix',`buletinSeria`='$post_buletinSeria',`buletinNr`='$post_buletinNr',`buletinElib`='$post_buletinElib' WHERE `clientid`='$clientid' AND `id`='$mailid'"; mysql_query( $query ) or die(mysql_error()); $j++; } } function crm_getContacts($clientid) { $query="SELECT * FROM `partners_contact` WHERE `clientid`='$clientid'"; $result=mysql_query( $query ) or die(mysql_error()); return $result; } function crm_getContact($contactid) { $query="SELECT * FROM `partners_contact` WHERE `id`='$contactid'"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } //autok a klienseknek function crm_addPartnerCar( $clientid, $userid, $stockid ) { $query = "INSERT INTO `partners_cars` VALUES (NULL , '$clientid','$userid','$stockid',NOW(),NULL,NULL,1);"; mysql_query( $query ) or die(mysql_error()); } function crm_addPartnerCarDirect( $clientid , $userid, $stockid, $CarName, $Number) { $query = "INSERT INTO `partners_cars` VALUES (NULL , '$clientid','$userid','$stockid',NOW(),'$CarName','$Number',1);"; $result=mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function crm_updatePartnerCars( $clientid , $array) { $query2="SELECT * FROM `partners_cars` WHERE `clientid`='$clientid' order by id"; $result2=mysql_query( $query2 ) or die(mysql_error()); $j=0; while( $row=mysql_fetch_array($result2) ) { $post_CarName = htmlspecialchars($array["CarName$j"]); $post_Number = htmlspecialchars($array["Number$j"]); $post_activ = htmlspecialchars($array["activCar$j"]); $mailid = $row["id"]; $query = "UPDATE `partners_cars` SET `CarName`='$post_CarName',`Number`='$post_Number',`activ`='$post_activ' WHERE `clientid`='$clientid' AND `id`='$mailid'"; mysql_query( $query ) or die(mysql_error()); $j++; } } function crm_getCars($clientid) { $query="SELECT * FROM `partners_cars` WHERE `clientid`='$clientid'"; $result=mysql_query( $query ) or die(mysql_error()); return $result; } function crm_getCar($contactid) { $query="SELECT * FROM `partners_cars` WHERE `id`='$contactid'"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } function crm_getAllClientsProvidersPotentials() { $query = "SELECT * FROM `partners` ORDER BY `name`"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { while( $row = mysql_fetch_array( $result ) ) $list[ $row["id"] ] = $row; return $list; }else return NULL; } function crm_getEventCategories() { $select = "SELECT * FROM `crm_eventCategory` ORDER by `name`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $infos[ $row["id"] ] = $row; } return $infos; } function crm_getEventTypes() { $select = "SELECT * FROM `crm_eventType` ORDER by `name`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $infos[ $row["id"] ] = $row; } return $infos; } function crm_insertEventCategory($name) { //megnezem van e mar city $query = "SELECT `id` FROM `crm_eventCategory` WHERE `name` LIKE '$name%'"; $result = mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)!=0) { $row=mysql_fetch_array($result); $citymax=$row["id"]; } else { $queryc="SELECT MAX(`id`) as maxid FROM `crm_eventCategory`"; $result=mysql_query($queryc); $res=mysql_fetch_array($result); $citymax=$res["maxid"]+1; $query="INSERT INTO `crm_eventCategory` values('$citymax','$name')"; mysql_query( $query ) or die(mysql_error()); } return $citymax; } function crm_insertEventType($name) { //megnezem van e mar city $query = "SELECT `id` FROM `crm_eventType` WHERE `name` LIKE '$name%'"; $result = mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)!=0) { $row=mysql_fetch_array($result); $citymax=$row["id"]; } else { $queryc="SELECT MAX(`id`) as maxid FROM `crm_eventType`"; $result=mysql_query($queryc); $res=mysql_fetch_array($result); $citymax=$res["maxid"]+1; $query="INSERT INTO `crm_eventType` values('$citymax','$name')"; mysql_query( $query ) or die(mysql_error()); } return $citymax; } function crm_getEventParticipants($eventid) { $select = "SELECT * FROM `crm_events_participants` WHERE `eventId`='$eventid' ORDER by `id` ASC"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $infos[ $row["id"] ] = $row; } return $infos; } function crm_getEventParticipantsHasStatus($eventid) { $select = "SELECT * FROM `crm_events_participants` WHERE `eventId`='$eventid' AND `status`!='0' ORDER by `id` ASC"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $infos[ $row["id"] ] = $row; } return $infos; } function crm_addevent( $array , $followUpEventId) { foreach( $array as $key => $xvalue ) $$key = $xvalue; $dateValue=$dataeveniment." ".$dataora.":".$dataminut; $deadlineValue=$deadlineeveniment." ".$deadlineora.":".$deadlineminut; $query = "INSERT INTO `crm_events` ( `id` , `ondate` , `userid` , `stockid` , `categoryId` , `clientid` , `contactid` , `dateFor` ,`duration`,`deadline`,`eventType`, `observation`,`priority`,`state`,`eventAvertTime`,`asignedTo`,`asignedToCar`,`oportunityValue`,`onvaluta`,`cityId`,`judetId`,`address`,`products`,`followUpEventId`,`rezolvareca`,`asignedToComanda`,`visibility`, `dosarid`) VALUES ( NULL , NOW(), '".$_SESSION["user"]["id"]."', '".$_SESSION["user"]["defstock"]."', '$eventcatid', '$clientid', '$contactsid', '$dateValue','$durata','$deadlineValue','$eventtcatid','$observatii','$starry0','$eventstatus','$avertizare','$hrid','$carid','$oportunityvalue','$onValuta','$where','$wherej','$address','$serviciiproduse','$followUpEventId','$rezolvareca','".command_getCommandIdFromNr($comandanr)."','$visibility','$dosarid');"; mysql_query( $query ) or die(mysql_error()); if($followUpEventId!=0) crm_modeventForFollowUp( $followUpEventId ); return mysql_insert_id(); } function crm_addEventsParticipants( $eventId , $array , $status, $kivetel, $kivetelid) { $elment="SELECt * FROM `crm_events_participants` WHERE `eventId`='$eventId'"; $res=mysql_query($elment)or die(mysql_error()); $mentes=array(); while ($row=mysql_fetch_array($res)){ $mentes[$row['hrId']]=$row; } $hrek=array_keys($mentes); $query = "DELETE FROM `crm_events_participants` WHERE `eventId`='$eventId'"; mysql_query( $query ) or die(mysql_error()); $addedHrs = $array; if( $addedHrs ) foreach( $addedHrs as $keyHrs => $valueHrs ) { //hogyha nem nekem keszult, csak resztvevo vagyok if (in_array($valueHrs,$hrek)) if ($kivetelid==$valueHrs){// ha van kivetel, akkor a kivetelnek a kiveteles erteket menti $stat=$kivetel; $date='NOW()'; }else{ // ha nincs kivetel, akkor lementi a mentetteket $stat=$mentes[$valueHrs]['status']; $date="'".$mentes[$valueHrs]['status_date']."'"; } else{ if ($kivetel==NULL){ $stat=0; $date="''"; }else{ $stat=$status; $date='NOW()'; } } $query = "INSERT INTO `crm_events_participants` ( `id` , `eventId` , `hrId`, `status`,`status_date`) VALUES ( NULL , '$eventId', '$valueHrs','$stat',$date);"; mysql_query( $query ) or die(mysql_error()); } } function crm_getPartiStatus($hrid,$eventid){ $query="SELECT `status` FROM `crm_events_participants` WHERE `hrId`='$hrid' AND `eventId`='$eventid'"; $result=mysql_fetch_array(mysql_query($query)); return $result['status']; } function crm_modevent( $eventId , $array ) { foreach( $array as $key => $xvalue ) $$key = $xvalue; $eventData = crm_getEvent( $eventid); $dateValue=$dataeveniment." ".$dataora.":".$dataminut; $deadlineValue=$deadlineeveniment." ".$deadlineora.":".$deadlineminut; if($eventData["dateFor"]!=$dateValue || $eventData["deadline"]!=$deadlineValue) { $query = "DELETE FROM `avertizare_avertizariItems` WHERE `avertizare_id`='$eventId' AND `mod_id`='12'"; mysql_query( $query ) or die(mysql_error()); } $update = "UPDATE `crm_events` SET `stockid` = '".$_SESSION["user"]["defstock"]."', `categoryId` = '$eventcatid', `clientid` = '$clientid', `contactid` = '$contactsid', `dateFor` = '$dateValue', `duration` = '$durata', `deadline` = '$deadlineValue', `eventType` = '$eventtcatid', `observation` = '$observatii', `priority` = '$starry0', `state` = '$eventstatus', `eventAvertTime` = '$avertizare', `asignedTo` = '$hrid', `asignedToCar` = '$carid', `oportunityValue` = '$oportunityvalue', `onvaluta` = '$onValuta', `cityId` = '$where', `judetId` = '$wherej', `products` = '$serviciiproduse', `rezolvareca` = '$rezolvareca', `address` = '$address', `asignedToComanda` = '".command_getCommandIdFromNr($comandanr)."', `visibility` = '$visibility', `dosarid` = '$dosarid' WHERE `crm_events`.`id` ='$eventId' LIMIT 1 ;"; mysql_query( $update ) or die(mysql_error()); } function crm_modeventForFollowUp( $eventId ) { $eventData = crm_getEvent( $eventid); $dateValue=$dataeveniment." ".$dataora.":".$dataminut; $deadlineValue=$deadlineeveniment." ".$deadlineora.":".$deadlineminut; if($eventData["dateFor"]!=$dateValue || $eventData["deadline"]!=$deadlineValue) { $query = "DELETE FROM `avertizare_avertizariItems` WHERE `avertizare_id`='$eventId' AND `mod_id`='12'"; mysql_query( $query ) or die(mysql_error()); } $update = "UPDATE `crm_events` SET `state` = '2' WHERE `crm_events`.`id` ='$eventId' LIMIT 1 ;"; mysql_query( $update ) or die(mysql_error()); } function crm_getEvent( $eventId ) { $query = "SELECT * FROM `crm_events` WHERE `id`='$eventId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); if( $result ) { $row = mysql_fetch_array( $result ); return $row; } else return NULL; } function crm_queryEventGenerator( $page , $orderby , $ordermode , $fromDate , $toDate , $searchval, $searchCriteria , $filter_menu,$rezolvat, $hrid) { //megnezem, hogy a user nek melyik alkalmazott felel meg, es kiveszem az idjat $u=hr_getAdminUserAsoc($hrid); if($hrid!=NULL && $hrid!=0) $userLimitQuery=" AND (e.`userid`='".$u."' OR `asignedTo`='$hrid' OR `e`.`id` IN(SELECT `eventId` FROM `crm_events_participants` WHERE `hrId`='$hrid') )"; else $userLimitQuery=""; $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; //filter_menu if($filter_menu) $filterSql = " AND e.`categoryId` = '$filter_menu'"; if($rezolvat!=""&&$rezolvat!="0") $filterSql.=" AND e.state='$rezolvat' "; $timeLimitQuery=" AND e.`dateFor` BETWEEN '$fromDate' AND '$toDate' "; if($searchCriteria=="name") { $query = "SELECT e.* FROM `crm_events` e, `partners` p WHERE `e`.`id` != '0' ".$timeLimitQuery.$userLimitQuery." AND p.`name` LIKE '%$searchval%' AND e.`clientid` = p.`id` ".$filterSql." ORDER BY e.`$orderby` $ordermode LIMIT $from,$howmany"; } else { $query = "SELECT * FROM `crm_events` e WHERE `e`.`id` != '0' ".$timeLimitQuery.$userLimitQuery.$searchPlus." ".$filterSql." ORDER BY $orderby $ordermode LIMIT $from,$howmany"; } return $query; } function crm_queryEventGeneratorActual( $page , $orderby , $ordermode , $fromDate , $toDate , $searchval, $searchCriteria , $filter_menu, $hrid) { //megnezem, hogy a user nek melyik alkalmazott felel meg, es kiveszem az idjat if($hrid!=NULL && $hrid!=0) $userLimitQuery=" AND `asignedTo`='$hrid' "; else $userLimitQuery=" AND `asignedTo`='0'"; $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; //filter_menu if($filter_menu) $filterSql = " AND e.`categoryId` = '$filter_menu'"; if($searchval) $timeLimitQuery=""; else $timeLimitQuery=" AND e.`dateFor` <= '$toDate' "; if($searchCriteria=="name") { $query = "SELECT e.* FROM `crm_events` e, `partners` p WHERE (`e`.`id` != '0' ".$timeLimitQuery.$userLimitQuery." AND `state`!='2' AND `state`!='4' AND `state`!='6' AND p.`name` LIKE '%$searchval%' AND e.`clientid` = p.`id` ".$filterSql.") OR (`e`.`id` != '0' ".$timeLimitQuery." AND `state`!='2' AND `state`!='4' AND `state`!='6' AND p.`name` LIKE '%$searchval%' AND e.`clientid` = p.`id` ".$filterSql." AND`e`.`id` in (SELECT `eventId` FROM `crm_events_participants` WHERE `hrId`='$hrid') ) ORDER BY e.`$orderby` $ordermode LIMIT $from,$howmany"; } else { $query = "SELECT * FROM `crm_events` e WHERE (`e`.`id` != '0' ".$timeLimitQuery.$userLimitQuery.$searchPlus." ".$filterSql." AND `state`!='2' AND `state`!='4' AND `state`!='6') OR (`e`.`id` != '0' ".$timeLimitQuery.$searchPlus." ".$filterSql." AND `state`!='2' AND `state`!='4' AND `state`!='6' AND `e`.`id` in (SELECT `eventId` FROM `crm_events_participants` WHERE `hrId`='$hrid') ) ORDER BY $orderby $ordermode LIMIT $from,$howmany"; } return $query; } function crm_getStatus($id){ $query="SELECT * FROM `crm_eventStatus` WHERE `eventId`='$id'"; $result=mysql_query( $query ) or die(mysql_error()); $lista=array(); while ($row=mysql_fetch_array($result)) $lista[]=$row; return $lista; } function crm_getEvents( $query ) { $results = mysql_query( $query ) or die(mysql_error()); if( $results ) { while( $row = mysql_fetch_array( $results ) ) $bons[ $row["id"] ] = $row; return $bons; } return NULL; } function crm_getEventsSearchCount( $query ) { $pos = strpos( $query , "LIMIT" ); if($pos!==FALSE) $query = substr( $query , 0 , $pos ); $result = mysql_query( $query ) or die(mysql_error()); return count( $result ); } function crm_getCompaniesAsArray() { $query="SELECT `id`,`name` FROM `partners`"; $result=mysql_query( $query ) or die(mysql_error()); $array; while($row=mysql_fetch_array($result)) { $array[$row['id']]=$row['name']; } return $array; } function crm_getNotesCategoriesAsArray() { $query="SELECT `id`,`name` FROM `crm_notesCategory`"; $result=mysql_query( $query ) or die(mysql_error()); $array; while($row=mysql_fetch_array($result)) { $array[$row['id']]=$row['name']; } return $array; } function crm_getNotesCategory($categoryId) { $query="SELECT `id`,`name` FROM `crm_notesCategory` WHERE `id`='$categoryId'"; $result=mysql_query( $query ) or die(mysql_error()); $array; $row=mysql_fetch_array($result); return $row["name"]; } function crm_saveNote($clientid,$eventid,$catid,$note,$userid,$stockid,$title) { $query="INSERT INTO `crm_notes`(`ondate`,`clientid`,`eventid`,`categoryId`,`note`,`userid`,`stockid`,`title`) VALUES (NOW(),'$clientid','$eventid','$catid','$note','$userid','$stockid','$title')"; $result=mysql_query($query) or die(mysql_error()); } function crm_getNotes($clientid,$eventid) { if($clientid!=0) $clientFilter=" AND `clientid`='$clientid'"; else $clientFilter=""; if($eventid!=0) $eventFilter=" AND `eventid`='$eventid'"; else $eventFilter=""; $query="SELECT * FROM `crm_notes` WHERE `id`!=0 ".$clientFilter." ".$eventFilter." order by `ondate` DESC"; $result=mysql_query( $query ) or die(mysql_error()); $array; while($row=mysql_fetch_array($result)) { $array[$row['id']]=$row; } return $array; } function crm_getNotesCounter($clientid,$eventid) { if($clientid!=0) $clientFilter=" AND `clientid`='$clientid'"; else $clientFilter=""; if($eventid!=0) $eventFilter=" AND `eventid`='$eventid'"; else $eventFilter=""; $query="SELECT * FROM `crm_notes` WHERE `id`!=0 ".$clientFilter." ".$eventFilter." order by `ondate` DESC"; $result=mysql_query( $query ) or die(mysql_error()); $counter=0; while($row=mysql_fetch_array($result)) { $counter++; } return $counter; } function crm_queryEventGeneratorForClient( $orderby , $ordermode , $clientid ) { //megnezem, hogy a user nek melyik alkalmazott felel meg, es kiveszem az idjat $query = "SELECT * FROM `crm_events` e WHERE `e`.`id` != '0' AND `clientid` = '$clientid' ORDER BY $orderby $ordermode "; return $query; } function crm_queryEventGeneratorForCommand( $orderby , $ordermode , $commandid ) { $query = "SELECT * FROM `crm_events` e WHERE `e`.`id` != '0' AND `asignedToComanda` = '$commandid' ORDER BY $orderby $ordermode "; return $query; } function crm_AvertEvent() { $query = "SELECT * FROM `crm_events` WHERE `state`!='2' AND `state`!='4' AND `state`!='6'"; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { if($row["dateFor"]!="0000-00-00 00:00:00") { $date=$row["dateFor"]; $nextWeek = time() + (1 * 1 * 1 * $row["eventAvertTime"] * 59); $todayDate = date("Y-m-d H:i:s",$nextWeek); $day=subtract_datesForMinutes($date, $todayDate); if($day>=0) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=12;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function crm_AvertEventDeadline() { $query = "SELECT * FROM `crm_events` WHERE `state`!='2' AND `state`!='4' AND `state`!='6'"; $result = mysql_query( $query ) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array($result) ) { if($row["deadline"]!="0000-00-00 00:00:00") { $date=$row["deadline"]; $nextWeek = time(); $todayDate = date("Y-m-d H:i:s",$nextWeek); $day=subtract_datesForMinutes($date, $todayDate); if($day>=0) { $id_=$row["id"]; $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=12;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) $list[$i++]=$row; } else $list[$i++]=$row; } } } return $list; } function crm_getEventHrConflict($eventid,$hrid, $dataeveniment, $dataora, $dataminut, $durata) { if($durata==0) $durata=1; if($eventid!='') $eventIdFilter=" AND `id`!='$eventid'"; else $eventIdFilter=""; $lastDate=date("Y-m-d H:i:s",strtotime($dataeveniment." ".$dataora.":".$dataminut.":00")+(1 * 1 * 1 * $durata * 60)); $query="SELECT * FROM `crm_events` WHERE `asignedTo`='$hrid' $eventIdFilter AND (`dateFor` BETWEEN '".$dataeveniment." ".$dataora.":".$dataminut.":00' AND '$lastDate' OR TIMESTAMPADD(MINUTE,`duration`,`dateFor`) BETWEEN '".$dataeveniment." ".$dataora.":".$dataminut.":00' AND '$lastDate' OR (`dateFor` < '".$dataeveniment." ".$dataora.":".$dataminut.":00' AND TIMESTAMPADD(MINUTE,`duration`,`dateFor`) > '$lastDate') ) LIMIT 1"; $result=mysql_query($query) or die(mysql_error()); if(mysql_num_rows($result)>0) { $row=mysql_fetch_array($result); return $row; } else { return NULL; } } function crm_getEventCarConflict($eventid,$carid, $dataeveniment, $dataora, $dataminut, $durata) { if($durata==0) $durata=1; if($eventid!='') $eventIdFilter=" AND `id`!='$eventid'"; else $eventIdFilter=""; $lastDate=date("Y-m-d H:i:s",strtotime($dataeveniment." ".$dataora.":".$dataminut.":00")+(1 * 1 * 1 * $durata * 60)); $query="SELECT * FROM `crm_events` WHERE `asignedToCar`='$carid' AND (`dateFor` BETWEEN '".$dataeveniment." ".$dataora.":".$dataminut.":00' AND '$lastDate' OR TIMESTAMPADD(MINUTE,`duration`,`dateFor`) BETWEEN '".$dataeveniment." ".$dataora.":".$dataminut.":00' AND '$lastDate' OR (`dateFor` < '".$dataeveniment." ".$dataora.":".$dataminut.":00' AND TIMESTAMPADD(MINUTE,`duration`,`dateFor`) > '$lastDate') ) ".$eventIdFilter." LIMIT 1"; $result=mysql_query( $query ) or die(mysql_error()); if(mysql_num_rows($result)>0) { $row=mysql_fetch_array($result); return $row; } else { return NULL; } } function avert_emailSending($id,$mailSettings) { $rootFolder = loadGeneralSettings(); //version loading $versions = loadVersion(); //megnezni az avert tipust, megirni a subjectet, es megirni a szoveget, kivalasztani kinek megy az email $avertizare=avertizare_getAvertizare($id); $avert=avertizare_getAvertizareData( $avertizare["avertizare_id"], $avertizare["mod_id"] ); if($avert["period"]=="unic") { $itemsDates=commandForClientAdv_getItemsDatesOnlyToFacture($avert["comandaId"]); if($itemsDates!=NULL) { $avert["facturaendDate"]=""; while($dates=mysql_fetch_array($itemsDates)) { $avert["facturaendDate"]=$avert["facturaendDate"].$dates["date"]." "; } } } $partner = partners_getPartner( $avert["clientid"] ); if($verified!=1) $clientName = utf8_encode($partner["name"]); else $clientName = $partner["name"]; $provider = partners_getPartner( $avert["provider"] ); if($verified!=1) $providerName = utf8_encode($provider["name"]); else $providerName = $provider["name"]; $partner2 = partners_getPartner( $avert["comandaClientId"] ); if($verified!=1) $clientName2 = utf8_encode($partner2["name"]); else $clientName2 = $partner2["name"]; $partner3 = partners_getPartner( $avert["clientid"] ); if($verified!=1) $clientName3 = utf8_encode($partner3["name"]); else $clientName3 = $partner3["name"]; $eventCat = crm_getEventCategories(); $eventtCat = crm_getEventTypes(); if($avertizare["avertizare_name"]=="Partner") { $balance=partner_getBalance($avertizare["avertizare_id"]); $limitPartner=partner_getLimit($avertizare["avertizare_id"]); } if($avertizare["avertizare_name"]=="BirthDay") { $clientInfoData=partners_getPartner($avertizare["avertizare_id"]); } if($avertizare["mod_id"]==2) { $per=$avert["perioada"]; $date=substr($per,12,12); $an=substr($date,1,4); $luna=substr($date,6,2); $zi=substr($date,9,2); $data=$zi."-".$luna."-".$an; } if($avert["termenDePlata"]=="0000-00-00") $termenDePlata=$avert["dataExecutiei"]; else $termenDePlata=$avert["termenDePlata"]; if($avertizare["mod_id"]==1) { $emailBaseContent = getTraducere("Produsul",$_SESSION["settings"]["default_lang"])." ".$avert["name"]." ".getTraducere("este pe terminate din stoc",$_SESSION["settings"]["default_lang"])."!"; $mailSubject = getTraducere("Avertizare - Stoc",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==2) { $emailBaseContent = getTraducere("Contractul angajatului",$_SESSION["settings"]["default_lang"])." ".$avert["forname"]." ".$avert["lastname"].", ".getTraducere("avand CNP nr.",$_SESSION["settings"]["default_lang"])." ".$avert["cnp"].", ".getTraducere("a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$data."!"; $mailSubject = getTraducere("Avertizare - Contract Angajat",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==3) { $emailBaseContent = getTraducere("Termenul de plata a facturii avand seria",$_SESSION["settings"]["default_lang"]).": ".$avert["serial"]." ".$avert["number"]." ".getTraducere("pentru client",$_SESSION["settings"]["default_lang"]).": ".$clientName.", ".getTraducere("(a) expira(t) la data de",$_SESSION["settings"]["default_lang"]).": ".$termenDePlata."!"; $mailSubject = getTraducere("Avertizare - Plata factura",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==5) { $emailBaseContent = getTraducere("Restanta clientului",$_SESSION["settings"]["default_lang"])." ".$avert["name"]." ".getTraducere("este mai mare",$_SESSION["settings"]["default_lang"])." ( ".$balance." RON ) ".getTraducere("decat suma permisa",$_SESSION["settings"]["default_lang"])." ( ".$limitPartner." RON )!"; $mailSubject = getTraducere("Avertizare - Restanta client prea mare",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==6) { $emailBaseContent = getTraducere("Asigurarea RCA a masinii cu nr.",$_SESSION["settings"]["default_lang"])." ".$avert["registrating"]." ".getTraducere("a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["RCA_data"]."!"; $mailSubject = getTraducere("Avertizare - Expirare asigurare RCA",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==8) { $emailBaseContent = getTraducere("Asigurarea Casco a masinii cu nr.",$_SESSION["settings"]["default_lang"])." ".$avert["registrating"]." ".getTraducere("a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["Casco_data"]."!"; $mailSubject = getTraducere("Avertizare - Expirare asigurare casco",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==15) { $emailBaseContent = getTraducere("Verificarea masinii cu nr.",$_SESSION["settings"]["default_lang"])." ".$avert["registrating"]." ".getTraducere("a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["Data_exp_verificare"]."!"; $mailSubject = getTraducere("Avertizare - Expirare verificare",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==16) { $emailBaseContent = getTraducere("Rovigneta masinii cu nr.",$_SESSION["settings"]["default_lang"])." ".$avert["registrating"]." ".getTraducere("a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["Data_exp_rovigneta"]."!"; $mailSubject = getTraducere("Avertizare - Expirare rovigneta",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==17) { $emailBaseContent = getTraducere("Trusa medicala maainii cu nr.",$_SESSION["settings"]["default_lang"])." ".$avert["registrating"]." ".getTraducere("a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["Data_exp_trusa"]."!"; $mailSubject = getTraducere("Avertizare - Expirare trusa medicala",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==18) { $emailBaseContent = getTraducere("Stingatorul masinii cu nr.",$_SESSION["settings"]["default_lang"])." ".$avert["registrating"]." ".getTraducere("a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["Data_exp_stingator"]."!"; $mailSubject = getTraducere("Avertizare - Expirare stingator",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==19) { $emailBaseContent = getTraducere("Licenta masinii cu nr.",$_SESSION["settings"]["default_lang"])." ".$avert["registrating"]." ".getTraducere("a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["Data_exp_licenta"]."!"; $mailSubject = getTraducere("Avertizare - Expirare licenta",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==20) { $emailBaseContent = getTraducere("Tahograful masinii cu nr.",$_SESSION["settings"]["default_lang"])." ".$avert["registrating"]." ".getTraducere("a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["Data_exp_tahograf"]."!"; $mailSubject = getTraducere("Avertizare - Expirare tahograf",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==7) { $emailBaseContent = getTraducere("Modificarea fisei zilnice de lucru nr.",$_SESSION["settings"]["default_lang"])." ".$avert["id"]." ".getTraducere("nu a fost efectuata",$_SESSION["settings"]["default_lang"])."!"; $mailSubject = getTraducere("Avertizare - Fise zilnice",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==9) { if($avert["facturaendDate"]==NULL) $showDate=$avert["comandaStartDate"]; else $showDate=$avert["facturaendDate"]; $emailBaseContent = getTraducere("Comanda nr.",$_SESSION["settings"]["default_lang"])." ".$avert["comandasecondserial"]." ".getTraducere("pentru client",$_SESSION["settings"]["default_lang"]).": ".$clientName2.", ".getTraducere("nu a fost facturata de la data",$_SESSION["settings"]["default_lang"]).": ".$showDate."!"; $mailSubject = getTraducere("Avertizare - Expirare facturare comanda",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==10) { $emailBaseContent = getTraducere("Termenul de plata a facturii de cheltuiala avand nr",$_SESSION["settings"]["default_lang"]).": ".$avert["number"]." ".getTraducere("pentru furnizor",$_SESSION["settings"]["default_lang"]).": ".$providerName.", ".getTraducere("(a) expira(t) la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["lastdayofpay"]."!"; $mailSubject = getTraducere("Avertizare - Plata cheltuiala",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==11) { if($avert["facturaendDate"]==NULL) $showDate=$avert["comandaStartDate"]; else $showDate=$avert["facturaendDate"]; $emailBaseContent = getTraducere("Comanda nr.",$_SESSION["settings"]["default_lang"])." ".$avert["comandasecondserial"]." ".getTraducere("pentru client",$_SESSION["settings"]["default_lang"]).": ".$clientName2.", ".getTraducere("o sa expira, sau a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$showDate."!"; $mailSubject = getTraducere("Avertizare - Expirare comanda",$_SESSION["settings"]["default_lang"]); } if($avertizare["mod_id"]==12) { $emailBaseContent = "".getTraducere("Evenimentul cu client",$_SESSION["settings"]["default_lang"]).": ".$clientName3.", ".$eventCat[ $avert["categoryId"] ]["name"].", ".$eventtCat[ $avert["eventType"] ]["name"].", ".getTraducere("o sa expira, sau a expirat la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["dateFor"]."!
"; $contactData=crm_getContact($avert["contactid"]); $emailBaseContent.= "
".$contactData["forname"]." ".$contactData["lastname"].", ".getTraducere("Tel",$_SESSION["settings"]["default_lang"]).": ".$contactData["tel"].", ".getTraducere("Putere de decizie",$_SESSION["settings"]["default_lang"]).": ".$contactData["decisionForce"]."
"; $eventDataParticipants = crm_getEventParticipants($avert["id"]); if( $eventDataParticipants ) foreach( $eventDataParticipants as $keyHrs => $valueHrs ) { $hrDataInfo = mysql_fetch_array(getHrData($valueHrs["hrId"])); $hrsInfo .= $hrDataInfo["forname"]." ".$hrDataInfo["lastname"].", "; } $emailBaseContent.="".getTraducere("Angajati participanti",$_SESSION["settings"]["default_lang"]).": ".$hrsInfo."
"; $hrsInfo=""; $emailBaseContent.="".getTraducere("Observatie",$_SESSION["settings"]["default_lang"]).": ".$avert["observation"]."
"; $emailBaseContent.="".getTraducere("Servicii produse interesate",$_SESSION["settings"]["default_lang"]).": ".$avert["products"]."

"; $emailBaseContent.=getTraducere("Note pentru eveniment",$_SESSION["settings"]["default_lang"]).":
"; $notesInfo = crm_getNotes($avert["clientid"],$avert["id"]); $counterNotesInfo=0; if( $notesInfo ) foreach( $notesInfo as $keyNotesInfo => $valueNotesInfo ) { $counterNotesInfo++; $emailBaseContent.="".getTraducere("Nr.",$_SESSION["settings"]["default_lang"]).": ".$counterNotesInfo.", ".getTraducere("Categoria",$_SESSION["settings"]["default_lang"]).": ".crm_getNotesCategory($valueNotesInfo["categoryId"])."
"; $emailBaseContent.="".getTraducere("Titlu",$_SESSION["settings"]["default_lang"]).": ".$valueNotesInfo["title"]."
"; $emailBaseContent.="".getTraducere("Nota",$_SESSION["settings"]["default_lang"]).": ".$valueNotesInfo["note"]."
"; $emailBaseContent.="".getTraducere("Data",$_SESSION["settings"]["default_lang"]).": ".$valueNotesInfo["ondate"]."

"; } "".getTraducere("Data evenimentului",$_SESSION["settings"]["default_lang"]).": ".$avert["dateFor"]."
"; $cityData = cities_getCity($avert["cityId"]); $emailBaseContent.="".getTraducere("Locatia",$_SESSION["settings"]["default_lang"]).": ".$cityData["name"].", ".$avert["address"]."
"; $emailBaseContent.="".getTraducere("Suma de oportunitate",$_SESSION["settings"]["default_lang"]).": ".$avert["oportunityValue"]; if($avert["onvaluta"]=="") $emailBaseContent.="RON"; else $emailBaseContent.=$avert["onvaluta"]; $emailBaseContent.="
".getTraducere("Deadline",$_SESSION["settings"]["default_lang"]).": ".$avert["deadline"]."
"; $mailSubject = getTraducere("Avertizare - Eveniment - Client",$_SESSION["settings"]["default_lang"]).": ".$clientName3." - ".getTraducere("La data de",$_SESSION["settings"]["default_lang"]).": ".$avert["dateFor"]."!"; $hrUserData = hr_getAdminUserAsoc($avert["asignedTo"]); $avert["userid"]=$hrUserData["id"]; } if($avertizare["mod_id"]==13) { $emailBaseContent = "".getTraducere("Evenimentul cu client",$_SESSION["settings"]["default_lang"]).": ".$clientName3.", ".$eventCat[ $avert["categoryId"] ]["name"].", ".$eventtCat[ $avert["eventType"] ]["name"].", ".getTraducere("nu a fost rezolvat pana la data de",$_SESSION["settings"]["default_lang"]).": ".$avert["deadline"]."!
"; $contactData=crm_getContact($avert["contactid"]); $emailBaseContent.= "
".$contactData["forname"]." ".$contactData["lastname"].", ".getTraducere("Tel",$_SESSION["settings"]["default_lang"]).": ".$contactData["tel"].", ".getTraducere("Putere de decizie",$_SESSION["settings"]["default_lang"]).": ".$contactData["decisionForce"]."
"; $eventDataParticipants = crm_getEventParticipants($avert["id"]); if( $eventDataParticipants ) foreach( $eventDataParticipants as $keyHrs => $valueHrs ) { $hrDataInfo = mysql_fetch_array(getHrData($valueHrs["hrId"])); $hrsInfo .= $hrDataInfo["forname"]." ".$hrDataInfo["lastname"].", "; } $emailBaseContent.="".getTraducere("Angajati participanti",$_SESSION["settings"]["default_lang"]).": ".$hrsInfo."
"; $hrsInfo=""; $emailBaseContent.="".getTraducere("Observatie",$_SESSION["settings"]["default_lang"]).": ".$avert["observation"]."
"; $emailBaseContent.="".getTraducere("Servicii produse interesate",$_SESSION["settings"]["default_lang"]).": ".$avert["products"]."

"; $emailBaseContent.=getTraducere("Note pentru eveniment",$_SESSION["settings"]["default_lang"]).":
"; $notesInfo = crm_getNotes($avert["clientid"],$avert["id"]); $counterNotesInfo=0; if( $notesInfo ) foreach( $notesInfo as $keyNotesInfo => $valueNotesInfo ) { $counterNotesInfo++; $emailBaseContent.="".getTraducere("Nr.",$_SESSION["settings"]["default_lang"]).": ".$counterNotesInfo.", ".getTraducere("Categoria",$_SESSION["settings"]["default_lang"]).": ".crm_getNotesCategory($valueNotesInfo["categoryId"])."
"; $emailBaseContent.="".getTraducere("Titlu",$_SESSION["settings"]["default_lang"]).": ".$valueNotesInfo["title"]."
"; $emailBaseContent.="".getTraducere("Nota",$_SESSION["settings"]["default_lang"]).": ".$valueNotesInfo["note"]."
"; $emailBaseContent.="".getTraducere("Data",$_SESSION["settings"]["default_lang"]).": ".$valueNotesInfo["ondate"]."

"; } "".getTraducere("Data evenimentului",$_SESSION["settings"]["default_lang"]).": ".$avert["dateFor"]."
"; $cityData = cities_getCity($avert["cityId"]); $emailBaseContent.="".getTraducere("Locatia",$_SESSION["settings"]["default_lang"]).": ".$cityData["name"].", ".$avert["address"]."
"; $emailBaseContent.="".getTraducere("Suma de oportunitate",$_SESSION["settings"]["default_lang"]).": ".$avert["oportunityValue"]; if($avert["onvaluta"]=="") $emailBaseContent.="RON"; else $emailBaseContent.=$avert["onvaluta"]; $emailBaseContent.="
".getTraducere("Deadline",$_SESSION["settings"]["default_lang"]).": ".$avert["deadline"]."
"; $mailSubject = getTraducere("Avertizare - Eveniment - Client",$_SESSION["settings"]["default_lang"]).": ".$clientName3." - ".getTraducere("La data de",$_SESSION["settings"]["default_lang"]).": ".$avert["dateFor"]."!"; $hrUserData = hr_getAdminUserAsoc($avert["asignedTo"]); $avert["userid"]=$hrUserData["id"]; } if($avertizare["mod_id"]==14) { $birthday = $avert["birthdate"]; $today = date('Y-m-d'); $nextTime = strtotime($today)+(1 * ($_SESSION["settings"]["avertizareBirthDay"]+1) * 24 * 60 * 59); $today = date("Y-m-d",$nextTime); $a_birthday = explode('-', $birthday); $a_today = explode('-', $today); $day_birthday = $a_birthday[2]; $month_birthday = $a_birthday[1]; $year_birthday = $a_birthday[0]; $day_today = $a_today[2]; $month_today = $a_today[1]; $year_today = $a_today[0]; $age = $year_today - $year_birthday; if (($month_today < $month_birthday) || ($month_today == $month_birthday && $day_today < $day_birthday)) { $age--; } $mailSubject = getTraducere("Avertizare - Ziua de nastere pentru client",$_SESSION["settings"]["default_lang"]); $emailBaseContent = getTraducere("Clientul",$_SESSION["settings"]["default_lang"])." ".$clientInfoData["name"]." ".getTraducere("are ziua lui la data de",$_SESSION["settings"]["default_lang"]).": ".date("Y")."-".substr($avert["birthdate"],5,10).", ".getTraducere("si o sa implineasca",$_SESSION["settings"]["default_lang"])." ".$age." ".getTraducere("ani",$_SESSION["settings"]["default_lang"])."!"; } if($avertizare["mod_id"]!=12 && $avertizare["mod_id"]!=13) $userData = users_getUser($avert["userid"]); else $userData = hr_getUser($avert["asignedTo"]); $clientEmail = $userData["email"]; $mailContent = $emailBaseContent; $compDetailsForEmail = admin_getCompanyDetails(); $propertyCompanyName = $compDetailsForEmail["comname"]; $propertyCompanyEmail = $compDetailsForEmail["cemail"]; $params = loadMailSettings($mailSettings["smtpAddress"],$mailSettings["domainAddress"],$mailSettings["emailAddress"],$mailSettings["emailPass"],$propertyCompanyName,$propertyCompanyEmail); $send_params['recipients'] = array($clientEmail); $hrsavert=getHrsForAvert($avertizare["mod_id"]); if($hrsavert) { foreach($hrsavert as $ak=>$av) { $userData11 = hr_getUser($av["hrid"]); array_push($send_params['recipients'],$userData11["email"]); } } // The recipients (can be multiple) $send_params['headers'] = array('Content-type: text/html; charset=iso-8859-1', 'From: "'.$params['papermanagement']['fromCompany'].'" <'.$params['papermanagement']['fromCompanyEmail'].'>', // Headers 'To: '.$clientEmail, 'Subject: '.$mailSubject,'\nReturn-Path: '.$params['papermanagement']['fromCompanyEmail'].'\nContent-Transfer-Encoding: 16bit\n'); $send_params['from'] = $params['papermanagement']['fromCompanyEmail']; // This is used as in the MAIL FROM: cmd $mailContentBase = ''.getTraducere("Avertizare - PaperManagement",$_SESSION["settings"]["default_lang"]).'
'.getTraducere("A fost trimis o avertizare din sistem",$_SESSION["settings"]["default_lang"]).' '.$rootFolder.'!
'.$mailContent.'
'; $mailContentEnding = '
'.getTraducere("generat din SigmaNet PaperManagement v",$_SESSION["settings"]["default_lang"]).' '.$versions["actual"]["number"].'
www.sigma-net.ro
'; // It should end up as the Return-Path: header $send_params['body'] = $mailContentBase.$mailContentEnding; // The body of the email if(is_object($smtp = smtp::connect($params)) AND $smtp->send($send_params)) { // Any recipients that failed (relaying denied for example) will be logged in the errors variable. $error["EmailSending"][0] = $smtp->errors; $error["EmailSending"]["sentSomething"] = 1; print_r($smtp->errors); } else { $error["EmailSending"][0] = $smtp->errors; $error["EmailSending"]["sentSomething"] = 0; print_r($smtp->errors); } if($avertizare["mod_id"]==13 || $avertizare["mod_id"]==12) { $eventDataParticipants = crm_getEventParticipants($avert["id"]); if( $eventDataParticipants ) foreach( $eventDataParticipants as $keyHrs => $valueHrs ) { $hrDataInfo = mysql_fetch_array(getHrData($valueHrs["hrId"])); $clientEmail = $hrDataInfo["email"]; $send_params['recipients'] = array($clientEmail); $send_params['headers'] = array('Content-type: text/html; charset=iso-8859-1', 'From: "'.$params['papermanagement']['fromCompany'].'" <'.$params['papermanagement']['fromCompanyEmail'].'>', // Headers 'To: '.$clientEmail, 'Subject: '.$mailSubject,'\nReturn-Path: '.$params['papermanagement']['fromCompanyEmail'].'\nContent-Transfer-Encoding: 16bit\n'); if(is_object($smtp = smtp::connect($params)) AND $smtp->send($send_params)) { // Any recipients that failed (relaying denied for example) will be logged in the errors variable. $error["EmailSending"][0] = $smtp->errors; $error["EmailSending"]["sentSomething"] = 1; print_r($smtp->errors); } else { $error["EmailSending"][0] = $smtp->errors; $error["EmailSending"]["sentSomething"] = 0; print_r($smtp->errors); } } } } function newsletter_getEmailTemplates() { $query="SELECT * FROM `emails_template` WHERE `type`='1' order by `name` ASC"; $result=mysql_query( $query ) or die(mysql_error()); $array; while($row=mysql_fetch_array($result)) { $array[$row['id']]=$row; } return $array; } function newsletter_getEmailTemplateContent($newsletterEmailTemplateId) { $query="SELECT * FROM `emails_template` WHERE `id`='$newsletterEmailTemplateId'"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row["content"]; } function crm_insertModification($eventid, $userid, $eventData, $postArray ) { $dateValue=$postArray["dataeveniment"]." ".$postArray["dataora"].":".$postArray["dataminut"].":00"; $deadlineValue=$postArray["deadlineeveniment"]." ".$postArray["deadlineora"].":".$postArray["deadlineminut"].":00"; $activity=""; if($eventData["dateFor"]!=$dateValue) { $activity=getTraducere("Modificare data",$_SESSION["settings"]["default_lang"]); $oldDate = $eventData["dateFor"]; $newDate = $dateValue; } if($eventData["deadline"]!=$deadlineValue) { $activity=getTraducere("Modificare deadline",$_SESSION["settings"]["default_lang"]); $oldDeadline = $eventData["deadline"]; $newDeadline = $deadlineValue; } if($eventData["observation"]!=$postArray["observatii"]) { $activity=getTraducere("Modificare observatii",$_SESSION["settings"]["default_lang"]); $oldObservation = $eventData["observation"]; $newObservation = $postArray["observatii"]; } if($eventData["state"]!=$postArray["eventstatus"]) { $activity=getTraducere("Modificare status eveniment",$_SESSION["settings"]["default_lang"]); $oldStatus = $eventData["state"]; $newStatus = $postArray["eventstatus"]; } if($activity!="") { $query="INSERT INTO `crm_eventStatus`(`activity`,`userid`,`ondate`,`eventId`,`oldDate`,`newDate`,`oldObservation`,`newObservation`,`oldDeadline`,`newDeadline`,`oldStatus`,`newStatus`) VALUES ('$activity','$userid',NOW(),'$eventid','$oldDate','$newDate','$oldObservation','$newObservation','$oldDeadline','$newDeadline','$oldStatus','$newStatus')"; mysql_query( $query ) or die(mysql_error()); } } ////////////////////////webadmin fugvenyek!!!!!///////////////////// function webadmin_getallmenu() { $query="SELECT * FROM content"; $result=mysql_query( $query ) or die(mysql_error()); while($row=mysql_fetch_array($result)) { $array[$row['id']]=$row; } return $array; } function webadmin_getWebadminWebpage() { $query = "SELECT * FROM `website` ORDER BY id"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $providers[ $row["id"] ] = $row; return $providers; } function webadmin_getWebadminWebpageFromId($id) { $query = "SELECT * FROM `website` where `id`='$id' ORDER BY id"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $result ); return $row["webpage"]; } function webadmin_getWebadminallfadher($webpageid,$lang) { $query = "SELECT * FROM `content` WHERE `webpageid`=$webpageid and `lang`='$lang' ORDER BY id"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $providers[ $row["id"] ] = $row; return $providers; } function webadmin_addWebadminMenu( $userid , $webpageid , $fadherid, $dateNow , $description , $clienti, $titlemeta, $content, $keywords, $lang, $titlu, $type, $level, $window) { if($fadherid == 0) { $q = "select * from content where `fadherid` = 0"; $r = mysql_query($q); $sequence = mysql_num_rows($r)+1; } else { $q = "select * from content where `fadherid` = '$fadherid'"; $r = mysql_query($q); $sequence = mysql_num_rows($r)+1; } $dateNow = date("Y-m-d"); $dateNowMonthTemp = time() + ( 30 * 24 * 60 * 59); $dateNowMonth = date("Y-m-d",$dateNowMonthTemp); $insertQ = "INSERT INTO `content` ( `id` , `title` , `content` , `active` , `userid` , `ondate` , `moddate` , `type` , `keywords` , `titlemeta` , `description` , `fadherid` , `webpageid` , `level` , `window` , `sequence` , `lang` ) VALUES (NULL , '$titlu', '$content' , '1' , '$userid', NOW(), '', '$type', '$keywords', '$titlemeta', '$description', '$fadherid', '$webpageid', '$level', '$window','$sequence', '$lang');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } class Menu44 { public $title; public $id; public $fadherid; public $webpageid; public $childs; public $level; public $ondate; public $moddate; public $active; public $lang; public $sequence; } function webadmin_searchGenerateQuery($searchval,$fromDate,$toDate,$site) { $toDate = mysql_nextDay($toDate); $query="SELECT c.id,c.ondate,c.moddate,c.active,c.userid,c.webpageid,c.level,c.sequence, c.title,c.fadherid,c.lang, SUBSTRING(GROUP_CONCAT(cr.child separator ','),1,2000) as childs from content c left join content_rel cr on c.id=cr.parent WHERE 1 "; if($fromDate) $query.=" AND c.`ondate`>='$fromDate' "; if($toDate) $query.=" AND c.`ondate`<='$toDate' "; if($site!="0"&&$site!="") $query.=" AND c.`webpageid`='$site' "; $query.=" group by c.id order by c.id"; $result=mysql_query($query) or die(mysql_error()); $res=array(); $mainmen=new Menu44(); $mainmen->id=0; $mainmen->childs=array(); if($result) { while($rowmenu=mysql_fetch_array($result)) { $menmenu = new Menu44(); $menmenu->childs = array(); $menmenu->id=(int)$rowmenu["id"]; $menmenu->webpageid=(int)$rowmenu["webpageid"]; $menmenu->ondate=$rowmenu["ondate"]; $menmenu->userid=$rowmenu["userid"]; $menmenu->moddate=$rowmenu["moddate"]; $menmenu->lang=$rowmenu["lang"]; $menmenu->webpageid=$rowmenu["webpageid"]; $menmenu->active=(int)$rowmenu["active"]; $menmenu->fadherid =(int)$rowmenu["fadherid"]; $menmenu->level =(int)$rowmenu["level"]; $menmenu->title=$rowmenu["title"]; $menmenu->sequence=$rowmenu["sequence"]; if ($rowmenu["childs"]) $menmenu->childs = explode(",",$rowmenu["childs"]); $res[$menmenu->id]=$menmenu; if($menmenu->fadherid==0) array_push($mainmen->childs,$menmenu->id); } } $res[0]=$mainmen; ksort($res); return $res; } function webadmin_addWebadminMenuRel($fadherid,$childid) { if($fadherid!=$childid) { $query="INSERT INTO `content_rel`(`parent`,`child`) VALUES ('$fadherid','$childid')"; mysql_query($query) or die(mysql_error()); } } function webadmin_modFactura( $id,$userid , $webpageid , $fadherid, $dateNow , $description , $clienti, $titlemeta, $content, $keywords, $lang, $titlu, $type, $level, $window) { if($id!=$fadherid) { $updateQ = "UPDATE `content` SET `userid` = '$userid', `webpageid` = '$webpageid', `fadherid` = '$fadherid', `description` = '$description', `titlemeta` = '$titlemeta', `lang` = '$lang', `title` = '$titlu', `keywords` = '$keywords', `window` = '$window', `level` = '$level', `content` = '$content', `type` = '$type', `moddate` = NOW() WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); $query="UPDATE `content_rel` SET `parent`='$fadherid' WHERE `child`='$id'"; $result=mysql_query($query) or die(mysql_error()); } } function webadmin_getWebadminallType() { $query = "SELECT * FROM `content_type` WHERE `active`=1 ORDER BY id"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) $providers[ $row["id"] ] = $row; return $providers; } function webadmin_registerItems( $factid , $content ) { $content = addslashes ($content); $query = "INSERT INTO `content_ads` VALUES (NULL, '$factid', '$content');"; mysql_query( $query ) or die(mysql_error()); } function getWebadminRegisteredItems ($commandId) { $query = "SELECT * FROM `content_ads` WHERE `web_id` = $commandId order by id ASC;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function webadmin_unRegisterItems( $factid ) { $query = "DELETE FROM `content_ads` WHERE `content_ads`.`web_id` = '$factid';"; mysql_query( $query ) or die(mysql_error()); $_SESSION["commandForClientAdv"]["edited"]=1; } function getWebadminRegisteredItemsCount ($commandId) { $query = "SELECT * FROM `content_ads` WHERE `web_id` = $commandId;"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function webadminFileUpload($uploaded_file, $prodid) { // Ellenorizzuk, hogy van-e fajl if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { // Ellenorizzuk, hogy az .jpg vagy .png kiterjesztesu-e es hogy kisebb 500kb-nal $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); $query = "select * from content where id = '$prodid' and active=1"; $res = mysql_query( $query ) or die(mysql_error()); $father = mysql_fetch_array($res); if($prodid == 5 || $father["fadherid"] == 5 || $father["type"] == 6) { $newname = dirname(__FILE__).'/images/uploaded/'.$kapott=$father["id"]."-".str_replace(" ","_",$_FILES["uploaded_file"]["name"]); } else { $newname = dirname(__FILE__).'/images/uploaded/'.$kapott=str_ireplace("/","_",$_FILES['uploaded_file']['tmp_name']).".".$ext; } // Ellenorizzuk, hogy letezik-e mar if (!file_exists($newname)) { // Ha nem letezik, felpakoljuk if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { webadminFileToDB($kapott, $prodid); $mess= getTraducere("Fisierul a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=false; } else { $mess= getTraducere("Gresit! Fisierul nu prea a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=true; } } else { $mess= getTraducere("Greseala: Fisierul ",$_SESSION["settings"]["default_lang"]).$_FILES["uploaded_file"]["name"]." ".getTraducere("deja exista!",$_SESSION["settings"]["default_lang"]); $err=true; } } else { $mess= getTraducere("Greseala: Fisierul nu a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=true; } if(!$err) $MessageHelpDialog=$mess; else $errorMessageHelpDialog=$mess; include("global_helpDialog.php"); } // Fajl adatbazisregisztracioja function webadminFileToDB($picname, $prodid) { $query='INSERT INTO content_images (`id`, `prodid`, `path`) VALUES (NULL, "'.$prodid.'", "'.$picname.'");'; $lekerdezes=mysql_query( $query ) or die(mysql_error()); } function webmenugetlevel($id) { $query = "SELECT * FROM `content` WHERE `id` = '$id' ;"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return $row["level"]; } function webmenugetfathername($id) { $query = "SELECT * FROM `content` WHERE `id` = '$id' ;"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array( $result ); return $row["title"]; } function webmenactivaredezactivare($id,$actcodok) { $query = "UPDATE `content` SET `active`=$actcodok WHERE `id` = '$id' ;"; $result = mysql_query( $query ) or die(mysql_error()); } function getMenuChildNr($id) { $query = "select * from content_rel where parent = '$id'"; $result = mysql_query( $query ) or die(mysql_error()); $j=0; while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function setTheMenuOrder($menuid, $value) { $query = "select * from content where `id` = $menuid"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array($result); $fatherid = $row["fadherid"]; $firstorder = $row["sequence"]; //=================================================== $query2 = "select * from content where `fadherid` = '$fatherid' and `sequence` = '$value'"; $result2 = mysql_query( $query2 ) or die(mysql_error()); $row2 = mysql_fetch_array($result2); $secondid = $row2["id"]; $query3 = "update content set `sequence` = '$firstorder' where `id` = '$secondid'"; $result3 = mysql_query( $query3 ) or die(mysql_error()); $query4 = "update content set `sequence` = '$value' where `id` = '$menuid'"; $result4 = mysql_query($query4); } function generateDataFromWebmenu($id) { $select = "SELECT * FROM `content` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function getAllUploadedFileForMenu($id) { $query = "select * from content_images where prodid = '$id'"; $result = mysql_query($query) or die("getAllUploadedFileForMenu ".mysql_error()); $j = 0; while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function deleteFileFromMenu($id, $prodid) { $query = "select * from content_images where id = '$id' and prodid = '$prodid'"; $res = mysql_query($query) or die("deleteFileFromMenu first query ".mysql_error()); $row = mysql_fetch_array($res); $file = $_SERVER['DOCUMENT_ROOT']."/images/uploaded/".$row["path"]; $quer = "delete from content_images where id = '$id' and prodid = '$prodid'"; $result = mysql_query($quer) or die("deleteFileFromMenu second query ".mysql_error()); return unlink($file); } function getCountryCodeByName($name) { $query="SELECT `Code` FROM `world_country` WHERE `Name`='$name'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row["Code"]; } //commandForPartner resz function command_getPartnercomandaForPartner( $clientid, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `comandaForPartner` WHERE `clientid`=$clientid AND `active` ='1' ORDER BY numberSerial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getcomandaForPartner( $pageno = -1, $orderby ) { $query = "SELECT * FROM `comandaForPartner` WHERE `active` ='1' ORDER BY `numberSerial` $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getcomandaForPartnerPunct( $defStockId , $pageno = -1, $orderby ) { $query = "SELECT * FROM `comandaForPartner` command, `users` users WHERE command.`active` ='1' AND command.`userid`=users.`id` AND users.`defstock` = '$defStockId' ORDER BY command.`id` ASC"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $counter=0; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; $counter++; } return $counter; } function getcomandaForPartner($commandid) { $query="SELECT * FROM `comandaForPartner` WHERE `id`='$commandid'"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } function getcomandaForPartnerItems($commandid) { $query="SELECT * FROM `comandaForPartnerItems` WHERE `comandaid`='$commandid'"; $result=mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) { $list[ $row["id"] ] = $row; } return $list; } function getcomandaForPartnerItemsCount($commandid) { $query="SELECT * FROM `comandaForPartnerItems` WHERE `comandaid`='$commandid'"; $i=0; $result=mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) { $i++; } return $i; } function stats_comandaForPartnerGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `comandaForPartner` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function comandaForPartner_delete( $facturaId ) { $query = "DELETE FROM `comandaForPartner` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function command_addcomandaForPartner( $clientid , $userid , $stockid , $rawvalue , $value , $number, $content , $termenDePlata, $dataExecutiei, $onValuta , $cursValue, $_comments, $clientPunctLucru, $contactPerson,$location,$depid) { $content = addslashes ($content); $insertQ = "INSERT INTO `comandaForPartner` ( `id` , `clientid` , `userid` , `stockid` , `numberSerial` , `rawValue` , `value` , `currency` , `cursValue` , `partnerTermen` , `content` , `ondate` , `active` , `printed` , `closed` , `comments`, `clientPunctLucru`, `termenExecutiei`, `contactPerson`, `locationId`, `departament` ) VALUES (NULL , '$clientid', '$userid', '$stockid' , '$number', '$rawvalue', '$value', '$onValuta', '$cursValue', '$termenDePlata' , '$content', NOW(), '1', '0', '0', '$_comments','$clientPunctLucru', '$dataExecutiei','$contactPerson','$location','$depid');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function commandForPartner_ExpiredCommandsTime() { $query = "SELECT * FROM `comandaForPartner` where `active`='1'"; $result = mysql_query( $query ) or die(mysql_error()); $j=0; while( $row = mysql_fetch_array($result) ) { $registeredItems = getCommandForPartnerAdvRegisteredItems ($row["id"]); $registeredItemsCount = getCommandForPartnerAdvRegisteredItemsCount ($row["id"]); $counter=1; for($i=1;$i<=$registeredItemsCount;$i++) { $nowDate = date("Y-m-d"); $nextWeek = time() + (1 * $_SESSION["settings"]["avertizareComandaDateExpire"] * 24 * 60 * 59); $fromDateNextWeek = date("Y-m-d",$nextWeek); $mustFacturat=0; //megnezem hogy a lejarati datum nagyobb-e mint a mai nap if($registeredItems[$i]["endDate"]!="0000-00-00" && subtract_dates($registeredItems[$i]["endDate"],$fromDateNextWeek)>0 && $registeredItems[$i]["period"]!="unic") { $mustFacturat=1; } if($mustFacturat==1) { // ez a resz ha kell szamlazni a megrendelot, tehat beteszem az avertizare listaba $id_=$row["id"]; // megnezem, hogy bent van e esetleg mar az avertizare a listaban $query2="select * from avertizare_avertizariItems where `avertizare_id`='$id_' and `mod_id`=11;"; $remdatefrom=""; $result2=mysql_query( $query2 ) or die(mysql_error()); if($result2) while($r=mysql_fetch_array($result2)) { if($r["remainderFrom"]!="0000-00-00") { $remdatefrom=$r["remainderFrom"]; $days=$r["remainder"]; } } if($remdatefrom) { $an=substr($remdatefrom,0,4); $luna=substr($remdatefrom,5,2); $zi=substr($remdatefrom,8,2); $d = date("Y-m-d", mktime(0,0,0,$luna,$zi+$days,$an)); $sub = subtract_dates($d,$todayDate); if( $sub<=0 ) { $list[$j++]=$row; } } else { $list[$j++]=$row; } } } } return $list; } function comandaForPartner_registerItems( $factid , $productid, $productname , $unitprice , $moneytype, $um, $quantity , $pricewithouttva , $tva, $TVAcalculare ) { $query = "INSERT INTO comandaForPartnerItems VALUES (NULL, '$factid', NOW() , '$productid', '$stockid', '$productname', '$unitprice' , '$moneytype', '$um' , '$quantity', '$pricewithouttva' , '$tva' , '$TVAcalculare');"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function comandaForPartner_unRegisterItems( $factid ) { $query = "DELETE FROM `comandaForPartnerItems` WHERE `comandaForPartnerItems`.`comandaid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); $_SESSION["comandaForPartner"]["edited"]=1; } function comandaForPartner_setActiveNess( $factid , $state ) { $update = "UPDATE `comandaForPartner` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); //if( $state == 0 )factura_deactivateBills( $factid ); } function comandaForPartner_modFactura( $id, $clientid , $userid , $stockid , $rawvalue , $value , $number, $content , $termenDePlata, $dataExecutiei, $onValuta , $cursValue, $_comments, $clientPunctLucru, $contactPerson,$location,$depid) { $content = addslashes ($content); $updateQ = "UPDATE `comandaForPartner` SET `clientid` = '$clientid', `content` = '$content', `rawvalue` = '$rawvalue', `value` = '$value', `currency` = '$onValuta', `partnerTermen` = '$termenDePlata', `comments` = '$_comments', `clientPunctLucru` = '$punctdelucru', `termenExecutiei` = '$dataExecutiei', `contactPerson` = '$contactperson', `locationId` = '$location', `departament` = '$depid', `cursValue` = '$cursValue' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function comandaForPartner_setPrinted( $id , $value ) { $updateQ = "UPDATE `comandaForPartner` SET `printed` = '$value' WHERE `id` ='$id' LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function comandaForPartner_setClosed( $id , $value ) { $updateQ = "UPDATE `comandaForPartner` SET `closed` = '$value' WHERE `id` ='$id' LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function comandaForPartner_setSerial( $id , $serial ) { $update = "UPDATE `comandaForPartner` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function comandaForPartner_getFacturi() { $select = "SELECT * FROM `comandaForPartner`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function commandForPartner_getFactura( $id ) { $select = "SELECT * FROM `comandaForPartner` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function generateDataFromcomandaForPartner( $id ) { $select = "SELECT * FROM `comandaForPartner` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function commandForPartner_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $firstserial, $secondserial, $serial, $dataLabel, $location , $locationId,$viewall=1,$userid=0) { //hanyat akar egy oldarra megjeleniteni $count = $_SESSION["settings"]["searchcount"]; ///honnan kezdje $from = ($page - 1) * $count; if($viewall!="1") { $viewquery= " AND ( f.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid') "; } $toDate = mysql_nextDay( $toDate ); //location if($location!=0) { $selectedStock = stock_getStockFromLocation($location); $selectedId = $selectedStock["id"]; $locationSql = " AND f.`stockid` = '$selectedId'"; } else { $locationSql = ""; } //location if($locationId!=0) { $locationIdSql = " AND f.`locationId` = '$locationId'"; } else { $locationIdSql = ""; } //datumszuro be ki kapcsolasa if($searchval!=NULL && $searchcriteria!="serial") $dateFilter=""; else $dateFilter = "AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; // filter menut a linkbol kapja valtozokent vagy a cautare postolasakor // itt kezelunk le kulonbozo esteket //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "nefacturate") { $query = "SELECT `f`.* FROM `comandaForPartner` f, `facturi` fact WHERE `f`.`id` <> `fact`.`fromActId` ".$plus_search.$locationSql.$locationIdSql." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'".$viewquery; $result = mysql_query($query) or die(mysql_error()); } if($filter_menu == "faraprofit") { if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`number` = '$searchval'"; else $plus_search="AND `p`.`name` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`name` FROM `comandaForPartner` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$plus_search.$locationSql.$locationIdSql." AND `f`.`profit` < 0 AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'".$viewquery." ORDER BY $orderby $ordermode"; $result = mysql_query($query) or die(mysql_error()); } if($filter_menu != "nefacturate" && $filter_menu != "faraprofit") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial") { if($firstserial!=NULL) $serialFilter.= " AND `f`.`firstserial` = '$firstserial'"; if($secondserial!=NULL) $serialFilter.= " AND `f`.`secondserial` = '$secondserial'"; if($serial!=NULL) $serialFilter.= " AND `f`.`numberSerial` = '$serial'"; if($dataLabel!=NULL) { $yearActual = substr($dataLabel,0,2); $monthActual = substr($dataLabel,2,2); $startDate = "20".$yearActual."-".$monthActual."-01"; $endDate = "20".$yearActual."-".$monthActual."-31"; $serialFilter.= " AND `f`.`ondate` BETWEEN '$startDate' AND '$endDate'"; } $query = "SELECT `f`.*, `p`.`name` FROM `comandaForPartner` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$serialFilter.$filterMenuSql.$locationSql.$locationIdSql.$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } ///ha nics szurve else { $query = "SELECT `f`.*, `p`.`name` FROM `comandaForPartner` f, `partners` p WHERE `p`.`name` LIKE '%$searchval%' AND `p`.`id` = `f`.`clientid` ".$dateFilter.$filterMenuSql.$locationSql.$locationIdSql.$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } } return $query; } function commandForPartner_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } //nir function nir_addNir( $provider, $userid , $defstock , $toStock , $TotalValueWithoutTvaRon , $TotalValueWithTvaRon , $number, $content , $documentType, $documentNr, $onValuta, $cursValue, $expdate, $observatii,$date) { if ($date=='') $date='NOW()'; else $date="DATE_ADD('".$date."', INTERVAL 1 SECOND)"; $content = addslashes ($content); $u=users_getUser($userid); $loc_id=$u['defstock']; $query = "INSERT INTO `nir` ( `id` ,`number` ,`rawvalue` ,`value` ,`content`, `ondate` ,`userid` ,`stockid` ,`provider` ,`fromActId` ,`fromActAdvId` ,`onValuta` ,`cursValue` ,`observatii` , `documentType` ,`documentNr` ,`documentDate` ,`toStock`,`loc_id` ) VALUES ( NULL , '$number', '$TotalValueWithoutTvaRon', '$TotalValueWithTvaRon', '$content', $date, '$userid', '$defstock', '$provider', '', '', '$onValuta', '$cursValue', '$observatii', '$documentType', '$documentNr', '$expdate', '$toStock', '$loc_id' );"; mysql_query( $query ) or die($query." ".mysql_error()); ?>= 0"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; else { while( $row = mysql_fetch_array( $results ) ) $expenses[ $row["id"] ] = $row; return $expenses; } } function nir_getNirNumber( $pageno, $orderby, $loc_id ) { if ($loc_id) $l="WHERE `loc_id`='$loc_id'"; else $l=""; $query = "SELECT * FROM `nir` $l ORDER BY `id` $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT 0, 1"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function uploadimportcsv($filename) { if((!empty($_FILES[$filename])) && ($_FILES[$filename]['error'] == 0)) { // Ellenorizzuk, hogy az .jpg vagy .png kiterjesztesu-e es hogy kisebb 500kb-nal $file = basename($_FILES[$filename]['name']); $ext = substr($file, strrpos($file, '.') + 1); if (((($ext == "csv")) || (($ext == "CSV") ) || (($ext == "Csv") ) && ($_FILES[$filename]["size"] < 1000000000))) { // Hova kell feltoltsuk + generalunk egy nevet neki a tempfile alapjan es hozzafuzzuk a kiterjesztest $kapott=str_replace("/","_",$_FILES[$filename]["tmp_name"]); $newname = dirname(__FILE__).'/images/uploaded/'.$kapott.".".$ext; // Ellenorizzuk, hogy letezik-e mar if (!file_exists($newname)) { // Ha nem letezik, felpakoljuk if ((move_uploaded_file($_FILES[$filename]['tmp_name'],$newname))) { $mess= getTraducere("Fisierul a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=false; } else { $mess= getTraducere("Gresit! Fisierul nu prea a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=true; } } else { $mess= getTraducere("Greseala: Fisierul ",$_SESSION["settings"]["default_lang"]).$_FILES["uploaded_file"]["name"]." ".getTraducere("deja exista!",$_SESSION["settings"]["default_lang"]); $err=true; } } else { $mess= getTraducere("Greseala: Numai .jpg si .png sub 1000kb poate fi uploadat!!!",$_SESSION["settings"]["default_lang"]); $err=true; } } else { $mess= getTraducere("Greseala: Fisierul nu a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=true; } if(!$err) $MessageHelpDialog=$mess; else $errorMessageHelpDialog=$mess; include("global_helpDialog.php"); return $newname; } function addPartenerCsv($name,$contactperson,$bank,$iban,$web,$country,$statename,$city,$address,$orcnumber,$cui,$phone,$fax,$mobile,$email,$stateid,$codpostal,$ispartner) { $query="INSERT INTO `partners`(`name`,`contactperson`,`country`,`state`,`city`,`address`,`orcnumber`,`bank`,`iban`,`cui`,`phone`,`fax`,`mobile`,`xemail`,`web`,`active`,`forname`,`lastname`,`cnp`,`birthdate`,`ispartner`,`sold`,`avanssold`,`limit`,`newsletter`,`codpostal`,`stateid`,`clientstate`,`partnersType`,`partnersDomain`,`ondate`,`userid`,`stockid`,`tags`,`partnersIsPartner`) VALUES('$name','$contactperson','$country','$statename','$city','$address','$orcnumber','$bank','$iban','$cui','$phone','$fax','$mobile','$email','$web',NULL,'','',NULL,NULL,'$ispartner','0','0','0','0','$codpostal','$stateid','1','1','0',NOW(),'34','1','','0')"; $result=mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function addAbonatCsv($name,$contactperson,$country,$state,$city,$address,$phone,$fax,$mobile,$email,$web,$forname,$lastname,$categoryId) { $name=mysql_escape_string($name); $email=mysql_escape_string($email); $contactperson=mysql_escape_string($contactperson); $forname=mysql_escape_string($forname); $lastname=mysql_escape_string($lastname); $query="INSERT INTO `newsletterClients`(`name`,`contactperson`,`country`,`state`,`city`,`address`,`phone`,`fax`,`mobile`,`xemail`,`web`,`active`,`forname`,`lastname`,`newsletter_nr`,`ondate`,`categoryId`) VALUES('$name','$contactperson','$country','$state','$city','$address','$phone','$fax','$mobile','$email','$web','1','$forname','$lastname',0,NOW(),'$categoryId')"; $result=mysql_query($query) or die($query.mysql_error()); return mysql_insert_id(); } function getCountyByName($name) { $query="SELECT `id` FROM `cities_Counties` WHERE `name`='$name'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row["id"]; } function UploadCounty($name,$country) { $query="INSERT INTO `cities_Counties`(`name`,`country`) VALUES('$name','$country')"; $result=mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function getCityByName($name,$judetid) { $query="SELECT `id` FROM `cities_new` WHERE `name`='$name' AND `judetid`='$judetid'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { $row=mysql_fetch_array($result); return $row["id"]; } $query="SELECT MAX(`id`) AS anyad FROM `cities_new`"; $res=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($res); $id=intval($row["anyad"])+1; $query="INSERT INTO `cities_new`(`id`,`judetid`,`name`,`country`) VALUES('$id','$judetid','$name','$country')"; $result=mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function UploadCity($judetid,$name,$country) { $query="SELECT MAX(`id`) AS anyad FROM `cities`"; $res=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($res); $id=intval($row["anyad"])+1; $query="INSERT INTO `cities`(`id`,`judetid`,`name`,`country`) VALUES('$id','$judetid','$name','$country')"; $result=mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function addPunctDeLucruCsv($clientid,$tara,$judet,$oras,$adresa,$sediu,$contact,$judetid) { $query="INSERT INTO `partners_punctDeLucru`(`clientid`,`number`,`tara`,`judet`,`oras`,`adresa`,`sediu`,`contactPerson`,`judetid`) VALUES('$clientid','0','$tara','$judet','$oras','$adresa','$sediu','$contact','$judetid')"; $result=mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function addContactCsv($clientid,$namearr,$hrtype,$email,$mobile,$telfix) { $query="INSERT INTO `partners_contact`(`clientid`,`userid`,`stockid`,`ondate`,`forname`,`lastname`,`hrType`,`decisionForce`,`departament`,`email`,`tel`,`telfix`,`activ`,`buletinSeria`,`buletinNr`,`buletinElib`) VALUES('$clientid','1','1',NOW(),'".$namearr[0]."','".$namearr[1]."','$hrtype','','','$email','$mobile','$telfix','1','','','')"; $result=mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function getModelCsColsForImportCSV() { $query="SELECT * FROM `models_cs` order by `name`"; $result=mysql_query($query) or die(mysql_error()); $all=""; while($row=mysql_fetch_array($result)) { $all[$row['id']]=$row; } return $all; } function getProdByCode($code) { $query="SELECT * FROM `container` WHERE `code`='$code'"; $result=mysql_query($query) or die(mysql_error()); if(mysql_num_rows($result)<1) return NULL; $row=mysql_fetch_array($result); return $row; } function uploadProdus($modelid,$name,$code,$code_produs,$desc,$price,$pret_promo,$pret_partner,$monytype,$minQuantity,$cs1,$cs2,$cs3,$cs4,$cs5,$cs6,$cs7,$cs8,$cs9,$cs10,$cs11,$cs12,$cs13,$cs14,$cs15,$cs16,$cs17,$cs18,$cs19,$cs20,$image,$lang) { $query="INSERT INTO `container`(`modelid`,`ondate`,`active`,`code_copy`,`name`,`code`,`code_produs`,`desc`,`price`,`pret_promo`,`pret_partner`,`monytype`,`minQuantity`,`cs1`,`cs2`,`cs3`,`cs4`,`cs5`,`cs6`,`cs7`,`cs8`,`cs9`,`cs10`,`cs11`,`cs12`,`cs13`,`cs14`,`cs15`,`cs16`,`cs17`,`cs18`,`cs19`,`cs20`,`image`,`visited`,`partnerid`,`lang`) VALUES ('$modelid',NOW(),1,0,'$name','$code','$code_produs','$desc','$price','$pret_promo','$pret_partner','$monytype','$minQuantity','$cs1','$cs2','$cs3','$cs4','$cs5','$cs6','$cs7','$cs8','$cs9','$cs10','$cs11','$cs12','$cs13','$cs14','$cs15','$cs16','$cs17','$cs18','$cs19','$cs20','','','','$lang')"; $result=mysql_query($query) or die(mysql_error()); $prodid=mysql_insert_id(); if($image=="") return NULL; if(file_exists("images/uploaded/".$image)) { $query="INSERT INTO `container_images`(`prodid`,`path`) VALUES ('$prodid','$image')"; $result=mysql_query($query) or die(mysql_error()); return NULL; } else { return "".$image.""; } } function uploadProdusStock($modelid,$name,$code,$code_produs,$desc,$price,$pret_promo,$pret_partner,$monytype,$minQuantity,$cs1,$cs2,$cs3,$cs4,$cs5,$cs6,$cs7,$cs8,$cs9,$cs10,$cs11,$cs12,$cs13,$cs14,$cs15,$cs16,$cs17,$cs18,$cs19,$cs20,$image,$lang) { $query="INSERT INTO `container`(`modelid`,`ondate`,`active`,`code_copy`,`name`,`code`,`code_produs`,`desc`,`price`,`pret_promo`,`pret_partner`,`monytype`,`minQuantity`,`cs1`,`cs2`,`cs3`,`cs4`,`cs5`,`cs6`,`cs7`,`cs8`,`cs9`,`cs10`,`cs11`,`cs12`,`cs13`,`cs14`,`cs15`,`cs16`,`cs17`,`cs18`,`cs19`,`cs20`,`image`,`visited`,`partnerid`,`lang`) VALUES ('$modelid',NOW(),1,0,'$name','$code','$code_produs','$desc','$price','$pret_promo','$pret_partner','$monytype','$minQuantity','$cs1','$cs2','$cs3','$cs4','$cs5','$cs6','$cs7','$cs8','$cs9','$cs10','$cs11','$cs12','$cs13','$cs14','$cs15','$cs16','$cs17','$cs18','$cs19','$cs20','','','','$lang')"; $result=mysql_query($query) or die(mysql_error()); $prodid=mysql_insert_id(); return $prodid; } function uploadModelCsValue($modelcsid,$name) { $query="INSERT INTO `models_cs_values`(`modelcsid`,`name`,`lang`) VALUES('$modelcsid','$name','')"; $result=mysql_query($query) or die(mysql_error()); $id= mysql_insert_id(); return $id; } function uploadUpdateProdus($prodid,$col,$val) { $query="UPDATE `container` SET `$col`='$val' WHERE `id`='$prodid'"; $res=mysql_query($query) or die(mysql_error()); } function uploadUpdateModelCsValue($csid,$col,$val) { $query="UPDATE `models_cs_values` SET `$col`='$val' WHERE `id`='$csid'"; $res=mysql_query($query) or die(mysql_error()); } function getModelByName($name,$lng) { $query="SELECT * FROM `models` WHERE `name`='$name'"; $result=mysql_query($query) or die(mysql_error()); if(mysql_num_rows($result)<1) return NULL; $row=mysql_fetch_array($result); return $row; } function getModelCsValueByName($modelcsid,$name,$lng) { $query="SELECT * FROM `models_cs_values` WHERE `modelcsid`='$modelcsid' AND `name`='$name'"; $result=mysql_query($query) or die(mysql_error()); if(mysql_num_rows($result)<1) { return NULL; } $row=mysql_fetch_array($result); return $row["id"]; } function getModelById( $modelId ) { $query = "SELECT * FROM `models` WHERE `id`='$modelId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $model = mysql_fetch_array( $result ); return $model; } function entry_searchGenerateQuery( $keyword , $type , $stockid , $page , $order , $ordermode, $id, $modelsid, $like,$viewall,$userid) { if( !isset( $page ) )$page = 1; $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; if ($like==0) $l=" LIKE '$keyword%'"; else $l=" LIKE '%$keyword%'"; if($viewall!="1") { $viewquery= " AND ( m.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) ) "; } if( strlen( $keyword ) > 0 ) { if( $type == "code" ) $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( c.code $l)".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery." ORDER BY c.modelid $ordermode LIMIT $from,$howmany"; elseif($type=="name") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( c.name $l)".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery." ORDER BY c.modelid $ordermode LIMIT $from,$howmany"; elseif($type=="desc") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( c.desc $l)".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery." ORDER BY c.modelid $ordermode LIMIT $from,$howmany"; elseif($type=="all") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( c.name $l OR c.desc $l OR c.code $l)".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery." ORDER BY c.modelid $ordermode LIMIT $from,$howmany"; } else $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery." ORDER BY c.modelid $ordermode LIMIT $from,$howmany"; return $query; } function entry_searchGenerateQueryAll( $keyword , $type , $stockid , $page , $order , $ordermode, $id, $modelid ) { if ($modelid=='') $model=''; else $model=" `c`.`modelid`='$modelid' AND "; if( !isset( $page ) )$page = 1; $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; if( strlen( $keyword ) > 0 ) { if( $type == "code" ) $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND $model ( c.code LIKE '%$keyword%') ORDER BY c.modelid $ordermode"; elseif($type=="name") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND $model ( c.name LIKE '%$keyword%') ORDER BY c.modelid $ordermode"; elseif($type=="desc") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND $model ( c.desc LIKE '%$keyword%') ORDER BY c.modelid $ordermode"; elseif($type=="all") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND $model ( c.name LIKE '%$keyword%' OR c.desc LIKE '%$keyword%' OR c.code LIKE '%$keyword%') ORDER BY c.modelid $ordermode"; } else $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE $model c.modelid=m.id ORDER BY c.modelid $ordermode"; return $query; } function getAllopinionall($order,$limit) { $query="SELECT * from opinie ORDER BY datum DESC LIMIT ".$order.",".$limit; $all=mysql_query( $query ) or die(mysql_error()); if($all) while ($listAll=mysql_fetch_array($all)) { $result[$listAll["id"]]=$listAll; } return $result; } function UploadModel($name) { $query="INSERT INTO `models`(`name`) VALUES('$name')"; $result=mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function getOrase($judet) { return getCitiesWithOld($judet); } function getCoduri($oras) { $query="SELECT * FROM `codpostal` WHERE `cityid`='$oras' ORDER BY `strada`"; $result= mysql_query($query) or die(mysql_error()); if($result&& mysql_num_rows($result)>0) { while($row= mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function getCodPostalById($id) { $query="SELECT * FROM `codpostal` WHERE `id`='$id'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row; } function contract_getcontractForComanda( $pageno = -1, $orderby ) { $query = "SELECT * FROM `contractForComanda` WHERE `active` ='1' ORDER BY secondserial DESC"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } //comandaInterna resz function command_getPartnercomandaIntern( $clientid, $pageno = -1, $orderby = "desc" ) { $query = "SELECT * FROM `comandaInterna` WHERE `clientid`=$clientid AND `active` ='1' ORDER BY numberSerial $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getcomandaInterna( $pageno = -1, $orderby ) { $query = "SELECT * FROM `comandaInterna` WHERE `active` ='1' ORDER BY `numberSerial` $orderby"; if ($pageno > 0) { $count = $_SESSION["settings"]["searchcount"]; $from = ($pageno - 1) * $count; $query = $query . " LIMIT $from, $count"; } $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function command_getcomandaInternaPunct( $defStockId , $pageno = -1, $orderby ) { $query = "SELECT * FROM `comandaInterna` command, `users` users WHERE command.`active` ='1' AND command.`userid`=users.`id` AND users.`defstock` = '$defStockId' ORDER BY command.`id` ASC"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $counter=0; while( $row = mysql_fetch_array( $results ) ) { $facturi[ $row["id"] ] = $row; $counter++; } return $counter; } function getComandaInternaFromComanda($commandid) { $query="SELECT * FROM `comandaInterna` WHERE `fromActAdvId`='$commandid' AND `partnerTermen`!='0000-00-00'"; $result=mysql_query( $query ) or die(mysql_error()); $lista=array(); while ($row=mysql_fetch_array($result)) $lista[]=$row; return $lista; } function getComandaInternaFromComandaId($commandid) { $query="SELECT * FROM `comandaInterna` WHERE `fromActAdvId`='$commandid' "; $result=mysql_query( $query ) or die(mysql_error()); $lista=array(); while ($row=mysql_fetch_array($result)) $lista[]=$row; return $lista; } function getcomandaInterna($commandid) { $query="SELECT * FROM `comandaInterna` WHERE `id`='$commandid'"; $result=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($result); return $row; } function getcomandaInternaItems($commandid) { $query="SELECT * FROM `comandaInternaItems` WHERE `comandaid`='$commandid'"; $result=mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) { $list[ $row["id"] ] = $row; } return $list; } function getcomandaInternaItemsCount($commandid) { $query="SELECT * FROM `comandaInternaItems` WHERE `comandaid`='$commandid'"; $i=0; $result=mysql_query( $query ) or die(mysql_error()); while( $row = mysql_fetch_array( $result ) ) { $i++; } return $i; } function stats_comandaInternaGenerateQuery( $fromDate , $toDate ) { $toDate = mysql_nextDay( $toDate ); $query = "SELECT `f`.*, `p`.`name` FROM `comandaInterna` f, `partners` p WHERE `p`.`id` = `f`.`clientid` AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; return $query; } function comandaInterna_delete( $facturaId ) { $query = "DELETE FROM `comandaInterna` WHERE `id`='$facturaId' LIMIT 1;"; $result = mysql_query( $query ) or die(mysql_error()); } function command_addcomandaInterna( $clientid , $userid , $stockid , $rawvalue , $value , $number, $content , $termenDePlata, $dataExecutiei, $onValuta , $cursValue, $_comments, $clientPunctLucru, $contactPerson,$location,$fromActAdvId,$scadenta,$observatii,$stateStatus,$depid,$contentWP) { $content = addslashes ($content); $contentWP = addslashes ($contentWP); $insertQ = "INSERT INTO `comandaInterna` ( `id` , `clientid` , `userid` , `stockid` , `numberSerial` , `rawValue` , `value` , `currency` , `cursValue` , `partnerTermen` , `content` , `ondate` , `active` , `printed` , `closed` , `comments`, `clientPunctLucru`, `termenExecutiei`, `contactPerson`, `locationId`, `fromActAdvId`, `scadenta`, `observatii`, `stateStatus`, `departament`, `contentWithoutPrices` ) VALUES (NULL , '$clientid', '$userid', '$stockid' , '$number', '$rawvalue', '$value', '$onValuta', '$cursValue', '$termenDePlata' , '$content', NOW(), '1', '0', '0', '$_comments','$clientPunctLucru', '$dataExecutiei','$contactPerson','$location','$fromActAdvId','$scadenta','$observatii','$stateStatus','$depid','$contentWP');"; mysql_query( $insertQ ) or die(mysql_error()); $facturid = mysql_insert_id (); return $facturid; } function comandaInterna_registerItems( $factid , $productid, $stockid , $productname , $unitprice , $moneytype, $um, $quantity , $quantity_real,$pricewithouttva , $tva, $TVAcalculare , $type , $toHr) { $query = "INSERT INTO comandaInternaItems VALUES (NULL, '$factid', NOW() , '$productid', '$stockid', '$productname', '$unitprice' , '$moneytype', '$um' , '$quantity','$quantity_real', '$pricewithouttva' , '$tva' , '$TVAcalculare','$type','$toHr');"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function comandaInterna_unRegisterItems( $factid ) { $query = "DELETE FROM `comandaInternaItems` WHERE `comandaInternaItems`.`comandaid` = '$factid';"; mysql_query( $query ) or die(mysql_error()); $_SESSION["comandaInterna"]["edited"]=1; } function comandaInterna_setActiveNess( $factid , $state ) { $update = "UPDATE `comandaInterna` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function comandaInterna_modFactura( $id, $clientid , $userid , $stockid , $rawvalue , $value , $number, $content , $termenDePlata, $dataExecutiei, $onValuta , $cursValue, $_comments, $clientPunctLucru, $contactPerson,$location,$scadenta,$observatii,$stateStatus,$depid,$contentWP) { $content = addslashes ($content); $contentWP = addslashes ($contentWP); $updateQ = "UPDATE `comandaInterna` SET `clientid` = '$clientid', `content` = '$content', `contentWithoutPrices` = '$contentWP', `rawvalue` = '$rawvalue', `value` = '$value', `currency` = '$onValuta', `partnerTermen` = '$termenDePlata', `comments` = '$_comments', `clientPunctLucru` = '$punctdelucru', `termenExecutiei` = '$dataExecutiei', `contactPerson` = '$contactperson', `locationId` = '$location', `scadenta` = '$scadenta', `observatii` = '$observatii', `stateStatus` = '$stateStatus', `departament` = '$depid', `cursValue` = '$cursValue' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function comandaInterna_setPrinted( $id , $value ) { $updateQ = "UPDATE `comandaInterna` SET `printed` = '$value' WHERE `id` ='$id' LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function comandaInterna_setClosed( $id , $value ) { $updateQ = "UPDATE `comandaInterna` SET `closed` = '$value' WHERE `id` ='$id' LIMIT 1 ; "; mysql_query( $updateQ ) or die(mysql_error()); } function comandaInterna_setSerial( $id , $serial ) { $update = "UPDATE `comandaInterna` SET `serial`='".$serial["serial"]."',`number`='".$serial["number"]."' WHERE `id`='$id' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function comandaInterna_getFacturi() { $select = "SELECT * FROM `comandaInterna`"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row["id"] ] = $row; } return $facturi; } function comandaInterna_getFactura( $id ) { $select = "SELECT * FROM `comandaInterna` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function generateDataFromcomandaInterna( $id ) { $select = "SELECT * FROM `comandaInterna` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function generateDataFromBonConsum( $id ) { $select = "SELECT * FROM `bonConsum` WHERE `id`='$id' LIMIT 1;"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; return ( $row = mysql_fetch_array( $result ) ); } function comandaInterna_searchGenerateQuery( $searchval , $searchcriteria , $page , $orderby , $ordermode , $fromDate , $toDate , $filter_menu, $firstserial, $secondserial, $serial, $dataLabel, $location , $locationId,$viewall=1,$userid=0) { //hanyat akar egy oldarra megjeleniteni $count = $_SESSION["settings"]["searchcount"]; ///honnan kezdje $from = ($page - 1) * $count; $toDate = mysql_nextDay( $toDate ); if($viewall!="1") { $viewquery= " AND ( f.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR f.`userid`='$userid') "; } //location if($location!=0) { $selectedStock = stock_getStockFromLocation($location); $selectedId = $selectedStock["id"]; $locationSql = " AND f.`stockid` = '$selectedId'"; } else { $locationSql = ""; } //location if($locationId!=0) { $locationIdSql = " AND f.`locationId` = '$locationId'"; } else { $locationIdSql = ""; } //datumszuro be ki kapcsolasa if($searchval!=NULL && $searchcriteria!="serial") $dateFilter=""; else $dateFilter = "AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'"; // filter menut a linkbol kapja valtozokent vagy a cautare postolasakor // itt kezelunk le kulonbozo esteket //filter_menu if($filter_menu == NULL) $filterMenuSql=""; if($filter_menu == "nefacturate") { $query = "SELECT `f`.* FROM `comandaInterna` f, `facturi` fact WHERE `f`.`id` <> `fact`.`fromActId` ".$plus_search.$locationSql.$locationIdSql." AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate'".$viewquery; $result = mysql_query($query) or die(mysql_error()); } if($filter_menu == "faraprofit") { if ($searchcriteria == "serial" && $searchval!=NULL) $plus_search="AND `f`.`number` = '$searchval'"; else $plus_search="AND `p`.`name` LIKE '%$searchval%'"; $query = "SELECT `f`.*, `p`.`name` FROM `comandaInterna` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$plus_search.$locationSql.$locationIdSql.$viewquery." AND `f`.`profit` < 0 AND `f`.`ondate` BETWEEN '$fromDate' AND '$toDate' ORDER BY $orderby $ordermode"; $result = mysql_query($query) or die(mysql_error()); } if($filter_menu != "nefacturate" && $filter_menu != "faraprofit") { if($filter_menu == "anulate") $filterMenuSql=" AND `f`.active = '0' "; if($filter_menu == "valabile") $filterMenuSql=" AND `f`.active = '1' "; if($filter_menu == "printate") $filterMenuSql=" AND `f`.printed = '1'"; if($filter_menu == "neprintate") $filterMenuSql=" AND `f`.printed = '0'"; if ($searchcriteria == "serial") { if($firstserial!=NULL) $serialFilter.= " AND `f`.`firstserial` = '$firstserial'"; if($secondserial!=NULL) $serialFilter.= " AND `f`.`secondserial` = '$secondserial'"; if($serial!=NULL) $serialFilter.= " AND `f`.`numberSerial` = '$serial'"; if($dataLabel!=NULL) { $yearActual = substr($dataLabel,0,2); $monthActual = substr($dataLabel,2,2); $startDate = "20".$yearActual."-".$monthActual."-01"; $endDate = "20".$yearActual."-".$monthActual."-31"; $serialFilter.= " AND `f`.`ondate` BETWEEN '$startDate' AND '$endDate'"; } $query = "SELECT `f`.*, `p`.`name` FROM `comandaInterna` f, `partners` p WHERE `p`.`id` = `f`.`clientid` ".$serialFilter.$filterMenuSql.$locationSql.$locationIdSql.$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } ///ha nics szurve else { $query = "SELECT `f`.*, `p`.`name` FROM `comandaInterna` f, `partners` p WHERE `p`.`name` LIKE '%$searchval%' AND `p`.`id` = `f`.`clientid` ".$dateFilter.$filterMenuSql.$locationSql.$locationIdSql.$viewquery." ORDER BY $orderby $ordermode LIMIT $from, $count"; } } return $query; } function comandaInterna_searchFactura( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() < 1 ) return NULL; while( $row = mysql_fetch_array( $result ) ) { $facturi[ $row[ "id" ] ] = $row; } return $facturi; } function getCommandInternRegisteredItem ($itemId) { $query = "SELECT * FROM `comandaInternaItems` WHERE `comandaid` = '$itemId' order by `id`"; $result = mysql_query( $query ) or die(mysql_error()); $counter=1; while( $row = mysql_fetch_array( $result ) ) { $entry[ $counter ] = $row; $counter++; } return $entry; } function getCommandInternRegisteredItemsCount ($commandId) { $query = "SELECT * FROM `comandaInternaItems` WHERE `comandaid` = '$commandId';"; $result = mysql_query( $query ) or die(mysql_error()); $counter=0; while( $row = mysql_fetch_array( $result ) ) { $counter++; $entry[ $counter ] = $row; } return $counter; } function commandaInterna_getFacturaGeneratedCount( $fromActId ) { $select = "SELECT COUNT(*) AS counting FROM `comandaInterna` WHERE (`fromActAdvId`='$fromActId' || `fromActAdvId` LIKE '%$fromActId,%') AND `active` = '1'"; $result = mysql_query( $select ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $result ); return $row["counting"]; } function getCitiesWithOld($judet) { $query="SELECT * FROM `cities_new`".($judet!="0"?" WHERE `judetid`='$judet'":"")." ORDER BY `name`"; $result= mysql_query($query) or die(mysql_error()); if($result&& mysql_num_rows($result)>0) { while($row= mysql_fetch_array($result)) $all[$row["id"]]=$row; } $query="SELECT * FROM `cities` ORDER BY `name`"; $result= mysql_query($query) or die(mysql_error()); if($result&& mysql_num_rows($result)>0) { while($row= mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function getInstitutii($oras){ $query="SELECT * FROM `institutii`".($oras!="0"?" WHERE `city_id`='$oras'":"")." ORDER BY `name`"; $result= mysql_query($query) or die(mysql_error()); $all=array(); while($row= mysql_fetch_array($result)) $all[$row["id"]]=$row; return $all; } function getTipClient($lang){ $query="SELECT * FROM `tip_client` WHERE `lang`='$lang' ORDER BY `name`"; $result= mysql_query($query) or die(mysql_error()); $all=array(); while($row= mysql_fetch_array($result)) $all[$row["id"]]=$row; return $all; } function getMaterieJuridica($lang){ $query="SELECT * FROM `materie_juridica` WHERE `lang`='$lang' ORDER BY `name`"; $result= mysql_query($query) or die(mysql_error()); $all=array(); while($row= mysql_fetch_array($result)) $all[$row["id"]]=$row; return $all; } function getObiectDosar($lang){ $query="SELECT * FROM `obiect_dosar` WHERE `lang`='$lang' ORDER BY `name`"; $result= mysql_query($query) or die(mysql_error()); $all=array(); while($row= mysql_fetch_array($result)) $all[$row["id"]]=$row; return $all; } function getStadiuProcesual($lang){ $query="SELECT * FROM `stadiu_procesual` WHERE `lang`='$lang' ORDER BY `name`"; $result= mysql_query($query) or die(mysql_error()); $all=array(); while($row= mysql_fetch_array($result)) $all[$row["id"]]=$row; return $all; } function updateMenuFileOrder($menuid, $order, $fileid) { $query = "select * from content_images where prodid = '$menuid'"; $res = mysql_query( $query ) or die(mysql_error()); while($row = mysql_fetch_array($res)) { if ($row["ord"] == $order) { $saved_id = $row["id"]; } if ($row["id"] == $fileid) { $saved_order = $row["ord"]; } } $quer1 = "update content_images set ord = '$saved_order' where id = '$saved_id'"; mysql_query($quer1) or die ("change file order 1".mysql_error()); $quer2 = "update content_images set ord = '$order' where id = '$fileid'"; mysql_query($quer2) or die ("change file order 2".mysql_error()); } function addWebUserCsv($username,$password,$clid,$email,$ccd) { $insertQ = "INSERT INTO `users_website` ( `username` , `upassworld` , `clientid` , `email` , `active` , `code` ) VALUES ( '$username',PASSWORD('$password'),'$clid','$email','1','$ccd')"; $res=mysql_query($insertQ) or die(mysql_error()); } function getCountyByNameCsv($name) { $name=trim(strtolower($name)); $name=str_replace(array(' ','-'),array('',''),$name); $query="SELECT `id` FROM `cities_Counties` WHERE REPLACE(REPLACE(`name`,' ',''),'-','')='$name'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row["id"]; } function getCityByNameCsv($name,$judetid,$country) { $name=trim(strtolower($name)); $name=str_replace(array(' ','-'),array('',''),$name); $query="SELECT `id` FROM `cities_new` WHERE REPLACE(REPLACE(`name`,' ',''),'-','')='$name'".($judetid!=""&&$judetid!="0"?"AND `judetid`='$judetid'":""); $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { $row=mysql_fetch_array($result); return $row["id"]; } $query="SELECT MAX(`id`) AS anyad FROM `cities_new`"; $res=mysql_query( $query ) or die(mysql_error()); $row=mysql_fetch_array($res); $id=intval($row["anyad"])+1; $query="INSERT INTO `cities_new`(`id`,`judetid`,`name`,`country`) VALUES('$id','$judetid','$name','$country')"; $result=mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function replaceRomanianCharachters($content) { $mit = array("�T","�>","�f","î","â","�~","�s","�,","�Z","�,","ţ","�T"); $mire = array("ş","ţ","ă","î","â","Ş","Ţ","Ă","Î","Â","ţ","ş"); $content = str_replace($mit,$mire,$content); return $content; } function getWebUserForClient($partnerid) { $query="SELECT * FROM `users_website` WHERE `clientid`='$partnerid' AND `clientid`!=0"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row; } function addWebUserForPartner($clientid,$username,$password,$email,$active) { $code=generateCode(6); $query="INSERT INTO `users_website`(`username`,`upassworld`,`clientid`,`email`,`active`,`code`) VALUES('$username',PASSWORD('$password'),'$clientid','$email','$active','$code')"; mysql_query($query) or die(mysql_error()); } function updateWebUserForPartner($clientid,$username,$password,$xemail,$active) { $query="UPDATE `users_website` SET `username`='$username',`active`='$active' WHERE `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); if($password!="password") { $query="UPDATE `users_website` SET `upassworld`=PASSWORD('$password') WHERE `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); } } //monitorizare fuggvenyei //megvizsgalja, hogy a kert cim letezik-e, 1-et terit vissza, ha igen function is_availableURL($url, $timeout = 30) { $ch = curl_init(); // get cURL handle // set cURL options $opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser CURLOPT_URL => $url, // set URL CURLOPT_NOBODY => true, // do a HEAD request only CURLOPT_TIMEOUT => $timeout); // set timeout curl_setopt_array($ch, $opts); curl_exec($ch); // do it! $retval = curl_getinfo($ch, CURLINFO_HTTP_CODE); // check if HTTP OK curl_close($ch); // close handle if ($retval!=404) return true; else return false; } function createArraytocrm($page,$obs){ $compInfo = admin_getCompanyDetails();//sajat adatok $kliens=getClientbyname($compInfo['name']); $u=getAngajatbyUserid($page['user_id']); $event=array(); $event['userid']=$page['user_id']; $event['eventcatid']="8"; $event['clientid']=$kliens['id']; $event['contactsid']=0; $event['dateValue']=date("Y-m-j G:i:s"); $event['durata']=0; $event['deadlineValue']=''; $event['eventtcatid']="3"; $event['observatii']=$obs; $event['starry0']="1"; $event['eventstatus']="1"; $event['avertizare']="0"; $event['hrid']=$u['id']; $event['carid']="0"; $event['oportunityvalue']="0"; $event['onValuta']=""; $event['where']="0"; $event['wherej']="0"; $event['address']=""; $event['serviciiproduse']=""; return $event; } function crm_addeventMonitor( $array ) { foreach( $array as $key => $xvalue ) $$key = $xvalue; $query = "INSERT INTO `crm_events` ( `id` , `ondate` , `userid` , `stockid` , `categoryId` , `clientid` , `contactid` , `dateFor` ,`duration`,`deadline`,`eventType`, `observation`,`priority`,`state`,`eventAvertTime`,`asignedTo`,`asignedToCar`,`oportunityValue`,`onvaluta`,`cityId`,`judetId`,`address`,`products`) VALUES ( NULL , NOW(), '".$userid."', '".$_SESSION["user"]["defstock"]."', '$eventcatid', '$clientid', '$contactsid', '$dateValue','$durata','$deadlineValue','$eventtcatid','$observatii','$starry0','$eventstatus','$avertizare','$hrid','$carid','$oportunityvalue','$onValuta','$where','$wherej','$address','$serviciiproduse');"; mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } function getClientbyname($name){ $query="SELECT `id` FROM `partners` WHERE `name` LIKE '%$name%'"; $result = mysql_query($query) or die(mysql_error()); return mysql_fetch_array( $result ); } function getAngajatbyUserid($userid){ $query="SELECT * FROM `hr` WHERE `userid`=$userid"; $result = mysql_query($query) or die(mysql_error()); return mysql_fetch_array( $result ); } //lekerdezi a megfigyelni valo site-ok adott ($data) mezojet function getMonitorArchives($id){ $query="SELECT * FROM `monitor_pages_archive` WHERE `id`='$id' "; $result = mysql_query($query) or die(mysql_error()); return mysql_fetch_array( $result ); } //lekerdezi a megfigyelni valo site-ot id alapjan function getMonitor($id){ $query="SELECT * FROM `monitor_pages` WHERE `id`='$id' "; $result = mysql_query($query) or die(mysql_error()); return mysql_fetch_array( $result ); } //aktivalja vagy dezaktivalja a monitort id alapjan function activareMonitor($siteid,$active){ $query="UPDATE `monitor_pages` SET `active` = '$active' WHERE `id` ='$siteid'"; $result = mysql_query($query) or die(mysql_error()); return $result; } //kitorol egy archivumot id alapjan function removefromArchives($id,$pageid){ $query="DELETE FROM `monitor_pages_archive` WHERE `$id` = '$pageid'"; $result = mysql_query($query) or die(mysql_error()); return $result; } //hozzaad egy archivumot oldalid,aktiv ,tartalom function inserttoArchives($pageid,$active,$content){ $query="INSERT INTO `monitor_pages_archive` (`id`,`ondate`,`site_id`,`active`,`content`) VALUES (NULL , NOW(), '$pageid', '$active', '$content')"; $result = mysql_query($query) or die(mysql_error()); return $result; } //listazom a site archivumait es rendezi novekvobe function listArchives($siteid){ $query="SELECT * FROM `monitor_pages_archive` WHERE `site_id`='$siteid' AND active='1' order by `ondate`"; $result = mysql_query($query) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array( $result ) ) { $list[ $i++ ] = $row; } return $list; } //listazom az osszes archivumot es rendezi novekvobe function listAllArchives(){ $query="SELECT * FROM `monitor_pages_archive` WHERE active='1' order by `ondate`"; $result = mysql_query($query) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array( $result ) ) { $list[ $i++ ] = $row; } return $list; } //lekerdezi az osszes aktiv megfigyelni valo siteot amelynek a lejarati datuma meg nem jart le function listSitestoMonitor(){ $query="SELECT * FROM `monitor_pages` WHERE `active`='1' AND date_to > NOW()"; $result = mysql_query($query) or die(mysql_error()); $i=0; while( $row = mysql_fetch_array( $result ) ) { $list[ $i++ ] = $row; } return $list; } //lekerdezi hogy szerepel-e mar a megfigyelni valo site-ok adott ($data) mezoje function getDatafromMonitor($data,$datavalue,$user_id){ $query="SELECT * FROM `monitor_pages` WHERE `$data`='$datavalue' AND `user_id`='$user_id' "; $result = mysql_query($query) or die(mysql_error()); if(mysql_affected_rows ()==0){ return 1; } return 0; } //hogyha nem szerepel mar az adatbazisban, akkor beszurja a megfigyelni valo site-ot function insertMonitor($name,$url,$desc,$user_id,$active,$date_to,$tolerance,$work,$passive,$sleep){ if ($active=="on") $active=1; else $active=0; $query="SELECT * FROM `monitor_pages` WHERE `name`='$name' AND `url`='$url' AND `desc`='$desc' AND `user_id`='$user_id' AND `tolerance`=$tolerance AND `active`=$active AND `date_to`='$date_to'"; $result = mysql_query($query) or die(mysql_error()); if(mysql_affected_rows ()==0){ $query="INSERT INTO `monitor_pages` (`id`, `ondate`, `name`, `url`, `desc`, `user_id`, `active`, `date_to`,`tolerance`,`it_works`,`it_sleeps`,`sleep_time`) VALUES (NULL, NOW(), '$name', '$url', '$desc', '$user_id', '$active', '$date_to', '$tolerance', '$work','$passive','$sleep')"; $result = mysql_query( $query ) or die(mysql_error()); if($result) return 1; else return 0; } return 0; } //kitorol egy siteot id alapjan function removefromMonitor($pageid){ $query="DELETE FROM `monitor_pages` WHERE `id` = $pageid"; $result = mysql_query($query) or die(mysql_error()); return $result; } function updateMonitor($id,$name,$url,$desc,$user_id,$active,$date_to,$tolerance,$sleep){ if ($active=="on") $active=1; else $active=0; $query="UPDATE `monitor_pages` SET `name` = '".$name."',`url` = '".$url."',`desc` = '".$desc."', `active` = '".$active."',`date_to` = '".$date_to."',`tolerance` = '".$tolerance."',`sleep_time` = '".$sleep."' WHERE `monitor_pages`.`id` =$id"; $result = mysql_query($query) or die(mysql_error()); return $result; } //beallitja a site it_works(elerheto(1) vagy nem(0) a site) tulajdonsagat function setitWorksMonitor($id,$work){ $query="UPDATE `monitor_pages` SET `it_works` = '$work' WHERE `monitor_pages`.`id` =$id"; $result = mysql_query($query) or die(mysql_error()); return $result; } //beallitja a site it_sleeps(nincs modositas(1) vagy vanmodositas(0) a site) tulajdonsagat function setitSleepsMonitor($id,$sleep){ $query="UPDATE `monitor_pages` SET `it_sleeps` = '$sleep' WHERE `monitor_pages`.`id` =$id"; $result = mysql_query($query) or die(mysql_error()); return $result; } //lekerdezi a user osszes megfigyelni valo site-jat function listallMonitors($f,$p){ $query="SELECT * FROM `monitor_pages` ".$f." order by `name` ".$p; $result = mysql_query($query) or die("$query
".mysql_error()); $i=0; while( $row = mysql_fetch_array( $result ) ) { $list[ $i++ ] = $row; } return $list; } //visszateriti a kereses darabszamat function numberofallMonitors($f,$p){ $query="SELECT * FROM `monitor_pages` ".$f." ".$p; $result = mysql_query($query) or die(mysql_error()); return mysql_affected_rows(); } //monitorizare fuggvenyei vege //Bodor Szilard az utvonaltervezes fuggvenyeinek kezdete=========================================================== function saveTheTrase($array) { $query = "insert into traseuInteractiv(id, name, nr_persons,adaos,profit)values(NULL, '".$array["name"]."', '".$array["pers_nr"]."', '".$array["adaos"]."', '".$array["profit"]."')"; $res = mysql_query($query) or die("saveTheTrase ".mysql_error()); return mysql_insert_id(); } function updateTheTrase($traseid, $array) { $query = "update traseuInteractiv set name = '".$array["name"]."', nr_persons = '".$array["pers_nr"]."', adaos = '".$array["adaos"]."',profit = '".$array["profit"]."' where id = '$traseid'"; $res = mysql_query($query) or die("updateTheTrase ".mysql_error()); } function getAllCitis() { $query = "select * from cities"; $res = mysql_query($query) or die("getAllCities ".mysql_error()); $j=0; while($row = mysql_fetch_array($res)) { $list[$j] = $row; $j++; } return $list; } function getAllCitisById($id) { $query = "select * from cities where id = '$id' limit 1"; $res = mysql_query($query) or die("getAllCities ".mysql_error()); return mysql_fetch_array($res); } function insert_citi_for_trase($traseid,$countryid, $cityid, $cityindex) { $query = "insert into traseCities(id, traseid,countryid, cityid, cityindex)values(NULL, '$traseid','$countryid', '$cityid', '$cityindex')"; mysql_query($query) or die("insert_citi_for_trase ".mysql_error()); } function getTraseuById($id) { $query = "select * from traseuInteractiv where id = '$id'"; $result = mysql_query($query) or die ("getTraseuById ".mysql_error()); return mysql_fetch_array($result); } function deleteTraseuCitiesForSave($id) { $query = "delete from traseCities where traseid = '$id'"; $result = mysql_query($query) or die ("deleteTraseuCitiesForSave ".mysql_error()); } function getTraseuCitiesByTraseId($id) { $query = "select * from traseCities where traseid = '$id' order by id"; $result = mysql_query($query) or die ("getTraseuCitiesByTraseId ".mysql_error()); $j=0; while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function getAllTraseu() { $query = "select * from traseuInteractiv"; $result = mysql_query($query) or die ("getAllTraseu ".mysql_error()); $j=0; while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function FullDeleteTraseuById($traseid) { $query1 = "delete from traseuInteractiv where id = '$traseid'"; $resul1t = mysql_query($query1) or die ("deleteTraseuMaintraseu ".mysql_error()); $query = "delete from traseCities where traseid = '$traseid'"; $result = mysql_query($query) or die ("deleteTheCiteiesfromtraseu ".mysql_error()); } function getAllCheltuieliCategories() { $query = "select * from expenses_cat"; $result = mysql_query($query) or die ("getAllCheltuieliCategories ".mysql_error()); $j=0; while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function getCheltuieliCategoriesById($id) { $query = "select * from expenses_cat where id = '$id'"; $result = mysql_query($query) or die ("getAllCheltuieliCategories ".mysql_error()); return mysql_fetch_array($result); } function getFurnizoriForChelt() { $query = "select * from partners where ispartner = 1"; $result = mysql_query($query) or die ("getFurnizoriForChelt ".mysql_error()); $j=0; while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function getFurnizoriForCheltById($id) { $query = "select * from partners where ispartner = 1 and id = '$id'"; $result = mysql_query($query) or die ("getFurnizoriForChelt ".mysql_error()); return mysql_fetch_array($result); } function saveCheltuieli($trasid, $cityind, $name, $cat, $fur, $pr, $tva, $on_or_all, $observatii) { $query = "insert into traseCitiesExpens(`id`,`traseid`,`cityIndex`,`cheltName`,`cheltCat`,`cheltFurnizor`,`cheltPriceWOTVA`,`cheltTVA`,`persoanasautoti`,`Observatii`)values(NULL, '$trasid', '$cityind','$name','$cat','$fur','$pr','$tva', '$on_or_all', '$observatii')"; mysql_query($query)or die("saveCheltuieli ".mysql_error()); } function getCheltuieliForTrase($trasid) { $query = "select * from traseCitiesExpens where traseid = '$trasid' order by id"; $result = mysql_query($query) or die("getCheltuieli ".mysql_error()); $j=0; while($row = mysql_fetch_array($result)) { $lis[$j] = $row; $j++; } return $lis; } function deleteTraseuCheltuieliForSave($trasid) { $query = "delete from traseCitiesExpens where traseid = '$trasid'"; $result = mysql_query($query) or die("deleteTraseuCheltuieliForSave ".mysql_error()); } function my_counties_addCounty( $name, $countryname ) { $query = "INSERT INTO `cities_Counties` (`id` ,`name`, `country`, `coordinates` ) VALUES (NULL , '$name', '$countryname', '');"; $results = mysql_query( $query ) or die(mysql_error()); return mysql_insert_id(); } //az utvonal tervezes fuggvenyeinek vege=========================================================================== function avertizare_deleteAvertizariForCar($carid) { $query="DELETE FROM `avertizare_avertizariItems` WHERE `avertizare_id`='$carid' AND `mod_id` IN (6,8,15,16,17,18,19,20) "; $result=mysql_query($query) or die(mysql_error()); } function partner_deleteAvertizariForPartner($partnerid) { $query="DELETE FROM `avertizare_avertizariItems` WHERE `avertizare_id`='$partnerid' AND `mod_id` IN (5,14) "; $result=mysql_query($query) or die(mysql_error()); } function getUtilizatorForAvertizare($mod_id,$avertizare_id) { if($mod_id!="12"&&$mod_id!="13") { $query="SELECT * FROM `users` WHERE `id`= (SELECT `userid` FROM "; switch($mod_id) { case "2": $query.="`contractAngajat` WHERE `hrid`='$avertizare_id'"; break; case "3": $query.="`facturi` WHERE `id`='$avertizare_id'"; break; case "6": $query.="`cars` WHERE `id`='$avertizare_id'"; break; case "8": $query.="`cars` WHERE `id`='$avertizare_id'"; break; case "15": $query.="`cars` WHERE `id`='$avertizare_id'"; break; case "16": $query.="`cars` WHERE `id`='$avertizare_id'"; break; case "17": $query.="`cars` WHERE `id`='$avertizare_id'"; break; case "18": $query.="`cars` WHERE `id`='$avertizare_id'"; break; case "19": $query.="`cars` WHERE `id`='$avertizare_id'"; break; case "20": $query.="`cars` WHERE `id`='$avertizare_id'"; break; case "9": $query.="`comandaForClientAdv` WHERE `id`='$avertizare_id'"; break; case "11": $query.="`comandaForClientAdv` WHERE `id`='$avertizare_id'"; break; case "5": $query.="`partners` WHERE `id`='$avertizare_id'"; break; case "14": $query.="`partners` WHERE `id`='$avertizare_id'"; break; case "7": $query.="`fisaZilnicadeLucru` WHERE `id`='$avertizare_id'"; break; case "1": $query.="`stock_items` WHERE `id`='$avertizare_id'"; break; case "10": $query.="`expenses` WHERE `id`='$avertizare_id'"; break; } $query.=")"; } else $query="SELECT * FROM `users` WHERE `id`= (SELECT `userid` FROM `hr` WHERE `id`=(SELECT `asignedTo` FROM `crm_events` WHERE `id`='$avertizare_id') )"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row; } function getVerificatDe($id) { $query="SELECT * FROM `users` WHERE `id`=(SELECT `userid` FROM `avertizare_avertizariVerificari` WHERE `averizareItemId`='$id' ORDER BY `id` DESC LIMIT 1)"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row; } function deleteAllFacturaItems($stornoid) { $factura = factura_getFactura($stornoid); $items=factura_getFacturiItems($stornoid); foreach($items as $key=>$value) { if($value["period"]=="unic"&&$commandData["fromActAdvId"]!="") { $commandid=$commandData["fromActAdvId"]; $serviceid=$av["modelid"]; $rowid=getCommandRowIdForServiceFromFactura($commandid,$serviceid); $query="UPDATE `comandaForClientAdvItemsDates` SET `onFactura`='0' WHERE `itemsId`='$rowid' AND `commandid`='$commandid' AND `serviceid`='$serviceid'"; $result=mysql_query($query) or die(mysql_error()); } } } function avertizare_getAvertizariAllWithoutPageForUsers($usrid,$mod="") { $query="SELECT * FROM `avertizare_avertizariItems` WHERE `rezolvatDe`=0 AND ( CASE `mod_id` WHEN 2 THEN ( `avertizare_id` IN(SELECT `hrid` as idd FROM `contractAngajat` WHERE `userid` IN $usrid)) WHEN 3 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `facturi` WHERE `userid` IN $usrid )) WHEN 6 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid` IN $usrid )) WHEN 8 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid` IN $usrid )) WHEN 15 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid` IN $usrid )) WHEN 16 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid` IN $usrid )) WHEN 17 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid` IN $usrid )) WHEN 18 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid` IN $usrid )) WHEN 19 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid` IN $usrid )) WHEN 20 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `cars` WHERE `userid` IN $usrid )) WHEN 9 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `comandaForClientAdv` WHERE `userid` IN $usrid )) WHEN 11 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `comandaForClientAdv` WHERE `userid` IN $usrid )) WHEN 5 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `partners` WHERE `userid` IN $usrid )) WHEN 14 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `partners` WHERE `userid` IN $usrid )) WHEN 7 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `fisaZilnicadeLucru` WHERE `userid` IN $usrid )) WHEN 1 THEN ( `avertizare_id` IN(SELECT `itemid` as idd FROM `stock_items` WHERE `userid` IN $usrid )) WHEN 10 THEN ( `avertizare_id` IN(SELECT `id` as idd FROM `expenses` WHERE `userid` IN $usrid )) WHEN 12 THEN ( `avertizare_id` IN(SELECT `id` FROM `crm_events` WHERE `asignedTo` IN (SELECT `id` FROM `hr` WHERE `userid` IN $usrid) )) WHEN 13 THEN ( `avertizare_id` IN(SELECT `id` FROM `crm_events` WHERE `asignedTo` IN (SELECT `id` FROM `hr` WHERE `userid` IN $usrid) )) END )"; if($mod!=""&&$mod!="all") $query.=" AND `mod_id`='$mod' "; $query.=" order by id DESC"; $result=mysql_query($query) or die(mysql_error()); return $result; } function users_getAllUsers() { $query="SELECT * FROM `users`"; $result=mysql_query($query) or die(mysql_errror()); if($result&&mysql_num_rows($result)>0) while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; return $all; } function avertizare_getAvertizariAllWithoutPage($mod="") { $users=users_getAllUsers(); $cnt=0; $str="("; foreach($users as $uk=>$uv) { if($cnt==0) $str.=$uk; else $str.=",".$uk; $cnt++; } $str.=")"; $result=avertizare_getAvertizariAllWithoutPageForUsers($str,$mod); return $result; } function stock_insertRezervareProdus($commandid, $productId, $inchiriere, $quants, $defStock , $punct,$user_id,$date) { if ($date=='') $date='NOW()'; else $date="DATE_ADD('".$date."', INTERVAL 1 SECOND)"; print_r($productsList = stock_getProdIdFifo( $_SESSION["user"]["defstock"] , $productId, $quants+inchirieri_getProdQuantityLocation( $_SESSION["user"]["defstock"], $productId ) )); if($productsList) foreach( $productsList as $keyProds => $valueProds ) { $selectedProdid = $valueProds; $query = "SELECT * FROM `stock_items` WHERE `id` = '$selectedProdid'"; $result = mysql_query( $query ) or die($query." ".mysql_error()); $row = mysql_fetch_array( $result ); $stockQuantity = $row["quantity"]; $stockQuantityType = $row["quantityType"]; $stockId = $row["stockid"]; $stockQuantity = $stockQuantity - inchirieri_getProdQuantityExactStock($stockId,$row["itemid"],$row["id"]); //megnezni mi van kiadva belole if($stockQuantity!=0) { if($quants>$stockQuantity) { $quants = $quants-$stockQuantity; $quantityToMinus = $stockQuantity; } else { $quantityToMinus = $quants; $quants = 0; } $stockProdId = $row["itemid"]; if ( $quantityToMinus != $stockQuantity ) { $query2="INSERT INTO `rezervareProdus` VALUES('NULL','$stockProdId','$commandid','$punct','$quantityToMinus','$stockId','$selectedProdid','$user_id',$date)"; $result2=mysql_query( $query2 ) or die(mysql_error()); } else { $query2="INSERT INTO `rezervareProdus` VALUES('NULL','$stockProdId','$commandid','$punct','$stockQuantity','$stockId','$selectedProdid','$user_id',$date)"; $result2=mysql_query( $query2 ) or die(mysql_error()); } } } } function stock_unInsertRezervareProdusbyId($id) { $query="DELETE FROM `rezervareProdus` WHERE `id`='$id'"; $result=mysql_query( $query ) or die(mysql_error()); } function stock_unInsertRezervareProdus($comandaId) { $query="DELETE FROM `rezervareProdus` WHERE `comandaId`='$comandaId' AND `punctDeLucruId`!='0'"; $result=mysql_query( $query ) or die($query.mysql_error()); } function stock_unInsertRezervareProdusIntern($comandaId) { $query="DELETE FROM `rezervareProdus` WHERE `comandaId`='$comandaId' AND `punctDeLucruId`='0'"; $result=mysql_query( $query ) or die(mysql_error()); } function stock_unInsertRezervareProdusInternDirect($comandaId,$stockProdusId,$quantity) { $query = "SELECT `r`.* FROM `rezervareProdus` r WHERE `r`.`comandaId`='$comandaId' AND `r`.`punctDeLucruId`='0' AND `r`.`stockProdusId`='$stockProdusId'"; $result = mysql_query( $query ) or die(mysql_error()); if($result) { $row = mysql_fetch_array($result); } $reservedQuantity=$row["quantity"]; if($quantity>$reservedQuantity) { $quantity = $quantity-$reservedQuantity; $quantityToMinus = $reservedQuantity; $query="DELETE FROM `rezervareProdus` WHERE `comandaId`='$comandaId' AND `punctDeLucruId`='0' AND `stockProdusId`='$stockProdusId'"; $result=mysql_query($query) or die(mysql_error()); } else { $quantityToMinus = $quantity; $query="UPDATE `rezervareProdus` SET `quantity`=`quantity`-'$quantityToMinus' WHERE `comandaId`='$comandaId' AND `punctDeLucruId`='0' AND `stockProdusId`='$stockProdusId'"; $result=mysql_query($query) or die(mysql_error()); } } function stock_howManyOnBonConsumCommandIntern($comandaId,$comandaIntId,$prodid) { $query = "SELECT `bi`.* FROM `bonConsum` b, `bonConsum_items` bi WHERE `b`.`fromActAdvId`='$comandaId' AND `b`.`fromActComInt`='$comandaIntId' AND `b`.`active`='1' AND `b`.`id`=`bi`.`factid` AND `bi`.`modelid`='$prodid'"; $quantity=0; $result = mysql_query( $query ) or die(mysql_error()); if($result) { while ($row = mysql_fetch_array($result)) { $quantity += $row["quantity"]; } return $quantity; } else return 0; } function stock_rezervedForCommandIntern($comandaId,$produsid,$stockid) { $query = "SELECT `r`.* FROM `rezervareProdus` r, `stocks` s WHERE `r`.`comandaId`='$comandaId' AND `r`.`produsId`='$produsid' AND `r`.`stockid`=`s`.`id` AND `s`.`locid`='$stockid' AND `r`.`punctDeLucruId`='0'"; $result = mysql_query( $query ) or die(mysql_error()); $quantityReservedForComanda=0; if($result) { while ($row = mysql_fetch_array($result)) { $quantityReservedForComanda += $row["quantity"]; } return $quantityReservedForComanda; } else { return 0; } } function stock_rezervedForCommandInternExact($comandaId,$produsid,$stockid,$stockProdusId) { $query = "SELECT `r`.* FROM `rezervareProdus` r, `stocks` s WHERE `r`.`comandaId`='$comandaId' AND `r`.`produsId`='$produsid' AND `r`.`stockid`=`s`.`id` AND `s`.`locid`='$stockid' AND `r`.`punctDeLucruId`='0' AND `r`.`stockProdusId`='$stockProdusId'"; $result = mysql_query( $query ) or die(mysql_error()); $quantityReservedForComanda=0; if($result) { while ($row = mysql_fetch_array($result)) { $quantityReservedForComanda += $row["quantity"]; } return $quantityReservedForComanda; } else { return 0; } } function stock_rezervedForCommandInternById($comandaId){ $query="SELECT * FROM `rezervareProdus` WHERE `comandaId`='$comandaId'"; $result=mysql_query($query) or die($query." ".mysql_error()); $lista=array(); while ($row=mysql_fetch_array($result)){ $lista[$row['id']]=$row; } return $lista; } function stock_rezervedForCommandInternExactWithoutStock($comandaId,$produsid,$stockProdusId) { $query = "SELECT `r`.* FROM `rezervareProdus` r, `stocks` s WHERE `r`.`comandaId`='$comandaId' AND `r`.`produsId`='$produsid' AND `r`.`stockid`=`s`.`id` AND `r`.`punctDeLucruId`='0' AND `r`.`stockProdusId`='$stockProdusId'"; $result = mysql_query( $query ) or die(mysql_error()); $quantityReservedForComanda=0; if($result) { while ($row = mysql_fetch_array($result)) { $quantityReservedForComanda += $row["quantity"]; } return $quantityReservedForComanda; } else { return 0; } } function stock_rezervedForCommand($comandaId,$produsid,$stockid) { $query = "SELECT `r`.* FROM `rezervareProdus` r, `stocks` s WHERE `r`.`comandaId`='$comandaId' AND `r`.`produsId`='$produsid' AND `r`.`stockid`=`s`.`id` AND `s`.`locid`='$stockid' AND `r`.`punctDeLucruId`!='0'"; $result = mysql_query( $query ) or die(mysql_error()); $quantityReservedForComanda=0; if($result) { while ($row = mysql_fetch_array($result)) { $quantityReservedForComanda += $row["quantity"]; } return $quantityReservedForComanda; } else { return 0; } } function stock_rezervedForCommandsList($modelid) { $quantityRezervare=0; $quantity=0; $queryComanda="SELECT `ci`.* FROM `comandaForClientAdvItems` ci, `comandaForClientAdv` c WHERE `ci`.`prodid`='$modelid' and `ci`.`selltype`='cumparare' and `ci`.`comandaid`=`c`.`id` and `c`.`active`='1' order by `ondate` asc"; $resultComanda = mysql_query($queryComanda); while( $rowComanda = mysql_fetch_array( $resultComanda ) ) { $comandaId = $rowComanda["comandaid"]; $prodid = $rowComanda["prodid"]; $quantity += $rowComanda["quantity"]; if($rowComanda["quantity"]!=0){ $comandaList[$rowComanda["comandaid"]]['q']+=$rowComanda["quantity"]; $comandaList[$rowComanda["comandaid"]]['t']='Client'; } $queryRezervare = "SELECT * FROM `rezervareProdus` WHERE `comandaId`='$comandaId' and `produsId`='$prodid'"; $resultRezervare = mysql_query($queryRezervare); while( $rowRezervare = mysql_fetch_array( $resultRezervare ) ) { $quantityRezervare += $rowRezervare["quantity"]; if($rowRezervare["quantity"]!=0) { $comandaList[$rowComanda["comandaid"]]['q']-=$rowRezervare["quantity"]; } } } $queryComandaIntern="SELECT `ci`.*, `c`.`fromActAdvId` FROM `comandaInternaItems` ci, `comandaInterna` c WHERE `ci`.`prodid`='$modelid' and `ci`.`comandaid`=`c`.`id` and `c`.`active`='1' order by `c`.`ondate` asc"; $resultComandaIntern = mysql_query($queryComandaIntern); while( $rowComandaIntern = mysql_fetch_array( $resultComandaIntern ) ) { $comandaId = $rowComandaIntern["fromActAdvId"]; $prodid = $rowComandaIntern["prodid"]; $quantity += $rowComandaIntern["quantity"]; if($rowComandaIntern["quantity"]!=0){ $comandaList[$rowComandaIntern["fromActAdvId"]]['q']+=$rowComandaIntern["quantity"]; $comandaList[$rowComandaIntern["fromActAdvId"]]['t']='Interna'; } $queryRezervareIntern = "SELECT * FROM `rezervareProdus` WHERE `comandaId`='$comandaId' and `produsId`='$prodid' and `punctDeLucruId`='0'"; $resultRezervareIntern = mysql_query($queryRezervareIntern); while( $rowRezervareIntern = mysql_fetch_array( $resultRezervareIntern ) ) { $quantityRezervare += $rowRezervareIntern["quantity"]; if($rowRezervareIntern["quantity"]!=0) { $comandaList[$rowComandaIntern["fromActAdvId"]]['q']-=$rowRezervareIntern["quantity"]; } } } return $comandaList; } function model_getModelsToCommand($query) { $result = mysql_query( $query ) or die(mysql_error()); $models=""; if( mysql_num_rows($result) <= 0 )return NULL; while( $row = mysql_fetch_array( $result ) ) { //megnezem hogy mely termekekbol kell rendelni, mert nincs a raktarban $modelid = $row["id"]; $quantityRezervare=0; $quantity=0; $queryComanda="SELECT `ci`.* FROM `comandaForClientAdvItems` ci, `comandaForClientAdv` c WHERE `ci`.`prodid`='$modelid' and `ci`.`selltype`='cumparare' and `ci`.`comandaid`=`c`.`id` and `c`.`active`='1' order by `c`.`ondate` asc"; $resultComanda = mysql_query($queryComanda); while( $rowComanda = mysql_fetch_array( $resultComanda ) ) { $comandaId = $rowComanda["comandaid"]; $prodid = $rowComanda["prodid"]; $quantity += $rowComanda["quantity"]; $queryRezervare = "SELECT * FROM `rezervareProdus` WHERE `comandaId`='$comandaId' and `produsId`='$prodid'"; $resultRezervare = mysql_query($queryRezervare); while( $rowRezervare = mysql_fetch_array( $resultRezervare ) ) { $quantityRezervare += $rowRezervare["quantity"]; } } $queryComandaIntern="SELECT `ci`.*, `c`.`fromActAdvId` FROM `comandaInternaItems` ci, `comandaInterna` c WHERE `ci`.`prodid`='$modelid' and `ci`.`comandaid`=`c`.`id` and `c`.`active`='1' and `partnerTermen`='0000-00-00' order by `c`.`ondate` asc"; $resultComandaIntern = mysql_query($queryComandaIntern); while( $rowComandaIntern = mysql_fetch_array( $resultComandaIntern ) ) { $comandaId = $rowComandaIntern["fromActAdvId"]; $prodid = $rowComandaIntern["prodid"]; $quantity += $rowComandaIntern["quantity"]; $queryRezervareIntern = "SELECT * FROM `rezervareProdus` WHERE `comandaId`='$comandaId' and `produsId`='$prodid' and `punctDeLucruId`='0'"; $resultRezervareIntern = mysql_query($queryRezervareIntern); while( $rowRezervareIntern = mysql_fetch_array( $resultRezervareIntern ) ) { $quantityRezervare += $rowRezervareIntern["quantity"]; } } if($quantityRezervare<$quantity) { //megnezem hogy veletlenul annyi nincs a raktarban? mert ha igen, akkor meg sincs szukseg rendelni $quantityStock = stock_getProdQuantityFromItemGeneral($modelid); if($quantityStock<$quantity) $models[ $row["id"] ] = $row; } } return $models; } function models_toComand($modelid) { $quantityRezervare=0; $quantity=0; $queryComanda="SELECT `ci`.*, `c`.`directDelivery` FROM `comandaForClientAdvItems` ci, `comandaForClientAdv` c WHERE `ci`.`prodid`='$modelid' and `ci`.`selltype`='cumparare' and `ci`.`comandaid`=`c`.`id` and `c`.`active`='1' order by `ondate` asc"; $resultComanda = mysql_query($queryComanda); while( $rowComanda = mysql_fetch_array( $resultComanda ) ) { $comandaId = $rowComanda["comandaid"]; $prodid = $rowComanda["prodid"]; if ($rowComanda['directDelivery']=='1') $quantity += $rowComanda["quantity"]; $queryRezervare = "SELECT * FROM `rezervareProdus` WHERE `comandaId`='$comandaId' and `produsId`='$prodid'"; $resultRezervare = mysql_query($queryRezervare); while( $rowRezervare = mysql_fetch_array( $resultRezervare ) ) { $quantityRezervare += $rowRezervare["quantity"]; } } $queryComandaIntern="SELECT `ci`.*, `c`.`fromActAdvId` FROM `comandaInternaItems` ci, `comandaInterna` c WHERE `ci`.`prodid`='$modelid' and `ci`.`comandaid`=`c`.`id` and `c`.`active`='1' order by `c`.`ondate` asc"; $resultComandaIntern = mysql_query($queryComandaIntern); while( $rowComandaIntern = mysql_fetch_array( $resultComandaIntern ) ) { $qcomanda="SELECT `directDelivery` FROM `comandaForClientAdv` WHERE `id`='".$rowComandaIntern['fromActAdvId']."'"; $status=mysql_fetch_array(mysql_query($qcomanda)); $comandaId = $rowComandaIntern["fromActAdvId"]; $prodid = $rowComandaIntern["prodid"]; if ($status['directDelivery']=='1') $quantity += $rowComandaIntern["quantity"]; $queryRezervareIntern = "SELECT * FROM `rezervareProdus` WHERE `comandaId`='$comandaId' and `produsId`='$prodid' and `punctDeLucruId`='0'"; $resultRezervareIntern = mysql_query($queryRezervareIntern); while( $rowRezervareIntern = mysql_fetch_array( $resultRezervareIntern ) ) { $quantityRezervare += $rowRezervareIntern["quantity"]; } } if($quantityRezervare<$quantity) return ($quantity-$quantityRezervare); else return 0; } function commandIntern_setActiveNess( $factid , $state ) { $update = "UPDATE `comandaInterna` SET `active`='$state' WHERE `id`='$factid' LIMIT 1;"; mysql_query( $update ) or die(mysql_error()); } function command_getCommandIdFromNr($secondserial) { $query = "SELECT id FROM `comandaForClientAdv` WHERE `secondserial`='$secondserial' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); $row = mysql_fetch_array($result); if($secondserial!=0) return $row["id"]; else return NULL; } function command_getCommandNrFromId($id) { $query = "SELECT `secondserial` FROM `comandaForClientAdv` WHERE `id`='$id' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if($result) { $row = mysql_fetch_array($result); return $row["secondserial"]; } else return 0; } function command_pagesInDatabase($id) { $query = "SELECT `suplimentPages` FROM `comandaForClientAdv` WHERE `id`='$id' LIMIT 1"; $result = mysql_query( $query ) or die(mysql_error()); if($result) { $row = mysql_fetch_array($result); return $row["suplimentPages"]; } else return 0; } function stock_verifyAndReserveAnotherProducts( $userid , $entryid , $toDefStock , $quantityIn,$date) { $queryComanda="SELECT `ci`.*, `c`.`clientPunctLucru` FROM `comandaForClientAdvItems` ci, `comandaForClientAdv` c WHERE `ci`.`prodid`='$entryid' and `ci`.`selltype`='cumparare' and `ci`.`comandaid`=`c`.`id` and `c`.`active`='1' order by `ondate` asc"; $quantityRezervare=0; $quantity=0; $toReserveInPlus=0; $resultComanda = mysql_query($queryComanda); while( $rowComanda = mysql_fetch_array( $resultComanda ) ) { $comandaId = $rowComanda["comandaid"]; $prodid = $rowComanda["prodid"]; $quantity += $rowComanda["quantity"]; $queryRezervare = "SELECT * FROM `rezervareProdus` WHERE `comandaId`='$comandaId' and `produsId`='$prodid' and `punctDeLucruId`!='0'"; $resultRezervare = mysql_query($queryRezervare); while( $rowRezervare = mysql_fetch_array( $resultRezervare ) ) { $quantityRezervare += $rowRezervare["quantity"]; } if($quantityRezervare<$quantity && $quantityRezervare!=0) { $toReserveInPlus = $quantity-$quantityRezervare; if($toReserveInPlus>=$quantityIn) { $quantityToReserve = $quantityIn; $quantityIn = 0; } else { $quantityToReserve=$toReserveInPlus; $quantityIn = $quantityIn - $toReserveInPlus; } if($quantityToReserve!=0){ $hr=hr_getUserAsoc($userid); stock_insertRezervareProdus( $comandaId, $prodid, "cumparare", $quantityToReserve, $rowComanda["stockid"], $rowComanda["clientPunctLucru"],$hr['id'],$date); } } } $quantityRezervare=0; $quantity=0; $toReserveInPlus=0; $queryComandaIntern="SELECT `ci`.*, `c`.`fromActAdvId` FROM `comandaInternaItems` ci, `comandaInterna` c WHERE `ci`.`prodid`='$entryid' and `ci`.`comandaid`=`c`.`id` and `c`.`active`='1' order by `c`.`ondate` asc"; $resultComandaIntern = mysql_query($queryComandaIntern); while( $rowComandaIntern = mysql_fetch_array( $resultComandaIntern ) ) { $comandaId = $rowComandaIntern["fromActAdvId"]; $prodid = $rowComandaIntern["prodid"]; $quantity += $rowComandaIntern["quantity"]; $queryRezervareIntern = "SELECT * FROM `rezervareProdus` WHERE `comandaId`='$comandaId' and `produsId`='$prodid' and `punctDeLucruId`='0'"; $resultRezervareIntern = mysql_query($queryRezervareIntern); while( $rowRezervareIntern = mysql_fetch_array( $resultRezervareIntern ) ) { $quantityRezervare += $rowRezervareIntern["quantity"]; } if($quantityRezervare<$quantity && $quantityRezervare!=0) { $toReserveInPlus = $quantity-$quantityRezervare; if($toReserveInPlus>=$quantityIn) { $quantityToReserve = $quantityIn; $quantityIn = 0; } else { $quantityToReserve=$toReserveInPlus; $quantityIn = $quantityIn - $toReserveInPlus; } if($quantityToReserve!=0){ $hr=hr_getUserAsoc($userid); stock_insertRezervareProdus( $comandaId, $prodid, "cumparare", $quantityToReserve, $rowComanda["stockid"], '0',$hr['id'],$date); } } } } function comandaInterna_modExecutare( $id ) { $updateQ = "UPDATE `comandaInterna` SET `partnerTermen` = NOW() WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); $updateQ = "UPDATE `comandaInterna` SET `stateStatus` = '2' WHERE `id` ='$id' LIMIT 1 ;"; $result=mysql_query( $updateQ ) or die(mysql_error()); } function getSimilars() { $query = "SELECT * FROM `container` WHERE `modelid`!=6 AND `modelid`!=7 ORDER BY `id`"; $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array($result)) $all[$row["id"]] = $row; return $all; } function MoveAllOpFromProforma($from,$to) { $query="UPDATE `op` SET `factid`='$to' WHERE `factid`='$from'"; $result=mysql_query($query) or die(mysql_error()); } function getCommandRowIdForServiceFromFactura($commandId,$serviceId) { $query="SELECT `id` FROM `comandaForClientAdvItems` WHERE `comandaid`='$commandId' AND `prodid`='$serviceId'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row["id"]; } function stock_maximizeProductPrice($entryid) { $query="SELECT `price` FROM `stock_items` WHERE `itemid`='$entryid' ORDER BY `price` DESC"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row["price"]; } //utolso sorozatszam meghatarozasa (oferta de pret vagy comanda) function getMaxSerial($type){ $query="SELECT max(`secondserial`) FROM `comandaForClientAdv` WHERE `firstserial`=$type"; $result=mysql_query( $query ) or die(mysql_error()); $row= mysql_fetch_array($result); return $row; } function getLangKeywords($searchval,$pager,$howmany) { $from=($pager-1)*$howmany; $query="SELECT * FROM `lang_keywords` WHERE `title` LIKE '%$searchval%' ORDER BY `id` LIMIT $from, $howmany"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function langKeywordSearchCount($searchval) { $query="SELECT * FROM `lang_keywords` WHERE `title` LIKE '%$searchval%'"; $result=mysql_query($query) or die(mysql_error()); return mysql_num_rows($result); } function deleteLangkeyword($keyid) { $query="DELETE FROM `lang_keywords` WHERE `id`='$keyid'"; mysql_query($query) or die(mysql_error()); $query="DELETE FROM `lang_keywords_values` WHERE `kvid`='$keyid'"; mysql_query($query) or die(mysql_error()); } function getLangKeywordData($keyid) { $query="SELECT * FROM `lang_keywords` WHERE `id`='$keyid'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { $row=mysql_fetch_array($result); } return $row; } function editLangKeyword($keyid,$array) { $query="UPDATE `lang_keywords` SET `title`='".$array["title"]."' WHERE `id`='$keyid'"; $result=mysql_query($query) or die(mysql_error()); } function addNewLangKeyword($array) { $query="INSERT INTO `lang_keywords`(`title`) VALUES('".$array["title"]."')"; $result=mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function getTraduceriKeywords($searchval,$lang,$pager,$howmany) { $from=($pager-1)*$howmany; $query="SELECT * FROM `lang_keywords_values` WHERE `title` LIKE '%$searchval%' "; if($lang!="0") $query.=" AND `lang`='$lang' "; $query.=" LIMIT $from, $howmany"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function langTraduceriSearchCount($searchval,$lang) { $query="SELECT * FROM `lang_keywords_values` WHERE `title` LIKE '%$searchval%' "; if($lang!="0") $query.=" AND `lang`='$lang' "; $result=mysql_query($query) or die(mysql_error()); return mysql_num_rows($result); } function getLangTraducereData($tkeyid) { $query="SELECT * FROM `lang_keywords_values` WHERE `id`='$tkeyid'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { $row=mysql_fetch_array($result); } return $row; } function addNewTraducereKeyword($array) { $query="INSERT INTO `lang_keywords_values`(`kvid`,`lang`,`title`) VALUES('".$array["kvid"]."','".$array["lang"]."','".$array["title"]."')"; mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function editLangTraducere($tkeyid,$array) { $query="UPDATE `lang_keywords_values` SET `kvid`='".$array["kvid"]."',`lang`='".$array["lang"]."',`title`='".$array["title"]."' WHERE `id`='$tkeyid'"; mysql_query($query) or die(mysql_error()); } function getAllLangKeywords() { $query="SELECT * FROM `lang_keywords`"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function getTraducere($keyw,$lang) { $query="SELECT `id` FROM `lang_keywords` WHERE LOWER(`title`)='".strtolower($keyw)."'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { $row=mysql_fetch_array($result); $kk=$row["id"]; $query2="SELECT `title` FROM `lang_keywords_values` WHERE `kvid`='$kk' AND `lang`='$lang' ORDER BY `id` DESC LIMIT 1"; $result2=mysql_query($query2) or die(mysql_error()); if($result2&&mysql_num_rows($result2)>0) { $row2=mysql_fetch_array($result2); return $row2["title"]; } else return $keyw; } else return $keyw; } function getImageForLang($folder,$image,$lang) { if(is_file($folder.$lang."/".$image)) return $folder.$lang."/".$image; else return $folder.$image; } function MoveAllBillFromProforma($from,$to) { $query="UPDATE `bills` SET `factid`='$to' WHERE `factid`='$from'"; $result=mysql_query($query) or die(mysql_error()); } function get_prea_lucraci($id) { $query = "select * from `creareLucrari_pre_AU` where `workId` = '$id' LIMIT 1"; $result = mysql_query($query) or die(mysql_error()); return mysql_num_rows($result); } function delete_from_Workid($id) { $query = "DELETE from `creareLucrari_pre_AU` where `workId` = '$id'"; $result = mysql_query($query) or die(mysql_error()); $query = "DELETE from `creareLucrari_Proceduri` where `workid` = '$id'"; $result = mysql_query($query) or die(mysql_error()); } function delete_from_Workers($id) { $query = "DELETE from `creareLucrari_Workers` where `work_id` = '$id'"; $result = mysql_query($query) or die(mysql_error()); } function getWorkersWorkAll($workid) { $j = 0; $l = 0; $query3 = "select `id_Pacient`, `sectia`, `sectia_nr`, `nr_fo`, `nume`, `data_extern`, `dg_int`, `tip_extern`, `sex`, `varsta`, `ziua_n`, `greutate_n`, `zile_sp`, `dg_pr1`, `j1`, `dg_pr2`, `j2`, `dg_s1`, `j3`, `dg_s2`, `j4`, `dg_s3`, `j5`, `dg_s4`, `j6`, `dg_s5`, `j7`, `dg_s6`, `j8`, `dg_s7`, `j9`, `dg_s8`, `j10`, `dg_s9`, `j11`, `dg_s10`, `j12`, `dg_s11`, `j13`, `dg_s12`, `j14`, `dg_s13`, `j15`, `dg_s14`, `j16`, `dg_s15`, `j17`, `dg_s16`, `j18`, `dg_s17`, `j19`, `dg_s18`, `j20`, `prpr`, `pr_s1`, `pr_s2`, `pr_s3`, `pr_s4`, `pr_s5`, `pr_s6`, `pr_s7`, `pr_s8`, `pr_s9`, `pr_s10`, `pr_s11`, `pr_s12`, `pr_s13`, `pr_s14`, `mdc`, `mperc`, `drg`, `vr_initial`, `tip_caz`,`e_sign` from creareLucrari_pre_AU where workId = '$workid' ORDER BY id asc"; $result3 = mysql_query( $query3 ) or die (" getwork2 ".mysql_error()); while ($r2 = mysql_fetch_array($result3)) { for ($i=0; $i 0) { return true; } else return false; } function checkWorkexist($workid, $hrid) { $query = "select * from creareLucrari_ModifiedExcel where workid = '$workid' and userid = '$hrid' limit 1"; $result = mysql_query($query) or die("checkWorkRezultNowOrLater ".mysql_error()); return mysql_fetch_array($result); } function Select_Activitati_to_Work($workid, $hr_id, $spec_id) { $query = "SELECT * FROM `creareLucrari_Workers` WHERE `work_id`= '$workid' AND `activ_id`='$spec_id' LIMIT 1"; $result = mysql_query( $query ) or die (" akt ".mysql_error()); if ($result) $row2 = mysql_fetch_array($result); return $row2["id"]; } function Update_Activitati_to_Work($workid, $hr_id, $spec_id,$id) { $query = "UPDATE `creareLucrari_Workers` SET `activ_id`='$spec_id',`hr_id`='$hr_id' WHERE `work_id`= '$workid' AND `id`='$id' "; $result = mysql_query( $query ) or die (" akt ".mysql_error()); } function get_prea_sectia_exist($id,$sectiaid) { $query = "select * from `creareLucrari_pre_AU` where `workId` = '$id' AND `sectia`='$sectiaid' LIMIT 1 "; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function delete_from_Workid_upload($id,$userid) { $query = "DELETE from `creareLucrari_ModifiedExcel` where `workId` = '$id' AND `userid`='$userid'"; $result = mysql_query($query) or die(mysql_error()); } function uinsert_upload_file_name($id,$workid,$exelmane) { $query = "UPDATE creareLucrari_Workers SET work_exel_name='$exelmane' where hr_id = '$id' and work_id = '$workid'"; $result = mysql_query($query) or die(mysql_error()); } function get_User_from_Work_exel_name($workid,$hrid) { $query = "select * from creareLucrari_Workers where work_id = '$workid' AND hr_id='$hrid' LIMIT 1"; $result = mysql_query( $query ) or die (mysql_error()); $row = mysql_fetch_array($result); return $row; } function generateTheFinalExcel4($workid,$userid) { $query = "select * from creareLucrari_ModifiedExcel where `workid` = '$workid' and `userid`='$userid'"; $result = mysql_query( $query ) or die (" final ".mysql_error()); $j = 0; while($row = mysql_fetch_array($result)) { $q = "select `id_Pacient`, `sectia`, `sectia_nr`, `nr_fo`, `nume`, `data_extern`, `dg_int`, `tip_extern`, `sex`, `varsta`, `ziua_n`, `greutate_n`, `zile_sp`, `dg_pr1`, `j1`, `dg_pr2`, `j2`, `dg_s1`, `j3`, `dg_s2`, `j4`, `dg_s3`, `j5`, `dg_s4`, `j6`, `dg_s5`, `j7`, `dg_s6`, `j8`, `dg_s7`, `j9`, `dg_s8`, `j10`, `dg_s9`, `j11`, `dg_s10`, `j12`, `dg_s11`, `j13`, `dg_s12`, `j14`, `dg_s13`, `j15`, `dg_s14`, `j16`, `dg_s15`, `j17`, `dg_s16`, `j18`, `dg_s17`, `j19`, `dg_s18`, `j20`, `prpr`, `pr_s1`, `pr_s2`, `pr_s3`, `pr_s4`, `pr_s5`, `pr_s6`, `pr_s7`, `pr_s8`, `pr_s9`, `pr_s10`, `pr_s11`, `pr_s12`, `pr_s13`, `pr_s14`, `mdc`, `mperc`, `drg`, `vr_initial`, `tip_caz` from creareLucrari_spec_back where id_Pacient = '".$row["id_pacient"]."'"; $res = mysql_query( $q ) or die (" final3 ".mysql_error()); $r = mysql_fetch_array($res); for ($i=0 , $l=0; $l $r["vr_initial"]) { for ($k=6; $k $v) { $array[$key]=str_replace("'","\'",$v); } $query = "INSERT INTO `creareLucrari_ModifiedExcel` (`id` ,`workid` ,`userid` , `hr_id` , `ondate` , `id_pacient` , `dg_pr1` , `j1` , `dg_pr2` , `j2` , `dg_s1` , `j3` , `dg_s2` , `j4` , `dg_s3` , `j5` , `dg_s4` , `j6` , `dg_s5` , `j7` , `dg_s6` , `j8` , `dg_s7` , `j9` , `dg_s8` , `j10` , `dg_s9` , `j11` , `dg_s10` , `j12` , `dg_s11` , `j13` , `dg_s12` , `j14` , `dg_s13` , `j15` , `dg_s14` , `j16` , `dg_s15` , `j17` , `dg_s16` , `j18` , `dg_s17` , `j19` , `dg_s18` , `j20` , `prpr` , `pr_s1` , `pr_s2` , `pr_s3` , `pr_s4` , `pr_s5` , `pr_s6` , `pr_s7` , `pr_s8` , `pr_s9` , `pr_s10` , `pr_s11` , `pr_s12` , `pr_s13` , `pr_s14` , `mdc` , `mperc` ,`drg_nou` , `vrxk_nou` , `normal` , `observatii` , `dif_vr_init` , `megj`) VALUES ( NULL , '$work_id', '$user_id', '$hr_id', NOW(), '$array[1]' ,'$array[74]', '$array[75]', '$array[76]', '$array[77]', '$array[78]', '$array[79]', '$array[80]', '$array[81]', '$array[82]', '$array[83]', '$array[84]', '$array[85]', '$array[86]', '$array[87]', '$array[88]', '$array[89]', '$array[90]', '$array[91]', '$array[92]', '$array[93]', '$array[94]', '$array[95]', '$array[96]', '$array[97]', '$array[98]', '$array[99]', '$array[100]', '$array[101]', '$array[102]', '$array[103]', '$array[104]', '$array[105]', '$array[106]', '$array[107]', '$array[108]', '$array[109]', '$array[110]', '$array[111]', '$array[112]', '$array[113]', '$array[114]', '$array[115]', '$array[116]', '$array[117]', '$array[118]', '$array[119]', '$array[120]', '$array[121]', '$array[122]', '$array[123]', '$array[124]', '$array[125]', '$array[126]', '$array[127]', '$array[128]', '$array[129]', '$array[130]', '$array[131]', '$array[132]', '$array[133]', '$array[134]', '$array[135]', '$array[136]');"; $result = mysql_query( $query ) or die ("modified excel ".mysql_error()); return mysql_insert_id(); } function getHrForUser($userid) { $query = "select * from hr where userid = '$userid'"; $result = mysql_query( $query ) or die (" get_hr ".mysql_error()); $row = mysql_fetch_array($result); return $row; } function checkTheWorkFinish($work_id) { $query = "select * from creareLucrari_Workers where work_id = '$work_id'"; $result = mysql_query( $query ) or die (" checkTheWork ".mysql_error()); $index = 0; while($row = mysql_fetch_array($result)) { $help = 0; for ($i=0; $i= count($workers_id)) { return true; } else return false; } function generateTheFinalExcel2($workid) { $query = "select * from creareLucrari_ModifiedExcel where workid = '$workid' group by id_pacient"; $result = mysql_query( $query ) or die (" final ".mysql_error()); $j = 0; while($row = mysql_fetch_array($result)) { $checker = 0; $q = "select `id_Pacient`, `sectia`, `sectia_nr`, `nr_fo`, `nume`, `data_extern`, `dg_int`, `tip_extern`, `sex`, `varsta`, `ziua_n`, `greutate_n`, `zile_sp`, `dg_pr1`, `j1`, `dg_pr2`, `j2`, `dg_s1`, `j3`, `dg_s2`, `j4`, `dg_s3`, `j5`, `dg_s4`, `j6`, `dg_s5`, `j7`, `dg_s6`, `j8`, `dg_s7`, `j9`, `dg_s8`, `j10`, `dg_s9`, `j11`, `dg_s10`, `j12`, `dg_s11`, `j13`, `dg_s12`, `j14`, `dg_s13`, `j15`, `dg_s14`, `j16`, `dg_s15`, `j17`, `dg_s16`, `j18`, `dg_s17`, `j19`, `dg_s18`, `j20`, `prpr`, `pr_s1`, `pr_s2`, `pr_s3`, `pr_s4`, `pr_s5`, `pr_s6`, `pr_s7`, `pr_s8`, `pr_s9`, `pr_s10`, `pr_s11`, `pr_s12`, `pr_s13`, `pr_s14`, `mdc`, `mperc`, `drg`, `vr_initial`, `tip_caz` from creareLucrari_spec_back where id_Pacient = '".$row["id_pacient"]."' and workId = '$workid'"; $res = mysql_query( $q ) or die (" final3 ".mysql_error()); if(mysql_num_rows($res)<=0) { $checker = 1; $q = "select `id_Pacient`, `sectia`, `sectia_nr`, `nr_fo`, `nume`, `data_extern`, `dg_int`, `tip_extern`, `sex`, `varsta`, `ziua_n`, `greutate_n`, `zile_sp`, `dg_pr1`, `j1`, `dg_pr2`, `j2`, `dg_s1`, `j3`, `dg_s2`, `j4`, `dg_s3`, `j5`, `dg_s4`, `j6`, `dg_s5`, `j7`, `dg_s6`, `j8`, `dg_s7`, `j9`, `dg_s8`, `j10`, `dg_s9`, `j11`, `dg_s10`, `j12`, `dg_s11`, `j13`, `dg_s12`, `j14`, `dg_s13`, `j15`, `dg_s14`, `j16`, `dg_s15`, `j17`, `dg_s16`, `j18`, `dg_s17`, `j19`, `dg_s18`, `j20`, `prpr`, `pr_s1`, `pr_s2`, `pr_s3`, `pr_s4`, `pr_s5`, `pr_s6`, `pr_s7`, `pr_s8`, `pr_s9`, `pr_s10`, `pr_s11`, `pr_s12`, `pr_s13`, `pr_s14`, `mdc`, `mperc`, `drg`, `vr_initial`, `tip_caz` from creareLucrari_pre_AU where id_Pacient = '".$row["id_pacient"]."' and workId = '$workid'"; $res = mysql_query( $q ) or die (" final2 ".mysql_error()); } if (mysql_num_rows($res)>0) { $r = mysql_fetch_array($res); for ($i=0 , $l=0; $l $r["vr_initial"]) { for ($k=6; $k0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function departamente_search($searchval , $pager,$howmany) { if($pager=="") $pager=1; if($howmany=="") $howmany=5; $query="SELECT * FROM `departamente` WHERE `name` LIKE '%$searchval%' LIMIT ".(($pager-1)*$howmany).", $howmany"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function departamente_SearchCount( $searchval ) { $query="SELECT * FROM `departamente` WHERE `name` LIKE '%$searchval%'"; $result=mysql_query($query) or die(mysql_error()); return mysql_num_rows($result); } function getDepartamentData($keyid) { $query="SELECT * FROM `departamente` WHERE `id`='$keyid'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row; } function addNewDepartament($array) { $name=str_replace("'","\\'",$array["name"]); $query="INSERT INTO `departamente`(`name`) VALUES('$name')"; $result=mysql_query($query) or die(mysql_error()); return mysql_insert_id(); } function editDepartament($keyid,$array) { $name=str_replace("'","\\'",$array["name"]); $query="UPDATE `departamente` SET `name`='$name' WHERE `id`='$keyid'"; $result=mysql_query($query) or die(mysql_error()); } function getAngajatiForDepartament($keyid,$searchval,$pager,$howmany) { if($pager=="") $pager=1; if($howmany=="") $howmany=10; $query="SELECT * FROM `hr` WHERE (`cnp` LIKE '%$searchval%' OR `forname` LIKE '%$searchval%' OR `lastname` LIKE '%$searchval%' OR `email` LIKE '%$searchval%' ) AND `main_departament` !='$keyid' AND `id` NOT IN (SELECT `hrid` FROM `departamente_hr` WHERE `dep_id`='$keyid') ORDER BY `forname` LIMIT ".(($pager-1)*$howmany).", $howmany"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>=0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function addHrToDepartament($keyid,$userid) { $query="INSERT INTO `departamente_hr`(`dep_id`,`hrid`) VALUES('$keyid','$userid')"; $result=mysql_query($query) or die(mysql_error()); } function RemoveHrFromDepartament($keyid,$userid) { $query="DELETE FROM `departamente_hr` WHERE `dep_id`='$keyid' AND `hrid`='$userid'"; $result=mysql_query($query) or die(mysql_error()); } function getAngajatiInDepartament($keyid) { $query="SELECT * FROM `hr` WHERE `main_departament`='$keyid' OR `id` IN (SELECT `hrid` FROM `departamente_hr` WHERE `dep_id`='$keyid')"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>=0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function CountAngajatiForDepartament($keyid,$searchval) { $query="SELECT * FROM `hr` WHERE (`cnp` LIKE '%$searchval%' OR `forname` LIKE '%$searchval%' OR `lastname` LIKE '%$searchval%' OR `email` LIKE '%$searchval%' ) AND `main_departament` !='$keyid' AND `id` NOT IN (SELECT `hrid` FROM `departamente_hr` WHERE `dep_id`='$keyid') ORDER BY `forname` "; $result=mysql_query($query) or die(mysql_error()); return mysql_num_rows($result); } function getUsersDepartaments($userid) { $query="SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { } } function getNonPaidFacturas($commandId,$fromdate,$clientid) { if($commandId!="") $query="SELECT * FROM `facturi` WHERE `clientid`='$clientid' AND `fromActAdvId`='$commandId' AND `active`='1' AND `termenDePlata`< NOW() AND `ondate`>'$fromdate'"; else $query="SELECT * FROM `facturi` WHERE `clientid`='$clientid' AND `active`='1' AND `termenDePlata`< NOW() AND `ondate`>'$fromdate'"; $result=mysql_query($query) or die($query.mysql_error()); $facturiid="("; if($result&&mysql_num_rows($result)>0) { $index=0; while($row=mysql_fetch_array($result)) { if(!factura_getStornedFactura( $row["id"] )) { if($index!=0) $facturiid.=","; $facturiid.=$row["id"]; $facturi[$row["id"]]=$row; $index++; } } } $facturiid.=")"; if($facturiid!="()") { $queryfi="SELECT * FROM `facturi_items` WHERE `factid` IN $facturiid"; $resultfi=mysql_query($queryfi) or die($queryfi.mysql_error()); if($resultfi&&mysql_num_rows($resultfi)>0) { $cnt=0; while($rowfi=mysql_fetch_array($resultfi)) { if($facturi[$rowfi["factid"]]["value"]=="") $facturi[$rowfi["factid"]]["value"]=0; if(strpos($rowfi["rowName"],"Penalizare")!==FALSE) { $facturi[$rowfi["factid"]]["value"]=$facturi[$rowfi["factid"]]["value"]-$rowfi["price"]; } if($rowfi["type"]=="1" ) { $serviciu=service_getService($rowfi["modelid"]); $servicecat=stock_getServiceModel($serviciu["modelid"]); if(strpos($servicecat["name"],"Taxe")!==FALSE) { $facturi[$rowfi["factid"]]["value"]=$facturi[$rowfi["factid"]]["value"]-$rowfi["price"]; } } } } $queryc="SELECT * FROM `bills` WHERE `factid` IN $facturiid"; $resultc=mysql_query($queryc) or die($queryc.mysql_error()); if($resultc&&mysql_num_rows($resultc)>0) { while($rowc=mysql_fetch_array($resultc)) { if($chitante[$rowc["factid"]]["total"]=="") $chitante[$rowc["factid"]]["total"]=0; if($rowop["cursValue"]==""||$rowop["cursValue"]=="0") $rowop["cursValue"]="1"; $chitante[$rowc["factid"]]["total"]+=$rowc["value"]*$rowc["cursValue"]; $chitante[$rowc["factid"]]["ondate"]=substr($rowc["ondate"],0,strpos($rowc["ondate"]," ")); } } $queryop="SELECT * FROM `op` WHERE `factid` IN $facturiid"; $resultop=mysql_query($queryop) or die(mysql_error()); if($resultop&&mysql_num_rows($resultop)>0) { while($rowop=mysql_fetch_array($resultop)) { if($op[$rowop["factid"]]["total"]=="") $op[$rowop["factid"]]["total"]=0; if($rowop["cursValue"]==""||$rowop["cursValue"]=="0") $rowop["cursValue"]="1"; $op[$rowop["factid"]]["total"]+=$rowop["value"]*$rowop["cursValue"]; $op[$rowop["factid"]]["ondate"]=substr($rowop["ondate"],0,strpos($rowop["ondate"]," ")); } } } if($facturi) { foreach($facturi as $fk=>$fv) { if($fv["value"]*$fv["cursValue"]>($op[$fk]["total"]+$chitante[$fk]["total"])) { $all[$fk]=$fv; $all[$fk]["restanta"]=$fv["value"]*$fv["cursValue"]-($op[$fk]["total"]+$chitante[$fk]["total"]); if($op[$fk]) $betwop=intval((strtotime($op[$fk]["ondate"]) - strtotime($fv["termenDePlata"])) / (60 * 60 * 24)); if($chitante[$fk]) $betwch=intval((strtotime($chitante[$fk]["ondate"]) - strtotime($fv["termenDePlata"])) / (60 * 60 * 24)); if($betwch=="") $betwch=0; if($betwop=="") $betwop=0; $betw=0; if($betwop<=$_SESSION["settings"]["PerioadaGratie"]) $betwop=0; if($op[$fk]==null&&$chitante[$fk]==null) $betw=intval((strtotime(date("Y-m-d")) - strtotime($fv["termenDePlata"])) / (60 * 60 * 24)); else if($betwch!=0) $betw=$betwch; else if($betwop!=0) $betw=$betwop; $all[$fk]["zile"]=$betw; $all[$fk]["total"]=$fv["value"]*$fv["cursValue"]; } } } return $all; } function HasclientUnPaidFacturaBefore($clientid,$id) { $query="SELECT * FROM `facturi` WHERE `clientid`='$clientid' AND `active`='1' AND `id`<'$id'"; $result=mysql_query($query) or die(mysql_error().$query); $facturiid="("; if($result&&mysql_num_rows($result)>0) { $indexfact=0; while($row=mysql_fetch_array($result)) { if(!factura_getStornedFactura( $row["id"] )) { if($indexfact!=0&&$facturiid!="(") { $facturiid.=","; } $facturiid.=$row["id"]; $facturi[$row["id"]]=$row; $indexfact++; } } } $facturiid.=")"; if($facturiid!="()") { $queryc="SELECT * FROM `bills` WHERE `factid` IN $facturiid"; $resultc=mysql_query($queryc) or die(mysql_error().$queryc); if($resultc&&mysql_num_rows($resultc)>0) { while($rowc=mysql_fetch_array($resultc)) { if($chitante[$rowc["factid"]]["total"]=="") $chitante[$rowc["factid"]]["total"]=0; if($rowop["cursValue"]==""||$rowop["cursValue"]=="0") $rowop["cursValue"]="1"; $chitante[$rowc["factid"]]["total"]+=$rowc["value"]*$rowc["cursValue"]; } } $queryop="SELECT * FROM `op` WHERE `factid` IN $facturiid"; $resultop=mysql_query($queryop) or die(mysql_error().$queryop); if($resultop&&mysql_num_rows($resultop)>0) { while($rowop=mysql_fetch_array($resultop)) { if($op[$rowop["factid"]]["total"]=="") $op[$rowop["factid"]]["total"]=0; if($rowop["cursValue"]==""||$rowop["cursValue"]=="0") $rowop["cursValue"]="1"; $op[$rowop["factid"]]["total"]+=$rowop["value"]*$rowop["cursValue"]; } } } if($facturi) { foreach($facturi as $fk=>$fv) { if($fv["value"]*$fv["cursValue"]>($op[$fk]["total"]+$chitante[$fk]["total"])) { $all[$fk]=$fv; $all[$fk]["restanta"]=$fv["value"]*$fv["cursValue"]-($op[$fk]["total"]+$chitante[$fk]["total"]); $betw=intval((strtotime(date("Y-m-d")) - strtotime($fv["termenDePlata"])) / (60 * 60 * 24)); $all[$fk]["zile"]=$betw; } } } return $all!=NULL; } function stock_getServiceModel($modelid) { $query="SELECT * FROM `service_models` WHERE `id`='$modelid'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)) $row=mysql_fetch_array($result); return $row; } function dateDifference1($startDate, $endDate) { $startDate = strtotime($startDate); $endDate = strtotime($endDate); if ($startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 || $startDate > $endDate) return false; $years = date('Y', $endDate) - date('Y', $startDate); $endMonth = date('m', $endDate); $startMonth = date('m', $startDate); // Calculate months $months = $endMonth - $startMonth; if ($months <= 0) { $months += 12; $years--; } if ($years < 0) return false; // Calculate the days $offsets = array(); if ($years > 0) $offsets[] = $years . (($years == 1) ? ' year' : ' years'); if ($months > 0) $offsets[] = $months . (($months == 1) ? ' month' : ' months'); $offsets = count($offsets) > 0 ? '+' . implode(' ', $offsets) : 'now'; $days = $endDate - strtotime($offsets, $startDate); $days = date('z', $days); return array($years, $months, $days); } function getUserHistory($searchval,$fromDate,$toDate,$pager,$howmany,$userid) { $query="SELECT * FROM `usersHistory` WHERE `datetime` >= '$fromDate' AND `datetime`<='$toDate' AND `userid`='$userid' AND `text`!='' AND `text` LIKE '%$searchval%' ORDER BY `datetime` DESC LIMIT ".($pager-1)*$howmany.", $howmany"; $result=mysql_query($query) or die($query.mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function isInDepartament($id,$table,$userid) { $query="SELECT * FROM `$table` WHERE `id`='$id' AND `departament` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid') ) OR `departament`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid')"; $result=mysql_query($query) or die(mysql_error()); return ($result&&mysql_num_rows($result)>0); } function getAllUploadedFileForEvent($eventid) { $query="SELECT * FROM `crm_eventsFiles` WHERE `eventid`='$eventid'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[]=$row; } return $all; } function crmFileToDB($picname, $prodid) { $query='INSERT INTO crm_eventsFiles (`id`, `eventid`, `filename`) VALUES (NULL, "'.$prodid.'", "'.$picname.'");'; $lekerdezes=mysql_query($query) or die(mysql_error()); } function comandaFileToDB($picname,$prodid) { $q="SELECT * FROM `comandaForClientAdvFiles` WHERE `command_id`='$prodid' AND `path`='$picname'"; mysql_query($q) or die(mysql_error()); $x=mysql_affected_rows(); if ($x==0){ $query='INSERT INTO `comandaForClientAdvFiles` ( `command_id`,`ondate`,`path`) VALUES ("'.$prodid.'", NOW(), "'.$picname.'");'; $lekerdezes=mysql_query($query) or die(mysql_error()); } } function contractFileToDB($picname,$prodid) { $q="SELECT * FROM `contractForComandaFiles` WHERE `contract_id`='$prodid' AND `path`='$picname'"; mysql_query($q) or die(mysql_error()); $x=mysql_affected_rows(); if ($x==0){ $query='INSERT INTO `contractForComandaFiles` ( `contract_id`,`ondate`,`path`) VALUES ("'.$prodid.'", NOW(), "'.$picname.'");'; $lekerdezes=mysql_query($query) or die(mysql_error()); } } function dosarFileToDB($picname,$prodid) { $q="SELECT * FROM `dosarFiles` WHERE `dosar_id`='$prodid' AND `path`='$picname'"; mysql_query($q) or die(mysql_error()); $x=mysql_affected_rows(); if ($x==0){ $query='INSERT INTO `dosarFiles` ( `dosar_id`,`ondate`,`path`) VALUES ("'.$prodid.'", NOW(), "'.$picname.'");'; $lekerdezes=mysql_query($query) or die(mysql_error()); } } function comandaGetFiles($comid){ $query="SELECT * FROM `comandaForClientAdvFiles` where `command_id`='$comid'"; $result=mysql_query($query) or die(mysql_error()); $lista=array(); while($row=mysql_fetch_array($result)) $lista[]=$row['path']; return $lista; } function getContractContent($id){ $query="SELECT `content` FROM `contractForComanda` WHERE `id`='$id'"; $res=mysql_fetch_array(mysql_query($query)); return $res['content']; } function contractGetFiles($comid){ $query="SELECT * FROM `contractForComandaFiles` where `contract_id`='$comid'"; $result=mysql_query($query) or die(mysql_error()); $lista=array(); while($row=mysql_fetch_array($result)) $lista[]=$row['path']; return $lista; } function dosar_GetFiles($dosid){ $query="SELECT * FROM `dosarFiles` where `dosar_id`='$dosid'"; $result=mysql_query($query) or die(mysql_error()); $lista=array(); while($row=mysql_fetch_array($result)) $lista[]=$row['path']; return $lista; } function crmFileUpload($uploaded_file, $prodid) { // Ellenorizzuk, hogy van-e fajl if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { // Ellenorizzuk, hogy az .jpg vagy .png kiterjesztesu-e es hogy kisebb 500kb-nal $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); $kapott=str_replace(" ","_",$_FILES["uploaded_file"]["name"]); $newname = dirname(__FILE__).'/images/uploaded/'.$kapott; // Ellenorizzuk, hogy letezik-e mar if (!file_exists($newname)) { // Ha nem letezik, felpakoljuk if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { crmFileToDB($kapott, $prodid); $mess= getTraducere("Fisierul a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=false; } else { $mess= getTraducere("Gresit! Fisierul nu prea a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=true; } } else { $kapott=(microtime()).str_replace(" ","_",$_FILES["uploaded_file"]["name"]); $newname=dirname(__FILE__).'/images/uploaded/'.$kapott; $mess= getTraducere("Greseala: Fisierul ",$_SESSION["settings"]["default_lang"]).$_FILES["uploaded_file"]["name"]." ".getTraducere("deja exista!",$_SESSION["settings"]["default_lang"]); $err=true; if (!file_exists($newname)) { // Ha nem letezik, felpakoljuk if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { crmFileToDB($kapott, $prodid); $mess= getTraducere("Fisierul a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=false; } else { $err=true; $mess= getTraducere("Gresit! Fisierul nu prea a fost uploadat!",$_SESSION["settings"]["default_lang"]); } } } } else { $mess= getTraducere("Greseala: Fisierul nu a fost uploadat!",$_SESSION["settings"]["default_lang"]); $err=true; } if(!$err) $MessageHelpDialog=$mess; else $errorMessageHelpDialog=$mess; include("global_helpDialog.php"); } function comandaFileDelete($file,$number){ if (file_exists(dirname(__FILE__).'/images/uploaded/'.$file)){ unlink(dirname(__FILE__).'/images/uploaded/'.$file); } if (count(glob(dirname(__FILE__).'/images/uploaded/comanda/'.$number.'/*')) === 0) rmdir(dirname(__FILE__).'/images/uploaded/comanda/'.$number.'/'); } function dosarFileDelete($file,$number){ if (file_exists(dirname(__FILE__).'/images/uploaded/'.$file)){ unlink(dirname(__FILE__).'/images/uploaded/'.$file); } if (count(glob(dirname(__FILE__).'/images/uploaded/dosar/'.$number.'/*')) === 0) rmdir(dirname(__FILE__).'/images/uploaded/dosar/'.$number.'/'); } function contractFileDelete($file,$number){ if (file_exists(dirname(__FILE__).'/images/uploaded/'.$file)){ unlink(dirname(__FILE__).'/images/uploaded/'.$file); } if (count(glob(dirname(__FILE__).'/images/uploaded/contract_comanda/'.$number.'/*')) === 0) rmdir(dirname(__FILE__).'/images/uploaded/contract_comanda/'.$number.'/'); } function comandaDeleteNonSavedFiles($lista,$number){ if (count($lista)>0){ foreach ($lista as $i=>$value){ $q="SELECT * FROM `comandaForClientAdvFiles` WHERE `path`='$value'"; mysql_query($q); if (mysql_affected_rows()==0){ comandaFileDelete($value,$number); } } } } function dosarDeleteNonSavedFiles($lista,$number){ if (count($lista)>0){ foreach ($lista as $i=>$value){ $q="SELECT * FROM `dosarFiles` WHERE `path`='$value'"; mysql_query($q); if (mysql_affected_rows()==0){ dosarFileDelete($value,$number); } } } } function contractDeleteNonSavedFiles($lista,$number){ if (count($lista)>0){ foreach ($lista as $i=>$value){ $q="SELECT * FROM `contractForComandaFiles` WHERE `path`='$value'"; mysql_query($q); if (mysql_affected_rows()==0){ contractFileDelete($value,$number); } } } } function comandaFileUpload($uploaded_file,$number) { // Ellenorizzuk, hogy van-e fajl if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); $kapott=str_replace(" ","_",$_FILES["uploaded_file"]["name"]); $newname = dirname(__FILE__).'/images/uploaded/comanda/'.$number.'/'.$kapott; if (!file_exists(dirname(__FILE__).'/images/uploaded/comanda/')) mkdir(dirname(__FILE__).'/images/uploaded/comanda/'); if (!file_exists(dirname(__FILE__).'/images/uploaded/comanda/'.$number.'/')) mkdir(dirname(__FILE__).'/images/uploaded/comanda/'.$number.'/'); if (!file_exists($newname)) { // Ha nem letezik, felpakoljuk if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { return 1; } else { return 0; } } else { return -1; } } else { return 0; } } function dosarFileUpload($uploaded_file,$number) { // Ellenorizzuk, hogy van-e fajl if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); $kapott=str_replace(" ","_",$_FILES["uploaded_file"]["name"]); $newname = dirname(__FILE__).'/images/uploaded/dosar/'.$number.'/'.$kapott; if (!file_exists(dirname(__FILE__).'/images/uploaded/dosar/')) mkdir(dirname(__FILE__).'/images/uploaded/dosar/'); if (!file_exists(dirname(__FILE__).'/images/uploaded/dosar/'.$number.'/')) mkdir(dirname(__FILE__).'/images/uploaded/dosar/'.$number.'/'); if (!file_exists($newname)) { // Ha nem letezik, felpakoljuk if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { return 1; } else { return 0; } } else { return -1; } } else { return 0; } } function contractFileUpload($uploaded_file,$number) { // Ellenorizzuk, hogy van-e fajl if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); $kapott=str_replace(" ","_",$_FILES["uploaded_file"]["name"]); $newname = dirname(__FILE__).'/images/uploaded/contract_comanda/'.$number.'/'.$kapott; if (!file_exists(dirname(__FILE__).'/images/uploaded/contract_comanda/')) mkdir(dirname(__FILE__).'/images/uploaded/contract_comanda/'); if (!file_exists(dirname(__FILE__).'/images/uploaded/contract_comanda/'.$number.'/')) mkdir(dirname(__FILE__).'/images/uploaded/contract_comanda/'.$number.'/'); if (!file_exists($newname)) { // Ha nem letezik, felpakoljuk if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { return 1; } else { return 0; } } else { return -1; } } else { return 0; } } function crm_getUplodedFiles($id){ $query="SELECT `filename` FROM `crm_eventsFiles` WHERE `eventid`='$id'"; $result=mysql_query( $query ) or die(mysql_error()); $lista=array(); while($rows=mysql_fetch_array($result)){ $lista[]=$rows['filename']; } return $lista; } function deleteFileFromEvent($imgid) { $query="DELETE FROM `crm_eventsFiles` WHERE `id`='$imgid'"; $result=mysql_query($query) or die(mysql_error()); } function sendAvertizareAprobatToDepartament($departid,$commandnumber,$szoveg,$type, $modositott='', $szoveg_neautorizat=''){ $departament=getAngajatiInDepartament($departid); $mail_content=' '.getTraducere("Avertizare - PaperManagement",$_SESSION["settings"]["default_lang"]).'
'.getTraducere("A fost trimis o avertizare din sistem",$_SESSION["settings"]["default_lang"]).' '.$root_folder.'!
'; $params['host'] = 'localhost'; // The smtp server host/ip $params['port'] = 25; // The smtp server port $params['auth'] = TRUE; // Whether to use basic authentication or not $params['user'] = 'office@sigma-net.ro'; // Username for authentication $params['pass'] = 'miniszoknya'; $from_mail_name="sc SigmaNet Srl"; //Nev, ami megjelenik (Nev) $from_mail="office@sigma-net.ro"; //email cim ami megjelenik (Nev) $subject=getTraducere("Avertizare PaperManagement",$_SESSION["settings"]["default_lang"])." - $type"; // mi legyen a temaja(subject) $sTimestamp=date('r'); // print_r($departament); $resipients1=array(); $resipients2=array(); foreach ($departament as $key=>$value){ $u=users_getUser($value['userid']); if ($u['generalFinalPriceView']){ $recipients2[]=$value['email']; }else $recipients1[]=$value['email']; } $content1=$mail_content.$szoveg.'
'.$szoveg_neautorizat.'
'.getTraducere("generat din SigmaNet PaperManagement v",$_SESSION["settings"]["default_lang"]).' 6.9
www.sigma-net.ro
'; $content2=$mail_content.$szoveg.'
'.$modositott.'
'.getTraducere("generat din SigmaNet PaperManagement v",$_SESSION["settings"]["default_lang"]).' 6.9
www.sigma-net.ro
'; $send_params['recipients'] = $recipients1; $send_params['headers'] = array('Content-type: text/html; charset=iso-8859-1', 'From: "'.$from_mail_name.'" <'.$from_mail.'>', // Headers 'Date: '.$sTimestamp.'\n', 'To: '.$send_params['recipients'][0], 'Subject: '.$subject, 'Return-Path: "office@sigma-net.ro"', 'Reply-To: "office@sigma-net.ro"', 'Content-Transfer-Encoding: 7bit'); $send_params['from'] = $params['user']; // This is used as in the MAIL FROM: cmd $send_params['body'] = $content1; if( is_object($smtp = smtp::connect($params)) AND $smtp->send($send_params) ){ $send_params['recipients'] = $recipients2; $send_params['headers'] = array('Content-type: text/html; charset=iso-8859-1', 'From: "'.$from_mail_name.'" <'.$from_mail.'>', // Headers 'Date: '.$sTimestamp.'\n', 'To: '.$send_params['recipients'][0], 'Subject: '.$subject, 'Return-Path: "office@sigma-net.ro"', 'Reply-To: "office@sigma-net.ro"', 'Content-Transfer-Encoding: 7bit'); $send_params['from'] = $params['user']; // This is used as in the MAIL FROM: cmd $send_params['body'] = $content2; if( is_object($smtp = smtp::connect($params)) AND $smtp->send($send_params) ){ return true; }else{ return false; } }else{ return false; } } function getDepartamentbyuserid($id){ $query="SELECT `main_departament` FROM `hr` WHERE `userid`='$id'"; $eredmeny=mysql_fetch_array(mysql_query($query)); return $eredmeny[0]; } function getAllDepartamentsByUserId($id,$userid){ $idk=array(); $idk[]=getDepartamentbyuserid($userid); $query="SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`='$id'"; $result=mysql_query( $query ) or die($query.mysql_error()); while ($row=mysql_fetch_array($result)){ if (!in_array($row['dep_id'],$idk)) $idk[]=$row['dep_id']; } if (count($idk)>=1){ $idize='('; for ($i=0;$i'.getTraducere("Nota de intrare",$_SESSION["settings"]["default_lang"]).''; $lista[$i]['number2']=''.$row['number'].''; $part=partner_getPartnerbyId($row['provider']); $lista[$i]['comment2']=getTraducere("Furnizor",$_SESSION["settings"]["default_lang"]).':'.$part['name'].''; $lista[$i]['comment']=getTraducere("Furnizor",$_SESSION["settings"]["default_lang"]).':'.$part['name']; } $i++; } return $lista; } function getAllStockItemFromProdId($prodid){ $query="SELECT `si`.*,`s`.`name` FROM `stock_items` as `si`, `stocks` as `s` WHERE `si`.`itemid`='$prodid' AND `si`.`stockid`=`s`.`id` order by `s`.`name` asc"; $result=mysql_query( $query ) or die(mysql_error()); $lista=array(); while($row=mysql_fetch_array($result)) $lista[]=$row; return $lista; } function getAllBonConsumFromProdId($prodid,$from,$to){ $query="SELECT `bi`.*,`b`.`number`,`b`.`id` as `bid`,`b`.`fromActAdvId` FROM `bonConsum_items` as `bi`, `bonConsum` as `b` WHERE `bi`.`modelid`='$prodid' AND `bi`.`factid`=`b`.`id` AND `b`.`ondate` BETWEEN '$from' AND '$to' order by `bi`.`ondate` desc"; $result=mysql_query( $query ) or die(mysql_error()); $lista=array();$i=0; while($row=mysql_fetch_array($result)){ $lista[$i]=$row; $lista[$i]['ar']=$row['natprice']; $lista[$i]['iesire_quantity']=$row['quantity']; $lista[$i]['iesire_price']=$row['natprice']; $lista[$i]['intr_price']='-'; $lista[$i]['intr_quantity']='-'; $lista[$i]['sold_anterior']='-'; $lista[$i]['sold']='-'; $lista[$i]['tip']=getTraducere("Bon consum",$_SESSION["settings"]["default_lang"]); $lista[$i]['tip2']=''.getTraducere("Bon consum",$_SESSION["settings"]["default_lang"]).''; $lista[$i]['number2']=''.$row['number'].''; if ($row['fromActAdvId']){ $part=command_getCommandById($row['fromActAdvId']); $lista[$i]['comment2']=''.getTraducere("Comanda nr",$_SESSION["settings"]["default_lang"]).':'.convertToSerial($part['secondserial']).''; $lista[$i]['comment']=getTraducere("Comanda nr",$_SESSION["settings"]["default_lang"]).':'.convertToSerial($part['secondserial']); } $i++; } return $lista; } function getAllAvizFromProdId($prodid,$from,$to){ $query="SELECT `ai`.*,`a`.`number`,`a`.`id` as `aid`,`a`.`fromActAdvId` FROM `avizeOutItems` as `ai`, `avizeOut` as `a` WHERE `a`.`removedFromStock`='1' AND `ai`.`stockItem`='$prodid' AND `ai`.`factid`=`a`.`id` AND `ai`.`ondate` BETWEEN '$from' AND '$to' order by `ai`.`ondate` desc"; $result=mysql_query( $query ) or die(mysql_error()); $lista=array();$i=0; while($row=mysql_fetch_array($result)){ $lista[$i]=$row; $lista[$i]['ar']=$row['natprice']; $lista[$i]['iesire_quantity']=$row['quantity']; $lista[$i]['iesire_price']=$row['natprice']; $lista[$i]['intr_price']='-'; $lista[$i]['intr_quantity']='-'; $lista[$i]['sold_anterior']='-'; $lista[$i]['sold']='-'; $lista[$i]['tip']=getTraducere("Aviz",$_SESSION["settings"]["default_lang"]); $lista[$i]['number2']=''.$row['number'].''; $lista[$i]['tip2']=''.getTraducere("Aviz",$_SESSION["settings"]["default_lang"]).''; if ($row['fromActAdvId']){ $part=command_getCommandById($row['fromActAdvId']); $lista[$i]['comment2']=''.getTraducere("Comanda nr",$_SESSION["settings"]["default_lang"]).':'.convertToSerial($part['secondserial']).''; $lista[$i]['comment']=getTraducere("Comanda nr",$_SESSION["settings"]["default_lang"]).':'.convertToSerial($part['secondserial']); } $i++; } return $lista; } function getAllFacturaFromProdId($prodid, $from, $to){ $query="SELECT `fi`.*,`f`.`number`,`f`.`id` as `fid`,`f`.`fromActAdvId` FROM `facturi_items` as `fi`, `facturi` as `f` WHERE `f`.`removedFromStock`='1' AND `fi`.`modelid`='$prodid' AND `fi`.`factid`=`f`.`id` AND `fi`.`ondate` BETWEEN '$from' AND '$to' order by `fi`.`ondate` desc"; $result=mysql_query( $query ) or die(mysql_error()); $lista=array();$i=0; while($row=mysql_fetch_array($result)){ $lista[$i]=$row; $lista[$i]['ar']=$row['natprice']; $lista[$i]['iesire_quantity']=$row['quantity']; $lista[$i]['iesire_price']=$row['natprice']; $lista[$i]['intr_price']='-'; $lista[$i]['intr_quantity']='-'; $lista[$i]['sold_anterior']='-'; $lista[$i]['sold']='-'; $lista[$i]['tip']=getTraducere("Factura",$_SESSION["settings"]["default_lang"]); $lista[$i]['number2']=''.$row['number'].''; $lista[$i]['tip2']=''.getTraducere("Factura",$_SESSION["settings"]["default_lang"]).''; if ($row['fromActAdvId']){ $part=command_getCommandById($row['fromActAdvId']); $lista[$i]['comment2']=''.getTraducere("Comanda nr",$_SESSION["settings"]["default_lang"]).':'.convertToSerial($part['secondserial']).''; $lista[$i]['comment']=getTraducere("Comanda nr",$_SESSION["settings"]["default_lang"]).':'.convertToSerial($part['secondserial']); } $i++; } return $lista; } function getCs($id){ $query="SELECT * FROM `models_cs_values` WHERE `id`= $id order by name"; $result = mysql_query($query) or die(mysql_error()); return mysql_fetch_array($result); } function getModelCs($id){ $query="SELECT * FROM `models_cs` WHERE `id`='$id' "; $query; $result = mysql_query($query) or die(mysql_error()); return mysql_fetch_array($result); } function nir_getLastDate(){ $query="SELECT max(`ondate`) as `date` FROM `nir`"; $datum=mysql_fetch_array(mysql_query($query)); return $datum['date']; } function bonConsum_getLastDate(){ $query="SELECT max(`ondate`) as `date` FROM `bonConsum`"; $datum=mysql_fetch_array(mysql_query($query)); return $datum['date']; } function getAllNirByOnDate($toDate,$stockid){ $locid = $_SESSION["user"]["defstock"]; if ($stockid) $st="`ni`.`stock_id`='$stockid'"; else $st=''; if ($toDate=='') $toDate=substr(date("Y-m-d G:i:s"),0,10); $query="SELECT `ni`.*,`n`.`number` FROM `nir_items` as `ni`, `nir` as `n`,`stocks` as `s` WHERE `ni`.`ondate` <= '$toDate"." 23:59:59"."' AND $st `ni`.`nir_id`=`n`.`id` AND `s`.`id`=`ni`.`stock_id` AND `n`.`active`='1' AND `s`.`locid`='$locid' order by `ni`.`ondate` desc"; $result=mysql_query( $query ) or die(mysql_error()); $lista=array();$i=0; while($row=mysql_fetch_array($result)){ $lista[$i]=$row; $lista[$i]['pprice']=$row['rawvalue']; $lista[$i]['tip']='Nir'; $i++; } return $lista; } function getAllBonConsumByOnDate($toDate,$stockid){ $locid = $_SESSION["user"]["defstock"]; if ($stockid) $st="`bi`.`stock_id`='$stockid' AND "; else $st=''; if ($toDate=='') $toDate=substr(date("Y-m-d G:i:s"),0,10); $query="SELECT `bi`.*,`b`.`number` FROM `bonConsum_items` as `bi`, `bonConsum` as `b`, `stocks` as `s` WHERE `bi`.`ondate` <= '$toDate"." 23:59:59"."' AND $st `bi`.`factid`=`b`.`id` AND `s`.`id`=`bi`.`stock_id` AND `s`.`locid`='$locid' order by `bi`.`ondate` desc"; $result=mysql_query( $query ) or die(mysql_error()); $lista=array();$i=0; while($row=mysql_fetch_array($result)){ $lista[$i]=$row; $lista[$i]['pprice']=$row['natprice']; $lista[$i]['quantity']=-1*$row['quantity']; $lista[$i]['tip']=getTraducere("Bon consum",$_SESSION["settings"]["default_lang"]); $lista[$i]['itemid']=$row['modelid']; $i++; } return $lista; } function osszesort($a,$b){ return strnatcmp($a['stocname'],$b['stocname']); } function sort_item($a,$b){ if ($a['itemid']>$b['itemid']) return true; else return false; } function returnProductinStockbyDate($prodid,$toDate,$price){ if ($toDate=='') $toDate=substr(date("Y-m-d G:i:s"),0,10); //nirek lekerese; $query="SELECT sum(`quantity`) as `osszeg` FROM `nir_items` WHERE `itemid`='$prodid' and `ondate`<'$toDate'"; $result=mysql_query( $query ) or die(mysql_error()); $nirek=0; $row=mysql_fetch_array($result); if ($row['osszeg']) $nirek=$row['osszeg']; //bonok lekerese; $quer="SELECT sum(`quantity`) as `osszeg` FROM `bonConsum_items` WHERE `modelid`='$prodid' and `ondate`<'$toDate'"; $resul=mysql_query($quer) or die(mysql_error()); $bonok=0; $ro=mysql_fetch_array($resul); if ($ro['osszeg']) $bonok=$ro['osszeg']; $que="SELECT sum(`ai`.`quantity`) as `osszeg` FROM `avizeOutItems` as `ai`, `avizeOut` as `a` WHERE `a`.`removedFromStock`='1' AND `ai`.`factid`=`a`.`id` AND `ai`.`stockItem`='$prodid' and `ai`.`ondate`<'$toDate'"; $resu=mysql_query($que) or die(mysql_error()); $avizok=0; $r=mysql_fetch_array($resu); if ($r['osszeg']) $avizok=$r['osszeg']; $qu="SELECT sum(`fi`.`quantity`) as `osszeg` FROM `facturi_items` as `fi`, `facturi` as `f` WHERE `f`.`removedFromStock`='1' AND `fi`.`factid`=`f`.`id` AND `fi`.`modelid`='$prodid' and `fi`.`ondate`<'$toDate'"; $res=mysql_query($qu) or die(mysql_error()); $facturak=0; $rr=mysql_fetch_array($res); if ($rr['osszeg']) $facturak=$rr['osszeg']; return $nirek-$bonok-$avizok-$facturak; } function bonConsum_search_expandXls( $stockid , $toDate ){ $nirek=getAllNirByOnDate($toDate,$stockid); $bonok=getAllBonConsumByOnDate($toDate,$stockid); $osszes=array(); $osszes= array_merge($osszes, $nirek); $osszes= array_merge($osszes, $bonok); uasort($osszes,'sort_item'); $osszevarialva=array(); foreach ($osszes as $key=>$value){ $i=0;$megvan=0; while ($i$values){ if ($values['quantity']>0.00001){ $value[]=$values; $osszegzo[$values['stock_id']]['total']+=$values['quantity']*$values['price']; $osszegzo[$values['stock_id']]['name']=$values['stocname']; $osszegzo[$values['stock_id']]['cat']=$values['cat']; } else if (round($values['quantity'])<0){ $value[]=$values; $osszegzo[$values['stock_id']]['total']+=$values['quantity']*$values['price']; $osszegzo[$values['stock_id']]['name']=$values['stocname']; $osszegzo[$values['stock_id']]['cat']=$values['cat']; } } $value[]=$osszegzo; return $value; } function rendez_datum($a,$b){ if (strtotime($a['ondate'])$b['name']) return true; else return false; } function entry_getEntry_Inchiriate_Rezervate($key,$mod,$userid,$page,$onpage,$rezervari,$modelid){ if ($key!=''){ if ($mod=='all'){ $q=" AND (`c`.`name` LIKE '%".$key."%' OR `c`.`code_produs` LIKE '%$key%' OR `c`.`desc` LIKE '%$key%')"; }else if ($mod=='name'){ $q=" AND `c`.`name` LIKE '%".$key."%'"; }else if ($mod=='code'){ $q=" AND `c`.`code_produs` LIKE '%".$key."%'"; }else if ($mod=='desc'){ $q=" AND `c`.`desc` LIKE '%".$key."%'"; }else $q=''; }else $q=''; if ($userid!='0'){ $user="`i`.`user_id`='$userid'"; $user2="`r`.`user_id`='$userid'"; }else{ $user=1; $user2=1; } if ($modelid=='') $query="SELECT `i`.*, `c`.`name`,`c`.`code_produs` FROM `inchirieri` as `i`, `container` as `c` WHERE $user AND `i`.`produsId`=`c`.`id` $q"; else $query="SELECT `i`.*, `c`.`name`,`c`.`code_produs` FROM `inchirieri` as `i`, `container` as `c`, `models` as `m` WHERE $user AND `m`.`id`=`c`.`modelid` AND `c`.`modelid`='$modelid' AND `i`.`produsId`=`c`.`id` $q"; $result=mysql_query( $query ) or die(mysql_error()); $lista=array();$i=0; while ($rows=mysql_fetch_array($result)){ $lista[$i]=$rows; $lista[$i]['mod']=getTraducere("Inchiriat",$_SESSION["settings"]["default_lang"]); $hr=hr_getUser($rows['user_id']); $lista[$i++]['pentru']="".$hr['forname']." ".$hr["lastname"].""; } //ha nem kerem a rezervalasokat is if ($rezervari!='0'){ //ha kerem a rezervalasokat if ($modelid=='') $query="SELECT `r`.*,`c`.`name`,`c`.`code_produs` FROM `rezervareProdus` as `r`, `container` as `c` WHERE $user2 AND `r`.`produsId`=`c`.`id` $q"; else $query="SELECT `r`.*,`c`.`name`,`c`.`code_produs` FROM `rezervareProdus` as `r`, `container` as `c`, `models` as `m` WHERE $user2 AND `m`.`id`=`c`.`modelid` AND `c`.`modelid`='$modelid' AND `r`.`produsId`=`c`.`id` $q"; $result=mysql_query( $query ) or die(mysql_error()); while ($rows=mysql_fetch_array($result)){ $lista[$i]=$rows; $lista[$i]['mod']='Rezervat'; $com="SELECT * FROM `comandaForClientAdv` WHERE `id`='".$rows['comandaId']."'"; $c=mysql_fetch_array(mysql_query($com)); $pa="SELECT * FROM `partners` WHERE `id`='".$c['clientid']."'"; $part=mysql_fetch_array(mysql_query($pa)); $szam=''; for ($l=0;$l<6-count($c[0]['secondserial']);$l++) $szam.='0'; $hr=hr_getUser($rows['user_id']); $comint=getComandaInternaFromComandaId($rows['comandaId']); $lista[$i]['pentru']=''.getTraducere("Comanda nr.",$_SESSION["settings"]["default_lang"]).':'.$szam.$c[0]['secondserial'].", ".getTraducere("pentru clientul",$_SESSION["settings"]["default_lang"]).":".$part['name']."
".getTraducere("de catre",$_SESSION["settings"]["default_lang"])." ".$hr['forname']." ".$hr["lastname"].""; if ($comint) $lista[$i]['pentru'].='
'.getTraducere("Comanda interna nr.",$_SESSION["settings"]["default_lang"]).':'.$comint['numberSerial']; $i++; } } uasort($lista,'rendez_nev'); if ($page && $onpage){ $vegleg=array();$i=0; foreach ($lista as $key=>$v) $vegleg[$i++]=$v; $lista=array(); $kezd=$page*$onpage-$onpage; if ($kezd>count($vegleg)) $kezd=0; $vege=$kezd+$onpage; for ($i=$kezd;$i<$vege;$i++){ if ($i>=count($vegleg)) break; $lista[]=$vegleg[$i]; } } return $lista; } function getNrOfSentMessages($type, $id, $clientemail){ $query="SELECt * FROM `documentViews` WHERE `type`='$type' AND `factid`='$id' AND `accessEmail`='$clientemail'"; mysql_query( $query ) or die(mysql_error()); return mysql_affected_rows(); } function crm_tree($items,&$duplazott,&$x,$key,$szint){ if (in_array($key,$duplazott)){ return $x; }else{ $x[$key]=$items[$key]; $x[$key]['row']=$szint; if ($items[$key]['followUpEventId']!=0){ $duplazott[]=$key; $szint+=1; crm_tree($items,$duplazott,$x,$items[$key]['followUpEventId'],$szint); }else{ $duplazott[]=$key; return $x; } } } function stoc_getStocCategorybyId($id){ $query="SELECT * FROM `stocks_Category` WHERE `id`='$id'"; $result=mysql_query($query) or die(mysql_error()); if ($result){ return mysql_fetch_array($result); }else return NULL; } function aviz_stornoAviz($avizid){ $av="SELECT `removedFromStock` FROM `avizeOut` WHERE `id`='$avizid'"; $aviz=mysql_fetch_array(mysql_query($av)); //letrehozom a masolatot az avizrol $number="SELECT * FROM `serials` WHERE `id`='21'"; $numb=mysql_fetch_array(mysql_query($number)); $m="SELECT `id`,`clientid`,`userid`,`stockid`,`rawvalue`,`value`,`serial`,`number`,`content`,`printed`,`closed`,NOW(),`active`,`paymode`,`comments`,`termenDePlata`,`dataExecutiei`,`cursValutar`,`onValuta`,`cursValue`,`fromActId`,`fromActAdvId`,`removedFromStock` FROM `avizeOut` WHERE `id`='$avizid'"; $mit=mysql_fetch_array(mysql_query($m)); $mit['content']=str_replace($mit['number'],$numb['current']+1,$mit['content']); $query="INSERT INTO `avizeOut`(`clientid`,`userid`,`stockid`,`rawvalue`,`value`,`serial`,`number`,`content`,`printed`,`closed`,`ondate`,`active`,`paymode`,`comments`,`termenDePlata`,`dataExecutiei`,`cursValutar`,`onValuta`,`cursValue`,`fromActId`,`fromActAdvId`,`removedFromStock`) VALUES ('".$mit['clientid']."','".$mit['userid']."','".$mit['stockid']."','".($mit['rawvalue']*(-1))."','".($mit['value']*(-1))."','".$mit['serial']."','".$numb['current']."','".str_replace("'","\'",$mit['content'])."','".$mit['printed']."','".$mit['closed']."',NOW(),'".$mit['active']."','".$mit['paymode']."','".$mit['comments']."','".$mit['termenDePlata']."','".$mit['dataExecutiei']."','".$mit['cursValutar']."','".$mit['onValuta']."','".$mit['cursValue']."','".$mit['fromActId']."','".$mit['fromActAdvId']."','".$mit['removedFromStock']."')"; mysql_query($query) or die(mysql_error()); $ujelemid=mysql_insert_id(); $el="SELECT * FROM `avizeOutItems` WHERE `factid`='".$mit['id']."'"; $elres=mysql_query($el) or die(mysql_error()); while ($row=mysql_fetch_array($elres)){ $mit['content']=str_replace("
".$row['quantity']."
","
-".$row['quantity']."
",$mit['content']); $mit['content']=str_replace("
".round($row['natprice']*$row['quantity'],3)."
","
-".round($row['natprice']*$row['quantity'],3)."
",$mit['content']); $insert="INSERT INTO `avizeOutItems`(`factid`,`modelid`,`price`,`natprice`,`quantity`,`type`,`rowName`,`ondate`,`stockItem`,`product_type`) VALUES ('$ujelemid','".$row['modelid']."','".$row['price']."','".$row['natprice']."','".($row['quantity']*(-1))."','".$row['type']."','".$row['rowName']."',NOW(),'".$row['stockItem']."','".$row['product_type']."')"; mysql_query($insert) or die(mysql_error()); //visszarakom az elemeit a raktarba, ha kivolt veve if ($aviz['removedFromStock']=='1'){ $stock="SELECT * FROM `stock_items_out` WHERE `itemid`='".$row['modelid']."' AND `quantity`='".$row['quantity']."' AND `ondate`='".$row['ondate']."'"; $stout=mysql_fetch_array(mysql_query($stock)); if ($stout){ $inserttostock="INSERT INTO `stock_items` (`ondate`,`userid`,`provid`,`stockid`,`itemid`,`code`,`quantity`,`price`,`natprice`,`src`,`arrived`,`transfercode`,`quantityType`,`moneyType`,`punctDeLucruID`,`serialNumber`) VALUES (NOW(),'".$stout['userid']."','".$stout['provid']."','".$stout['stockid']."','".$stout['itemid']."','1','".$stout['quantity']."','".$stout['originalprice']."','".($stout['originalprice']*(1+$_SESSION['settings']['tva']))."','".$stout['src']."','1','1','".$stout['quantityType']."','RON','".$_SESSION['user']['defstock']."','')"; mysql_query($inserttostock)or die (mysql_error()); } } } $update="UPDATE `avizeOut` SET `content`='".str_replace("'","\'",$mit['content'])."' WHERE `id`='$ujelemid'"; mysql_query($update) or die (mysql_error()); // modositom a serials tablat $query="UPDATE `serials` set `current`=".($numb['current']+1)." WHERE `id`='21'"; mysql_query( $query ) or die(mysql_error()); } function factura_putItemsBackToStock($stornoid){ $query="SELECT `fi`.* FROM `facturi` as `f`, `facturi_items` as `fi` WHERE `f`.`id`='$stornoid' AND `f`.`id`=`fi`.`factid` AND `f`.`removedFromStock`='1'"; $result=mysql_query( $query ) or die($query.mysql_error()); if (mysql_affected_rows ()>0){ while ($row=mysql_fetch_array($result)){ $stock="SELECT * FROM `stock_items_out` WHERE `itemid`='".$row['modelid']."' AND `quantity`='".$row['quantity']."' AND `ondate`='".$row['ondate']."'"; $stout1=mysql_query($stock) or die($stock.mysql_error()); $stout=mysql_fetch_array($stout1); if ($stout){ $inserttostock="INSERT INTO `stock_items` (`ondate`,`userid`,`provid`,`stockid`,`itemid`,`code`,`quantity`,`price`,`natprice`,`src`,`arrived`,`transfercode`,`quantityType`,`moneyType`,`punctDeLucruID`,`serialNumber`) VALUES (NOW(),'".$stout['userid']."','".$stout['provid']."','".$stout['stockid']."','".$stout['itemid']."','1','".$stout['quantity']."','".$stout['originalprice']."','".($stout['originalprice']*(1+$_SESSION['settings']['tva']))."','".$stout['src']."','1','1','".$stout['quantityType']."','RON','".$_SESSION['user']['defstock']."','')"; mysql_query($inserttostock)or die ($inserttostock.mysql_error()); } } } } function aviz_out_stornoSearch($value,$tomb){ $i=0; foreach($tomb as $key=>$array){ if ($array['userid']==$value['userid'] && $array['stockid']==$value['stockid'] && $array['rawvalue']==(-1)*$value['rawvalue'] && $array['value']==(-1)*$value['value'] && $array['ondate']>$value['ondate']) return false; } return true; } function getAvizByBc($bcid) { $query="SELECT * FROM `aviz` WHERE `bcid`='$bcid'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row; } function getTraducereIfHas($keyw,$lang) { $query="SELECT `id` FROM `lang_keywords` WHERE LOWER(`title`)='".strtolower($keyw)."'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { $row=mysql_fetch_array($result); $kk=$row["id"]; $query2="SELECT `title` FROM `lang_keywords_values` WHERE `kvid`='$kk' AND `lang`='$lang' ORDER BY `id` DESC LIMIT 1"; $result2=mysql_query($query2) or die(mysql_error()); if($result2&&mysql_num_rows($result2)>0) { $row2=mysql_fetch_array($result2); return $row2["title"]; } else return ""; } else return ""; } ///////////////////////////////////////management riport//////////////////////////////// function getReportFileFirstInformationByWorkID($workid) { $query = "select * from reportFileFirstData where workid = '$workid' order by IdPacientFisa "; $result = mysql_query($query) or die ("getReportFileFirstInformationByWorkID ".mysql_error()); $j = 0; while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function getReportFileDiagnosticsByPacientCode($code, $workid) { $query = "select * from reportFileSecondDataCC where CazID = '$code' and workid = '$workid'"; $result = mysql_query($query) or die("getReportFileDiagnosticsByPacientCode ".mysql_error()); $j=0; while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function insertFirstDataFromReportFile($workid,$data_array) { $dates=explode("/",$data_array[5]); $data_array[5]= $dates[2]."-".$dates[1]."-".$dates[0]; $dates=explode("/",$data_array[10]); $data_array[10]= $dates[2]."-".$dates[1]."-".$dates[0]; $query = "INSERT INTO `reportFileFirstData` (`id`, `workid`, `on_date`, `IdPacientFisa`, `CazID`, `CodSpital`, `NFO`, `DataInternare`, `IdTipInternare`, `IdCriteriuInternare`, `CodSectieInternare`, `NrSectieInternare`, `DataExternare`, `IdTipExternare`, `IdStareExternare`, `CodSectieExternare`, `NrSectieExternare`, `CNP`, `Nume`, `Prenume`, `IdLocalitate`, `Strada`, `NrStrada`, `DataNastere`, `Sex`, `GreutateInternare`, `IdNivelInstruire`, `IdOcupatie`, `IdTipCetatenie`, `IdCetatenie`, `IdStatutAsigurat`, `IdTipAsigurareCNAS`, `IdCAS`, `IdCategorieAsiguratCNAS`, `CodMedicCurant`, `CodDI`, `CodDP1`, `CodDP2`, `CodICP`, `CodMedicOperator`, `DataICP`, `IdAccident`, `IdStareValidare`, `IdStareRecord`, `IdTipFinantareSectie`, `SelectieExport`, `Finalizat`, `CodDRG`, `CodValiditateDRG`, `CodValiditateICP`, `CodValiditateDP1`, `CodValiditateDP2`,`VR`,`DMS`,`LI`,`LS`,`RegulaIncalcata`, `SerieBilet`, `NumarBilet`, `CNPMama`, `NFOMama`, `Info`) VALUES ( NULL, '$workid', NOW(), '$data_array[1]', '$data_array[2]', '$data_array[3]', '$data_array[4]', '$data_array[5]', '$data_array[6]', '$data_array[7]', '$data_array[8]', '$data_array[9]', '$data_array[10]', '$data_array[11]', '$data_array[12]', '$data_array[13]', '$data_array[14]', '$data_array[15]', '$data_array[16]', '$data_array[17]', '$data_array[18]', '$data_array[19]', '$data_array[20]', '$data_array[21]', '$data_array[22]', '$data_array[23]', '$data_array[24]', '$data_array[25]', '$data_array[26]', '$data_array[27]', '$data_array[28]', '$data_array[29]', '$data_array[30]', '$data_array[31]', '$data_array[32]', '$data_array[33]', '$data_array[34]', '$data_array[35]', '$data_array[36]', '$data_array[37]', '$data_array[38]', '$data_array[39]', '$data_array[40]', '$data_array[41]', '$data_array[42]', '$data_array[43]', '$data_array[44]', '$data_array[45]', '$data_array[46]', '$data_array[47]', '$data_array[48]', '$data_array[49]', '$data_array[50]', '$data_array[51]', '$data_array[52]', '$data_array[53]', '$data_array[54]', '$data_array[55]', '$data_array[56]', '$data_array[57]', '$data_array[58]', '$data_array[59]' )"; $result = mysql_query($query) or die("insertFirstDataFromReportFile ".mysql_error()); } function insertSecondDataFromReportFile($workid, $data_array) { $query = "INSERT INTO `reportFileSecondDataCC` (`id`, `workid`, `on_date`, `CazID`, `CodDiagnosticSecundar`, `Invalid`) VALUES (NULL, '$workid', NOW(), '$data_array[2]', '$data_array[3]', '$data_array[4]')"; $result = mysql_query($query) or die("insertSecondDataFromReportFile ".mysql_error()); } function insertThirdDataFromReportFile($workid, $data_array) { $query = "INSERT INTO `reportFileThirdDataProceduri` (`id`, `workid`, `on_date`, `CazID`, `CodProcedura`, `Cantitate`, `Invalid`) VALUES (NULL,'$workid', NOW(), '$data_array[2]', '$data_array[3]', '$data_array[4]', '$data_array[5]')"; $result = mysql_query($query) or die("insertThirdDataFromReportFile ".mysql_error()); } function saveReportProcess($array) { $query = "insert into reportWorks(`id`, `clientid`, `hr_id`,`name`, `on_date`,`document_date`) values (NULL, '".$array["clientid"]."', '".$array["managerProiect"]."','".$array["proiectName"]."', NOW(),'".$array["document_date"]."')"; $result = mysql_query($query) or die ("saveReportProcess ".mysql_error()); return mysql_insert_id(); } function updateReportProcess($array, $workid) { if ($array["clientid"]!= "" && $array["managerProiect"] != "" && $array["proiectName"]!= "" && $array["document_date"]!="") { $query = "update reportWorks set clientid = '".$array["clientid"]."', hr_id = '".$array["managerProiect"]."', name = '".$array["proiectName"]."', `document_date`='".$array["document_date"]."' where id = '$workid'"; mysql_query($query) or die("updateReportProcess ".mysql_error()); } } function getAllReportWork() { $query = "select * from reportWorks group by `clientid` order by on_date"; $result = mysql_query($query) or die ("getAllReportWork ".mysql_error()); $j=0; while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function getAllReportbyHospytal($id,$plusz){ if ($plusz=='') $query = "select * from `reportWorks` where `clientid`='$id' order by `document_date`"; else{//felepitem a kereses feltetleit $d=$plusz['firstyear']."-".$plusz['firstmonth']."-01"; $d2=$plusz['lastyear']."-".$plusz['lastmonth']."-31"; $query = "select * from `reportWorks` where `clientid`='$id' and `document_date` between '$d' and '$d2' order by `document_date`"; } $result = mysql_query($query) or die ("getAllReportWorkbyHospytal ".mysql_error()); $j=0; while($row = mysql_fetch_array($result)) { $list[$j] = $row; $j++; } return $list; } function compare_elso($a, $b) { return strnatcmp($a[1],$b[1]); // or other function/code } function elsoRiport($partnerid,$id,$tcp){ $partner=partners_getPartner($partnerid); $chirurgext=0; $sexternare="SELECT `ls`.`tip` FROM `Lista_Sectii` as `ls`, `reportFileFirstData` as `rf` WHERE `ls`.`id`=`rf`.`CodSectieExternare` "; $extquery=mysql_query($sexternare) or die ("ext".mysql_error()); while($stip=mysql_fetch_array($extquery)) if ($stip['tip']=='C') $chirurgext++; $query="SELECT * from `reportFileFirstData` where `workid` in $id group by `CodSectieInternare`"; $result = mysql_query($query) or die ("elsoReport ".mysql_error()); $lista=array();$i=0; while ($row=mysql_fetch_array($result)){ $lista[$i++]=$row; } $cazuri=array(); for ($i=0;$i=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $cazuri[$i][7]+=$days_diff; $coefk+=$k; $cazuri[$i][5]+=$vira['vr']*$k*$tcp; $icm+=$vira['vr']*$k; //indice de operabilitate $proci="SELECT `tip` FROM `Lista_Proceduri` where `cod`='".$e2['CodICP']."'"; $tipus=mysql_fetch_array(mysql_query($proci)); if ($tipus['tip']=='C'){ $chirurgi++; }else{ $tobbiproci="SELECT `lp`.`tip` FROM `reportFileThirdDataProceduri` as `rt`, `Lista_Proceduri` as `lp` WHERE `CazID`='".$e2['CazID']."' AND `rt`.`CodProcedura`=`lp`.`cod`"; $tq=mysql_query($tobbiproci); while ($top=mysql_fetch_array($tq)){ if ($top['tip']=='C'){ $chirurgi++; break; } } } //concordanta di/de if (substr($e2['CodDI'],0,3)==substr($e2['CodDP1'],0,3)) $di++; else{ $kettesnegyes="SELECT * FROM `Lista_exceptii_diagnostice` WHERE `cod_DI`='".$e2['CodDI']."' AND `cod_DP1`='".substr($e2['CodDP1'],0,3)."'"; $qkettes=mysql_query($kettesnegyes); if (mysql_affected_rows()>0) $di++; else{ $egyesharmas="SELECT * FROM `Lista_exceptii_diagnostice` WHERE `cod_DI`='".$e2['CodDI']."' AND `cod_DP1`='".$e2['CodDP1']."'"; $qharmas=mysql_query($egyesharmas); if (mysql_affected_rows()>0) $di++; } } //megye meghatarozasa if ($e2['IdLocalitate']!='0'){//ha megvan adva a helyseg kodja $helyseg="SELECT * FROM `siruta_fara_diacritice` WHERE `SIRUTA`='".$e2['IdLocalitate']."'"; $loc=mysql_fetch_array(mysql_query($helyseg)); $jud="SELECt * FROM `siruta_fara_diacritice` WHERE `JUD`='".$loc['JUD']."' AND `NIV`='1'"; $megye=mysql_fetch_array(mysql_query($jud)); $megy=strtolower(substr($megye['DENLOC'],8)); if ($megy!=strtolower($partner['state'])) $cazuri[$i][9]++; } } $cazuri[$i][7]= round($cazuri[$i][7]/$j); $cazuri[$i][3]= $icm/$j; $cazuri[$i][4]= $coefk/$j; $cazuri[$i][2]=$numarcazuri."
".($numarcazuri-$nevalidate)." / ".$nevalidate; $cazuri[$i][8]=$nrdeces." / ".$nrtransfer; $cazuri[$i][11]=round(($di*100)/ $osszeseset,2); $cazuri[$i][12]=round(($chirurgi*100)/ $chirurgext,2); $osszescnp="SELECT * FROM `reportFileFirstData` where `workid` in $id and `CodSectieInternare`='".$lista[$i]['CodSectieInternare']."' group by `CNP`"; $cnpquery=mysql_query($osszescnp); while ($z=mysql_fetch_array($cnpquery)) if ($z['CNP']!='0' && $z['CNP']!=''){ $duplak="SELECT * FROM `reportFileFirstData` where `workid` in $id AND `CodSectieInternare`='".$lista[$i]['CodSectieInternare']."' and `CNP`='".$z['CNP']."' order by `DataInternare` asc"; $qu=mysql_query($duplak); if (mysql_affected_rows()>1){ $cnp1=mysql_fetch_array($qu); while ($cnp=mysql_fetch_array($qu)){ $date1 = strtotime($cnp1['DataExternare']); $date2 = strtotime($cnp['DataInternare']); $days_diff = round(($date2 - $date1)/(60*60*24)); if ($days_diff<=2){ $cazuri[$i][10]++; } $cnp1=$cnp; } } } } uasort ( $cazuri ,"compare_elso"); $j=0; foreach ($cazuri as $i=>$ertek){ $cazuri[$j++]=$ertek; } return $cazuri; } function compare_masodik($a, $b) { return strnatcmp($a[2],$b[2]); // or other function/code } function insertvirament($data_array) { $query = "INSERT INTO `drg_virament` (`id`, `ondate`, `drg`, `cmd`, `mc`, `denumire`, `vr`, `dms`, `inf`, `sup`) VALUES ( NULL, NOW(), '$data_array[1]', '$data_array[2]', '$data_array[3]', '$data_array[5]', '$data_array[6]', '$data_array[7]', '$data_array[8]', '$data_array[9]' )"; $result = mysql_query($query) or die("insertFirstDataFromReportFile ".mysql_error()); } function insertexceptii($data_array) { if ($data_array[7]=='3' || $data_array[7]=='4'){ $kod=explode("-",$data_array[5]); $query = "INSERT INTO `Lista_exceptii_diagnostice` (`id`,`cod_DI`,`DenDI`,`IdClasaDiagnostic`,`IdSubClasaDiagnostic`,`cod_DP1`,`Denumire_DP1`,`IdTip`) VALUES ( NULL, '$data_array[1]', '$data_array[2]', '$data_array[3]', '$data_array[4]', '$kod[0]', '$data_array[6]','$data_array[7]' )"; mysql_query( $query ) or die(mysql_error()); $query = "INSERT INTO `Lista_exceptii_diagnostice` (`id`,`cod_DI`,`DenDI`,`IdClasaDiagnostic`,`IdSubClasaDiagnostic`,`cod_DP1`,`Denumire_DP1`,`IdTip`) VALUES ( NULL, '$data_array[1]', '$data_array[2]', '$data_array[3]', '$data_array[4]', '$kod[1]', '$data_array[6]','$data_array[7]' )"; mysql_query( $query ) or die(mysql_error()); }else{ $query = "INSERT INTO `Lista_exceptii_diagnostice` (`id`,`cod_DI`,`DenDI`,`IdClasaDiagnostic`,`IdSubClasaDiagnostic`,`cod_DP1`,`Denumire_DP1`,`IdTip`) VALUES ( NULL, '$data_array[1]', '$data_array[2]', '$data_array[3]', '$data_array[4]', '$data_array[5]', '$data_array[6]','$data_array[7]' )"; $result = mysql_query($query) or die("insertFirstDataFromReportFile ".mysql_error()); } } function insertinterventii($data_array) { $q="SELECT * FROM `code_convert` WHERE `regi`='".$data_array[1]."'"; $talal=mysql_fetch_array(mysql_query($q)); if (count($talal)>0){ $update="UPDATE `Lista_Proceduri` set `tip`='C' where `cod`='".$talal['uj']."'"; mysql_query($update) or die(mysql_error()); } } //nem validalt esetek function masodikRiport($partnerid,$id,$tcp){ $partner=partners_getPartner($partnerid); $query="SELECT * from `reportFileFirstData` where `workid` in $id and `RegulaIncalcata`!=''"; $result = mysql_query($query) or die ("elsoReport ".mysql_error()); $cazuri=array();$i=0; while ($row=mysql_fetch_array($result)){ $cazuri[$i][0]=$row['CazID']; $cazuri[$i][1]=$row['NrSectieInternare']; $se="SELECT `name` from `Lista_Sectii` where `id`='".$row['CodSectieInternare']."'"; $sectienume=mysql_fetch_array(mysql_query($se)); $cazuri[$i][2]=$sectienume[0]; $cazuri[$i][3]=$row['CodMedicCurant']; $cazuri[$i][4]=$row['NFO']; $cazuri[$i][5]=$row['DataExternare']; $cazuri[$i][6]=$row['CodDRG']; $date1 = strtotime($row['DataExternare']); $date2 = strtotime($row['DataInternare']); $days_diff =1+ round(($date1 - $date2)/(60*60*24)); $drg="SELECT * from `drg_virament` where `drg`='".$row['CodDRG']."'"; $vira=mysql_fetch_array(mysql_query($drg)); $inf=$vira['inf']; $sup=$vira['sup']; if ($inf!='-' && $sup!='-'){ if ($days_diff>=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $cazuri[$i][7]=$vira['vr']*$k; $cazuri[$i][8]=$row['RegulaIncalcata']; $i++; } uasort ( $cazuri ,"compare_masodik"); $j=0; foreach ($cazuri as $i=>$ertek){ $cazuri[$j++]=$ertek; } return $cazuri; } function compare_harmadik($a, $b) { return strnatcmp($a[2],$b[2]); // or other function/code } //rovid es hosszu esetek function harmadikRiport($partnerid,$id,$tcp){ $partner=partners_getPartner($partnerid); $query="SELECT * from `reportFileFirstData` where `workid` in $id "; $result = mysql_query($query) or die ("elsoReport ".mysql_error()); $cazuri=array();$i=0; while ($row=mysql_fetch_array($result)){ $date1 = strtotime($row['DataExternare']); $date2 = strtotime($row['DataInternare']); $days_diff =1+ round(($date1 - $date2)/(60*60*24)); $drg="SELECT * from `drg_virament` where `drg`='".$row['CodDRG']."'"; $vira=mysql_fetch_array(mysql_query($drg)); $inf=$vira['inf']; $sup=$vira['sup']; if ($inf!='-' && $sup!='-') if ($days_diff<$inf || $days_diff>$sup){ if ($days_diff<$inf){ $k=$days_diff/$inf; $cazuri[$i][9]='scurt'; } if ($days_diff>$sup){ $k=$days_diff/$sup; $cazuri[$i][9]='lung'; } $cazuri[$i][0]=$row['CazID']; $cazuri[$i][1]=$row['NrSectieInternare']; $se="SELECT `name` from `Lista_Sectii` where `id`='".$row['CodSectieInternare']."'"; $sectienume=mysql_fetch_array(mysql_query($se)); $cazuri[$i][2]=$sectienume[0]; $cazuri[$i][3]=$row['CodMedicCurant']; $cazuri[$i][4]=$row['NFO']; $cazuri[$i][5]=$row['DataExternare']; $cazuri[$i][6]=$row['CodDRG']; $cazuri[$i][7]=$vira['vr']*$k; $tip="SELECT `name` FROM `Lista_TipExternare` WHERE `id`='".$row['IdTipExternare']."'"; $t=mysql_fetch_array(mysql_query($tip)); $cazuri[$i][8]=$t['name']; $i++; } } uasort ( $cazuri ,"compare_harmadik"); $j=0; foreach ($cazuri as $i=>$ertek){ $cazuri[$j++]=$ertek; } return $cazuri; } function compare_negyedik($a, $b) { return strnatcmp($a[2],$b[2]); // or other function/code } //elhunyt es athelyezett esetek function negyedikRiport($partnerid,$id,$tcp){ $partner=partners_getPartner($partnerid); $query="SELECT * from `reportFileFirstData` where `workid` in $id"; $result = mysql_query($query) or die ("elsoReport ".mysql_error()); $cazuri=array();$i=0; while ($row=mysql_fetch_array($result)){ $tip="SELECT `id`,`name` FROM `Lista_TipExternare` WHERE `id`='".$row['IdTipExternare']."'"; $t=mysql_fetch_array(mysql_query($tip)); if ($t['id']=='3' || $t['id']=='4'){ $cazuri[$i][8]=$t['name']; $cazuri[$i]['tip']=$t['id']; $cazuri[$i][0]=$row['CazID']; $cazuri[$i][1]=$row['NrSectieInternare']; $se="SELECT `name` from `Lista_Sectii` where `id`='".$row['CodSectieInternare']."'"; $sectienume=mysql_fetch_array(mysql_query($se)); $cazuri[$i][2]=$sectienume[0]; $cazuri[$i][3]=$row['CodMedicCurant']; $cazuri[$i][4]=$row['NFO']; $cazuri[$i][5]=$row['DataExternare']; $cazuri[$i][6]=$row['CodDRG']; $date1 = strtotime($row['DataExternare']); $date2 = strtotime($row['DataInternare']); $days_diff =1+ round(($date1 - $date2)/(60*60*24)); $drg="SELECT * from `drg_virament` where `drg`='".$row['CodDRG']."'"; $vira=mysql_fetch_array(mysql_query($drg)); $inf=$vira['inf']; $sup=$vira['sup']; if ($inf!='-' && $sup!='-'){ if ($days_diff>=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $cazuri[$i][7]=$vira['vr']*$k; $i++; } } uasort ( $cazuri ,"compare_negyedik"); $j=0; foreach ($cazuri as $i=>$ertek){ $cazuri[$j++]=$ertek; } return $cazuri; } function compare_otodik($a, $b) { return strnatcmp($a[2],$b[2]); // or other function/code } //elhunyt es athelyezett esetek function otodikRiport($partnerid,$id,$tcp){ $partner=partners_getPartner($partnerid); $query="SELECT * from `reportFileFirstData` where `workid` in $id"; $result = mysql_query($query) or die ("elsoReport ".mysql_error()); $cazuri=array();$i=0; while ($row=mysql_fetch_array($result)){ if ($row['IdLocalitate']!='0'){//ha megvan adva a helyseg kodja $helyseg="SELECT * FROM `siruta_fara_diacritice` WHERE `SIRUTA`='".$row['IdLocalitate']."'"; $loc=mysql_fetch_array(mysql_query($helyseg)); $jud="SELECt * FROM `siruta_fara_diacritice` WHERE `JUD`='".$loc['JUD']."' AND `NIV`='1'"; $megye=mysql_fetch_array(mysql_query($jud)); $megy=strtolower(substr($megye['DENLOC'],8)); }else{ $megy=strtolower($partner['state']); } if ($megy!=strtolower($partner['state'])){ $cazuri[$i][8]=$t['name']; $cazuri[$i]['tip']=$t['id']; $cazuri[$i][0]=$row['CazID']; $cazuri[$i][1]=$row['NrSectieInternare']; $se="SELECT `name` from `Lista_Sectii` where `id`='".$row['CodSectieInternare']."'"; $sectienume=mysql_fetch_array(mysql_query($se)); $cazuri[$i][2]=$sectienume[0]; $cazuri[$i][3]=$row['CodMedicCurant']; $cazuri[$i][4]=$row['NFO']; $cazuri[$i][5]=$row['DataExternare']; $cazuri[$i][6]=$row['CodDRG']; $date1 = strtotime($row['DataExternare']); $date2 = strtotime($row['DataInternare']); $days_diff =1+ round(($date1 - $date2)/(60*60*24)); $drg="SELECT * from `drg_virament` where `drg`='".$row['CodDRG']."'"; $vira=mysql_fetch_array(mysql_query($drg)); $inf=$vira['inf']; $sup=$vira['sup']; if ($inf!='-' && $sup!='-'){ if ($days_diff>=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $cazuri[$i][7]=$vira['vr']*$k; $cazuri[$i][8]=$vira['vr']*$k*$tcp; $i++; } } uasort ( $cazuri ,"compare_otodik"); $j=0; foreach ($cazuri as $i=>$ertek){ $cazuri[$j++]=$ertek; } return $cazuri; } function compare_hatodik($a, $b) { return strnatcmp($a[2],$b[2]); // or other function/code } //48 oran beluli visszafektetesek function hatodikRiport($partnerid,$id,$tcp){ $partner=partners_getPartner($partnerid); $query="SELECT `CNP` from `reportFileFirstData` where `workid` in $id and `CNP`!='0' AND `CNP`!='' group by `CNP`"; $result = mysql_query($query) or die ("elsoReport ".mysql_error()); $lista=array(); while ($row=$row=mysql_fetch_array($result)){ $lista[]=$row; } $cazuri=array();$j=0; for ($i=0;$i1){ $cnp1=mysql_fetch_array($qu); while ($cnp=mysql_fetch_array($qu)){ $date1 = strtotime($cnp1['DataExternare']); $date2 = strtotime($cnp['DataInternare']); $days_diff = round(($date2 - $date1)/(60*60*24)); if ($days_diff<=2){ $cazuri[$j][0]=$cnp1['CazID']."
".$cnp['CazID']; $cazuri[$j][1]=$cnp1['NrSectieInternare']."
".$cnp['NrSectieInternare']; $se="SELECT `name` from `Lista_Sectii` where `id`='".$cnp1['CodSectieInternare']."'"; $sectienume=mysql_fetch_array(mysql_query($se)); $se="SELECT `name` from `Lista_Sectii` where `id`='".$cnp['CodSectieInternare']."'"; $sectienume2=mysql_fetch_array(mysql_query($se)); $cazuri[$j][2]=$sectienume[0]."
".$sectienume2[0]; $cazuri[$j][3]=$cnp1['CodMedicCurant']."
".$cnp['CodMedicCurant']; $cazuri[$j][4]=$cnp1['NFO']."
".$cnp['NFO']; $cazuri[$j][5]=$cnp1['DataInternare']."
".$cnp['DataInternare']; $cazuri[$j][6]=$cnp1['DataExternare']."
".$cnp['DataExternare']; $cazuri[$j][7]=$cnp1['CodDRG']."
".$cnp['CodDRG']; $drg="SELECT * from `drg_virament` where `drg`='".$cnp1['CodDRG']."'"; $vira=mysql_fetch_array(mysql_query($drg)); $inf=$vira['inf']; $sup=$vira['sup']; if ($inf!='-' && $sup!='-'){ if ($days_diff>=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $v=$vira['vr']*$k; $drg="SELECT * from `drg_virament` where `drg`='".$cnp['CodDRG']."'"; $vira=mysql_fetch_array(mysql_query($drg)); $inf=$vira['inf']; $sup=$vira['sup']; if ($inf!='-' && $sup!='-'){ if ($days_diff>=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $cazuri[$j][8]=$v."
".$vira['vr']*$k; $cazuri[$j][9]="
".$days_diff; $j++; } $cnp1=$cnp; } } } uasort ( $cazuri ,"compare_hatodik"); $j=0; foreach ($cazuri as $i=>$ertek){ $cazuri[$j++]=$ertek; } return $cazuri; } //30 leggyakoribb fodiagnozis function hetedikRiport($partnerid,$id,$tcp){ //osszes eset lekerdezese $ossz="SELECT `CodDP1` from `reportFileFirstData` where `workid` in $id"; $result=mysql_query($ossz); $osszeseset=mysql_affected_rows(); $query="SELECT `CodDP1`,count(*) as `drb` from `reportFileFirstData` where `workid` in $id group by `CodDP1` order by count(*) desc limit 30"; $result = mysql_query($query) or die ("elsoReport ".mysql_error()); $cazuri=array();$i=0; $lista=array(); while ($row=mysql_fetch_array($result)){ $cazuri[$i][0]=$row[0]; $denum="SELECT * FROM `Lista_Diagnostice` where `codDiagnostic`='".$row['CodDP1']."'"; $d=mysql_fetch_array(mysql_query($denum)); $cazuri[$i][1]=$d['name']; $cazuri[$i][2]=$row['drb']; $cazuri[$i][3]=round(($row['drb']*100)/$osszeseset,2); $prop=0; for ($k=0;$k<=$i;$k++) $prop+=$cazuri[$k][2]; $cazuri[$i][4]=round(($prop*100)/$osszeseset,2); $i++; } return $cazuri; } //20 leggyakoribb drg csoport function nyolcadikRiport($partnerid,$id,$tcp){ //osszes eset lekerdezese $ossz="SELECT * from `reportFileFirstData` where `workid` in $id"; $result=mysql_query($ossz); $osszeseset=mysql_affected_rows(); $query="SELECT `CodDRG`,count(*) as `drb` from `reportFileFirstData` where `workid` in $id group by `CodDRG` order by count(*) desc limit 20"; $result = mysql_query($query) or die ("elsoReport ".mysql_error()); $cazuri=array();$i=0; $lista=array(); while ($row=mysql_fetch_array($result)){ $cazuri[$i][0]=$row['CodDRG']; $denum="SELECT * FROM `Lista_CoduriDRG` where `codDrg`='".$row['CodDRG']."'"; $d=mysql_fetch_array(mysql_query($denum)); if (mysql_affected_rows<1){ $dd="SELECT `r`.`name` FROM `Lista_CoduriDRG` as `r`, `drgcode_convert` as `u` WHERE `u`.`newcode`='".$row['CodDRG']."' AND `u`.`oldcode`=`r`.`codDrg`"; $d=mysql_fetch_array(mysql_query($dd)); } $cazuri[$i][1]=$d['name']; $cazuri[$i][2]=0; $cazuri[$i][3]=$row['drb']; $cazuri[$i][4]=round(($row['drb']*100)/$osszeseset,2); $prop=0; for ($k=0;$k<=$i;$k++) $prop+=$cazuri[$k][3]; $cazuri[$i][5]=round(($prop*100)/$osszeseset,2); $vr="SELECT `DataExternare`, `DataInternare` FROM `reportFileFirstData` WHERE `CodDRG`='".$row['CodDRG']."'"; $qq=mysql_query($vr); while ($r=mysql_fetch_array($qq)){ $date1 = strtotime($r['DataExternare']); $date2 = strtotime($r['DataInternare']); $days_diff =1+ round(($date1 - $date2)/(60*60*24)); $drg="SELECT * from `drg_virament` where `drg`='".$row['CodDRG']."'"; $vira=mysql_fetch_array(mysql_query($drg)); $inf=$vira['inf']; $sup=$vira['sup']; if ($inf!='-' && $sup!='-'){ if ($days_diff>=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $cazuri[$i][2]+=$vira['vr']*$k; } $cazuri[$i][6]=round($cazuri[$i][3]*$cazuri[$i][2],2); $i++; } return $cazuri; } function cmp_kilenc($a, $b) { if ($a[2] == $b[2]) { return 0; } return ($a[2] > $b[2]) ? -1 : 1; } //20 legnagyobb vr erteku drg csoport function kilencedikRiport($partnerid,$id,$tcp){ $ossz="SELECT * from `reportFileFirstData` where `workid` in $id "; $result=mysql_query($ossz); $osszeseset=mysql_affected_rows(); $ossz="SELECT * from `reportFileFirstData` where `workid` in $id group by `CodDRG`"; $result=mysql_query($ossz); $cazuri=array();$i=0; $lista=array(); while ($row=mysql_fetch_array($result)){ $cazuri[$i][0]=$row['CodDRG']; $denum="SELECT * FROM `Lista_CoduriDRG` where `codDrg`='".$row['CodDRG']."'"; $d=mysql_fetch_array(mysql_query($denum)); if (mysql_affected_rows<1){ $dd="SELECT `r`.`name` FROM `Lista_CoduriDRG` as `r`, `drgcode_convert` as `u` WHERE `u`.`newcode`='".$row['CodDRG']."' AND `u`.`oldcode`=`r`.`codDrg`"; $d=mysql_fetch_array(mysql_query($dd)); } $cazuri[$i][1]=$d['name']; $cazuri[$i][2]=0; $cazuri[$i][3]=0; $vr="SELECT `DataExternare`, `DataInternare` FROM `reportFileFirstData` WHERE `CodDRG`='".$row['CodDRG']."'"; $qq=mysql_query($vr); while ($r=mysql_fetch_array($qq)){ $date1 = strtotime($r['DataExternare']); $date2 = strtotime($r['DataInternare']); $days_diff =1+ round(($date1 - $date2)/(60*60*24)); $drg="SELECT * from `drg_virament` where `drg`='".$row['CodDRG']."'"; $vira=mysql_fetch_array(mysql_query($drg)); $inf=$vira['inf']; $sup=$vira['sup']; if ($inf!='-' && $sup!='-'){ if ($days_diff>=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $cazuri[$i][2]+=$vira['vr']*$k; $cazuri[$i][3]++; } $cazuri[$i][4]=round(($cazuri[$i][3]*100)/$osszeseset,2); $cazuri[$i][6]=round($cazuri[$i][2]*$cazuri[$i][3],2); $i++; } uasort($cazuri,'cmp_kilenc'); $j=0; $caz=array(); foreach ($cazuri as $i => $ertek){ $caz[$j]=$ertek; $prop=0; for ($p=0;$p<=$j;$p++){ $prop+=$caz[$p][3]; } $caz[$j][5]=round(($prop*100)/$osszeseset,2); $j++; if ($j==20) break; } return $caz; } function cmp_tiz($a, $b) { if ($a['darab'] == $b['darab']) { return 0; } return ($a['darab'] > $b['darab']) ? -1 : 1; } //30 leggyakoribb procedura function tizedikRiport($partnerid,$id,$tcp){ $kodok=array(); $darab=array(); $iterator=array(); $i=0; $elso="SELECT * from `reportFileFirstData` where `workid` in $id "; $e=mysql_query($elso) or die(mysql_error()); $osszeseset=mysql_affected_rows(); while ($x=mysql_fetch_array($e)){ if ($x['CodICP']!=''){ if (!in_array($x['CodICP'],$kodok)){ $kodok[$i]=$x['CodICP']; $darab[$i]['darab']++; $darab[$i]['kod']=$x['CodICP']; $i++; }else{ $darab[array_search($x['CodICP'],$kodok)]['darab']++; } } $harmadik="SELECT * from `reportFileThirdDataProceduri` where `CazID`='".$x['CazID']."'"; $h=mysql_query($harmadik); while ($y=mysql_fetch_array($h)){ if (!in_array($y['CodProcedura'],$kodok)){ $kodok[$i]=$y['CodProcedura']; $darab[$i]['darab']++; $darab[$i]['kod']=$y['CodProcedura']; $i++; }else{ $darab[array_search($y['CodProcedura'],$kodok)]['darab']++; } } } uasort($darab,'cmp_tiz'); $cazuri=array();$j=0; foreach ($darab as $i=>$ertek){ $cazuri[$j][0]=$ertek['kod']; $n="SELECT `name` FROM `Lista_Proceduri` where `cod`='".$ertek['kod']."'"; $nev=mysql_fetch_array(mysql_query($n)); $cazuri[$j][1]=$nev['name']; $cazuri[$j][2]=$ertek['darab']; $cazuri[$j][3]=round(($ertek['darab']*100)/$osszeseset,2); $prop=0; for ($k=0;$k<=$j;$k++) $prop+=$cazuri[$k][2]; $cazuri[$j][4]=round(($prop*100)/$osszeseset,2); $j++; if ($j==20) break; } return $cazuri; } function tizenegyedikRiport($partnerid,$id,$tcp){ $osztalyok="SELECT `CodSectieInternare`, `NrSectieInternare`,`DataExternare`,`DataInternare` from `reportFileFirstData` where `workid` in $id group by `CodSectieInternare`"; $result=mysql_query($osztalyok); $lista=array();$i=0; while ($e=mysql_fetch_array($result)){ $lista[$i++]=$e; } $cazuri=array(); $o=0; $cazuri[0]['atlag']=0; $cazuri[0]['diag'][0][0]='0'; $cazuri[0]['diag'][1][0]='1'; $cazuri[0]['diag'][2][0]='2'; $cazuri[0]['diag'][3][0]='3'; $cazuri[0]['diag'][4][0]='4'; $cazuri[0]['diag'][5][0]='5'; $cazuri[0]['diag'][6][0]='6'; $cazuri[0]['diag'][7][0]='7'; $cazuri[0]['diag'][8][0]='8'; $cazuri[0]['diag'][9][0]='0'; $cazuri[0]['diag'][10][0]='10'; $cazuri[0]['diag'][11][0]='11-12'; $cazuri[0]['diag'][12][0]='13-14'; $cazuri[0]['diag'][13][0]='15-16'; $cazuri[0]['diag'][14][0]='17-18'; $cazuri[0]['diag'][15][0]='19-20'; $cazuri[0]['diag'][16][0]='21-25'; $cazuri[0]['diag'][17][0]='26-30'; $cazuri[0]['diag'][18][0]='31-40'; $cazuri[0]['diag'][19][0]='41-50'; $cazuri[0]['diag'][20][0]='51-100'; $cazuri[0]['diag'][21][0]='>100'; for ($s=0;$s=11 && $days_diff<=12) $cazuri[$j]['diag'][10][3]++; else if ($days_diff>=13 && $days_diff<=14) $cazuri[$j]['diag'][11][3]++; else if ($days_diff>=15 && $days_diff<=16) $cazuri[$j]['diag'][12][3]++; else if ($days_diff>=17 && $days_diff<=18) $cazuri[$j]['diag'][13][3]++; else if ($days_diff>=19 && $days_diff<=20) $cazuri[$j]['diag'][14][3]++; else if ($days_diff>=21 && $days_diff<=25) $cazuri[$j]['diag'][15][3]++; else if ($days_diff>=26 && $days_diff<=30) $cazuri[$j]['diag'][16][3]++; else if ($days_diff>=31 && $days_diff<=40) $cazuri[$j]['diag'][17][3]++; else if ($days_diff>=41 && $days_diff<=50) $cazuri[$j]['diag'][18][3]++; else if ($days_diff>=51 && $days_diff<=100) $cazuri[$j]['diag'][19][3]++; else if ($days_diff>100) $cazuri[$j]['diag'][20][3]++; } for ($h=0;$h<=21;$h++){ $cazuri[$j]['diag'][$h][1]=$lista[$s]['NrSectieInternare']; $cazuri[$j]['diag'][$h][2]=$sectienume[0]; $cazuri[$j]['diag'][$h][4]=round(($cazuri[$j]['diag'][$h][3]*100)/$osszeseset,2); $prop=0; for ($d=0;$d<=$h;$d++){ $prop+=$cazuri[$j]['diag'][$d][3]; } $cazuri[$j]['diag'][$h][5]=round(($prop*100)/$osszeseset,2); $cazuri[0]['diag'][$h][1]=''; $cazuri[0]['diag'][$h][2]='Total'; $cazuri[0]['diag'][$h][3]+=$cazuri[$j]['diag'][$h][3]; } $cazuri[$j]['diag'][22][0]='Medie'; $cazuri[$j]['diag'][22][1]=$lista[$s]['NrSectieInternare']; $cazuri[$j]['diag'][22][2]=$sectienume[0]; $cazuri[$j]['diag'][22][3]=round($cazuri[$j]['atlag']/$osszeseset,2)." zile"; $cazuri[0]['diag'][22][0]='Medie'; $cazuri[0]['diag'][22][1]=''; $cazuri[0]['diag'][22][2]='Total'; $cazuri[0]['diag'][22][3]+=$cazuri[$j]['atlag']; } $cazuri[0]['sectie']='Total'; for ($h=0;$h<=21;$h++){ $cazuri[0]['diag'][$h][4]=round(($cazuri[0]['diag'][$h][3]*100)/$o,2); $prop=0; for ($d=0;$d<=$h;$d++){ $prop+=$cazuri[0]['diag'][$d][3]; } $cazuri[0]['diag'][$h][5]=round(($prop*100)/$o,2); } $cazuri[0]['diag'][22][3]=round($cazuri[0]['diag'][22][3]/$o,2)." zile"; return $cazuri; } //15 leggyakoribb fodiagnozis osztalyokra function tizenkettedikRiport($partnerid,$id,$tcp){ $osztalyok="SELECT `CodSectieInternare`, `NrSectieInternare` from `reportFileFirstData` where `workid` in $id group by `CodSectieInternare`"; $result=mysql_query($osztalyok); $lista=array();$i=0; while ($e=mysql_fetch_array($result)){ $lista[$i++]=$e; } $cazuri=array(); for ($j=0;$j=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $cazuri[$j]['diag'][$i][4]+=$vira['vr']*$k; } $cazuri[$j]['diag'][$i][8]=round($cazuri[$j]['diag'][$i][4]*$cazuri[$j]['diag'][$i][5],2); $i++; } } return $cazuri; } function cmp_tizennegyedik($a, $b) { if ($a[4] == $b[4]) { return 0; } return ($a[4] > $b[4]) ? -1 : 1; } //10 leggyakoribb DRG csoport max VR osztalyokra function tizennegyedikRiport($partnerid,$id,$tcp){ $osztalyok="SELECT `CodSectieInternare`, `NrSectieInternare` from `reportFileFirstData` where `workid` in $id group by `CodSectieInternare`"; $result=mysql_query($osztalyok); $lista=array();$i=0; while ($e=mysql_fetch_array($result)){ $lista[$i++]=$e; } $cazuri=array(); for ($j=0;$j=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $cazuri[$j]['diag'][$i][4]+=$vira['vr']*$k; $cazuri[$j]['diag'][$i][5]++; } $cazuri[$j]['diag'][$i][6]=round(($cazuri[$j]['diag'][$i][5]*100)/$osszeseset,2); $prop=0; for ($q=0;$q<=$i;$q++){ $prop+=$cazuri[$j]['diag'][$q][5]; } $cazuri[$j]['diag'][$i][7]=round(($prop*100)/$osszeseset,2); $cazuri[$j]['diag'][$i][8]=round($cazuri[$j]['diag'][$i][4]*$cazuri[$j]['diag'][$i][5],2); $i++; } uasort($cazuri[$j]['diag'],'cmp_tizennegyedik'); $m=0;$caz=array(); foreach ($cazuri[$j]['diag'] as $i => $ertek){ $caz[$m++]=$ertek; if ($m==10) break; } for ($m=0;$m $b['darab']) ? -1 : 1; } //15 leggyakoribb procedura osztalyokra function tizenotodikRiport($partnerid,$id,$tcp){ $osztalyok="SELECT `CodSectieInternare`, `NrSectieInternare` from `reportFileFirstData` where `workid` in $id group by `CodSectieInternare`"; $result=mysql_query($osztalyok); $lista=array();$i=0; while ($e=mysql_fetch_array($result)){ $lista[$i++]=$e; } $cazuri=array(); for ($j=0;$j$ertek){ $c[$b][0]=$lista[$j]['NrSectieInternare']; $c[$b][1]=$sectienume[0]; $c[$b][2]=$ertek['kod']; $n="SELECT `name` FROM `Lista_Proceduri` where `cod`='".$ertek['kod']."'"; $nev=mysql_fetch_array(mysql_query($n)); $c[$b][3]=$nev['name']; $c[$b][4]=$ertek['darab']; $c[$b][5]=round(($ertek['darab']*100)/$osszeseset,2); $prop=0; for ($k=0;$k<=$b;$k++) $prop+=$c[$k][4]; $c[$b][6]=round(($prop*100)/$osszeseset,2); $b++; if ($b==15) break; } $cazuri[$j]['diag']=$c; } return $cazuri; } function cmp_tizenhat($a, $b) { if ($a['darab'] == $b['darab']) { return 0; } return ($a['darab'] > $b['darab']) ? -1 : 1; } //15 leggyakoribb procedura osztalyokra function tizenhatodikRiport($partnerid,$id,$tcp){ $chirurgext=0; $sexternare="SELECT `ls`.`tip` FROM `Lista_Sectii` as `ls`, `reportFileFirstData` as `rf` WHERE `ls`.`id`=`rf`.`CodSectieExternare` "; $extquery=mysql_query($sexternare) or die ("ext".mysql_error()); while($stip=mysql_fetch_array($extquery)) if ($stip['tip']=='C') $chirurgext++; $orvosok="SELECT `CodMedicCurant`,`CodSectieInternare`,`NrSectieInternare` from `reportFileFirstData` where `workid` in $id group by `CodMedicCurant`"; $result=mysql_query($orvosok); $lista=array();$i=0; while ($e=mysql_fetch_array($result)){ $lista[$i++]=$e; } $cazuri=array(); $venit=0; for ($j=0;$j=$inf && $days_diff<=$sup)//normal eset $k=1; else{ if ($days_diff<$inf) $k=$days_diff/$inf; if ($days_diff>$sup) $k=$days_diff/$sup; } }else $k=1; $coefk+=$k; $cazuri[$j][7]+=$vira['vr']*$k*$tcp; $icm+=$vira['vr']*$k; if ($x['IdTipExternare']=='4')//meghalt $deces++; if ($x['IdTipExternare']=='3')//transfer $trans++; //indice de operabilitate $proci="SELECT `tip` FROM `Lista_Proceduri` where `cod`='".$x['CodICP']."'"; $tipus=mysql_fetch_array(mysql_query($proci)); if ($tipus['tip']=='C'){ $chirurgi++; }else{ $tobbiproci="SELECT `lp`.`tip` FROM `reportFileThirdDataProceduri` as `rt`, `Lista_Proceduri` as `lp` WHERE `CazID`='".$x['CazID']."' AND `rt`.`CodProcedura`=`lp`.`cod`"; $tq=mysql_query($tobbiproci); while ($top=mysql_fetch_array($tq)){ if ($top['tip']=='C'){ $chirurgi++; break; } } } //concordanta di/de if (substr($e2['CodDI'],0,3)==substr($e2['CodDP1'],0,3)) $di++; else{ $kettesnegyes="SELECT * FROM `Lista_exceptii_diagnostice` WHERE `cod_DI`='".$e2['CodDI']."' AND `cod_DP1`='".substr($e2['CodDP1'],0,3)."'"; $qkettes=mysql_query($kettesnegyes); if (mysql_affected_rows()>0) $di++; else{ $egyesharmas="SELECT * FROM `Lista_exceptii_diagnostice` WHERE `cod_DI`='".$e2['CodDI']."' AND `cod_DP1`='".$e2['CodDP1']."'"; $qharmas=mysql_query($egyesharmas); if (mysql_affected_rows()>0) $di++; } } //megye meghatarozasa if ($x['IdLocalitate']!='0'){//ha megvan adva a helyseg kodja $helyseg="SELECT * FROM `siruta_fara_diacritice` WHERE `SIRUTA`='".$x['IdLocalitate']."'"; $loc=mysql_fetch_array(mysql_query($helyseg)); $jud="SELECt * FROM `siruta_fara_diacritice` WHERE `JUD`='".$loc['JUD']."' AND `NIV`='1'"; $megye=mysql_fetch_array(mysql_query($jud)); $megy=strtolower(substr($megye['DENLOC'],8)); if ($megy!=strtolower($partner['state'])) $cazuri[$j][11]++; } } $cazuri[$j][12]=0; $osszescnp="SELECT * FROM `reportFileFirstData` where `workid` in $id and `CodMedicCurant`='".$lista[$j]['CodMedicCurant']."' group by `CNP`"; $cnpquery=mysql_query($osszescnp); while ($z=mysql_fetch_array($cnpquery)) if ($z['CNP']!='0' && $z['CNP']!=''){ $duplak="SELECT * FROM `reportFileFirstData` where `workid` in $id AND `CodMedicCurant`='".$lista[$j]['CodMedicCurant']."' and `CNP`='".$z['CNP']."' order by `DataInternare` asc"; $qu=mysql_query($duplak) or die(mysql_error()); if (mysql_affected_rows()>1){ $cnp1=mysql_fetch_array($qu); while ($cnp=mysql_fetch_array($qu)){ $date1 = strtotime($cnp1['DataExternare']); $date2 = strtotime($cnp['DataInternare']); $days_diff = round(($date2 - $date1)/(60*60*24)); if ($days_diff<=2){ $cazuri[$j][12]++; } $cnp1=$cnp; } } } $venit+=$cazuri[$j][7]; $cazuri[$j][3]=($osszeseset-$nevalidate)." / ".$nevalidate; $cazuri[$j][4]=round(($osszeseset*100)/$osszkor,2); $cazuri[$j][5]=round($icm/$osszeseset,2); $cazuri[$j][6]=round($coefk/$osszeseset,2); $cazuri[$j][7]=round($cazuri[$j][7],2); $cazuri[$j][9]=round($days/$osszeseset,2); $cazuri[$j][10]=$deces." / ".$trans; $cazuri[$j][13]=round(($di*100)/ $osszkor,2); $cazuri[$j][14]=round(($chirurgi*100)/$chirurgext,2); } for ($i=0;$i0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function getActualCommandsForProdus($entryid,$viewall,$userid) { if($viewall!="1") { $viewquery= " AND ( `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR `userid`='$userid') "; } $query="SELECT * FROM `comandaForClientAdv` WHERE `id` IN(SELECT `comandaid` FROM `comandaForClientAdvItems` WHERE `sellType`='inchiriere' AND `prodid`='$entryid') AND `firstserial`='0' $viewquery ORDER BY `ondate` DESC"; $result=mysql_query($query) or die($query.mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function getPriceForComandaItem($entryid,$comandaid) { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$comandaid' AND `prodid`='$entryid'"; $result=mysql_query($query) or die($query.mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); if($row["sellType"]=="inchiriere") { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$comandaid' AND sellType='' AND period!='' AND `id`>'".$row["id"]."' AND `endDate`>'".date("Y-m-d")."' ORDER BY `id` LIMIT 1"; $result=mysql_query($query) or die($query.mysql_error()); if($result&&mysql_num_rows($result)>0) { $row=mysql_fetch_array($result); } } return $row; } function commandForClientAdv_getRegisteredItem($entryid,$comandaid) { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `comandaid`='$comandaid' AND `prodid`='$entryid'"; $result=mysql_query($query) or die($query.mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row; } function getActualCommandsForClient($clientid,$viewall,$userid) { if($viewall!="1") { $viewquery= " AND ( `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR `userid`='$userid') "; } $query="SELECT * FROM `comandaForClientAdv` WHERE `clientid`='$clientid' AND `id` IN (SELECT `comandaid` FROM `comandaForClientAdvItems` WHERE `sellType`!='necesar' AND `endDate`>'".date("Y-m-d")."' AND `endDate`!='0000-00-00') AND `firstserial`='0' $viewquery ORDER BY `ondate` DESC"; $result=mysql_query($query) or die($query.mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function getAllCommandsForClient($clientid,$viewall,$userid) { if($viewall!="1") { $viewquery= " AND ( `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) OR `userid`='$userid') "; } $query="SELECT * FROM `comandaForClientAdv` WHERE `clientid`='$clientid' AND `id` IN (SELECT `comandaid` FROM `comandaForClientAdvItems` WHERE `sellType`!='necesar' AND `endDate`<'".date("Y-m-d")."' ) AND `firstserial`='0' $viewquery ORDER BY `ondate` DESC"; $result=mysql_query($query) or die($query.mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function getAllCsVals($viewall,$userid) { if($viewall!="1") { $viewquery= " WHERE ( `departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) ) "; } $query="SELECT * FROM `models_cs` WHERE `id` IN ( SELECT CONCAT_WS(',',`cs1`,`cs2`,`cs3`,`cs4`,`cs5`,`cs6`,`cs7`,`cs8`,`cs9`,`cs10`,`cs11`,`cs12`,`cs13`,`cs14`,`cs15`,`cs16`,`cs17`,`cs18`,`cs20`) FROM `models` $viewquery ) "; $result=mysql_query($query) or die($query.mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $all[$row["id"]]=$row; } return $all; } function entry_searchGenerateQueryAvansat($keyword , $type , $stockid , $page , $order , $ordermode, $id, $modelsid, $like,$viewall,$userid,$filtername,$filterprice,$filtercname,$filteredate,$filtercsarr,$activefilter) { if( !isset( $page ) ||$page=="0"||$page=="")$page = 1; $from = ($page - 1 ) * $_SESSION["settings"]["searchcount"]; $howmany = $_SESSION["settings"]["searchcount"]; if ($like==0) { $l=" LIKE '$keyword%'"; } else { $l=" LIKE '%$keyword%'"; } if($viewall!="1") { $viewquery= " AND ( m.`departament` IN (SELECT `id` FROM `departamente` WHERE `id`=(SELECT `main_departament` FROM `hr` WHERE `userid`='$userid') OR `id` IN (SELECT `dep_id` FROM `departamente_hr` WHERE `hrid`=(SELECT `id` FROM `hr` WHERE `userid`='$userid'))) ) "; } if($activefilter!="all") { $actquery=" AND `c`.`active`='$activefilter' "; } if( strlen( $keyword ) > 0 ) { if( $type == "code" ) $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( c.code $l)".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery.$actquery." "; elseif($type=="name") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( c.name $l)".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery.$actquery." "; elseif($type=="desc") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( c.desc $l)".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery.$actquery." "; elseif($type=="cname") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( c.`id` IN (SELECT `prodid` FROM `comandaForClientAdvItems` WHERE `sellType`!='' AND `comandaid` IN (SELECT `id` FROM `comandaForClientAdv` WHERE `clientid` IN (SELECT `id` FROM `partners` WHERE `name`$l) ))) ".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery.$actquery." "; elseif($type=="all") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( c.name $l OR c.desc $l OR c.code $l OR c.`cs1`$l OR c.`cs2`$l OR c.`cs3`$l OR c.`cs4`$l OR c.`cs5`$l OR c.`cs6`$l OR c.`cs7`$l OR c.`cs8`$l OR c.`cs9`$l OR c.`cs10`$l OR c.`cs11`$l OR c.`cs12`$l OR c.`cs13`$l OR c.`cs14`$l OR c.`cs15`$l OR c.`cs16`$l OR c.`cs17`$l OR c.`cs18`$l OR c.`cs19`$l OR c.`cs20`$l OR CONVERT(c.`cs1`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs2`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs3`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs4`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs5`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs6`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs7`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs8`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs9`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs10`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs11`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs12`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs13`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs14`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs15`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs16`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs17`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs18`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs19`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs20`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR c.`id` IN (SELECT `prodid` FROM `comandaForClientAdvItems` WHERE `sellType`!='' AND `comandaid` IN (SELECT `id` FROM `comandaForClientAdv` WHERE `clientid` IN (SELECT `id` FROM `partners` WHERE `name`$l) ))) ".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery.$actquery." "; else { $css=getModelCs($type); if($css["type"]=="2") $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( CONVERT(c.`cs1`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs2`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs3`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs4`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs5`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs6`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs7`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs8`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs9`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs10`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs11`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs12`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs13`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs14`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs15`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs16`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs17`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs18`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs19`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) OR CONVERT(c.`cs20`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`$l) )".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery.$actquery." "; else { $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id AND ( REPLACE(REPLACE(c.`cs1`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs2`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs3`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs4`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs5`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs6`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs7`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs8`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs9`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs10`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs11`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs12`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs13`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs14`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs15`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs16`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs17`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs18`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs19`,';',''),' ','')$l OR REPLACE(REPLACE(c.`cs20`,';',''),' ','')$l )".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery.$actquery." "; } } } else $query = "SELECT c.*, m.name as modelname FROM `container` c, `models` m WHERE c.modelid=m.id".($modelsid?" AND c.modelid='$modelsid' ":"").$viewquery.$actquery." "; if($filtername!=""&&$filtername!="all") $query.=" AND c.`name`='$filtername' "; if($filterprice!=""&&$filterprice!="all") $query.=" AND c.`price`='$filterprice' "; if($filtercname!=""&&$filtercname!="all") $query.=" AND c.`id` IN (SELECT `prodid` FROM `comandaForClientAdvItems` WHERE `sellType`!='' AND `comandaid` IN (SELECT `id` FROM `comandaForClientAdv` WHERE `clientid` IN (SELECT `id` FROM `partners` WHERE `name`='$filtercname') )) "; if($filteredate!=""&&$filteredate!="all") $query.=" AND c.`id` IN (SELECT `prodid` FROM `comandaForClientAdvItems` WHERE `sellType`!='' AND `endDate` ='$filteredate' ) "; if(count($filtercsarr)>0) { $model=model_getModel($modelsid); for($i=1;$i<=20;$i++) { if($filtercsarr[$i]!=""&&$filtercsarr[$i]!="all") { $css=getModelCs($model["cs".$i]); if($css["type"]=="2") $query.=" AND CONVERT(c.`cs$i`,SIGNED) IN (SELECT `id` FROM `models_cs_values` WHERE `name`='".$filtercsarr[$i]."') "; else $query.=" AND REPLACE(REPLACE(c.`cs$i`,';',''),' ','')='".$filtercsarr[$i]."'"; } } } if(intval($order)==0&&$order!="cname"&&$order!="edate") $query.=" ORDER BY c.`$order` $ordermode LIMIT $from,$howmany "; else if(intval($order)!=0) $query.=" ORDER BY REPLACE(REPLACE(c.`cs$order`,';',''),' ','') $ordermode LIMIT $from,$howmany "; return $query; } function stock_SearchAvansat( $query ) { $result = mysql_query( $query ) or die(mysql_error()); if( $result == NULL )return $result; while( $row = mysql_fetch_array( $result ) ) $found[ ] = $row; return $found; } function dosar_getLastNumberDosar(){ $query="SELECT `serial` FROM `dosar` ORDER BY `ondate` DESC LIMIT 1"; $result=mysql_query($query) or die ($query." ".mysql_error()); $row=mysql_fetch_array($result); if (mysql_affected_rows()==0) return 1; else return $row['serial']+1; } function dosar_setFinalizat($id,$value){ $query="UPDATE `dosar` SET `finalizat`='$value' WHERE `id`='$id'"; return mysql_query($query) or die (mysql_error()); } function dosar_addDosar($array){ $insert="INSERT INTO `dosar` (`serial`,`active`,`finalizat`,`content`,`userid`,`ondate`,`number_dosar`,`fromActAdvId`,`county`,`city`,`institute`,`observation_public`,`observation_privat`, `clientid`,`tip_client`,`adversar`,`materie_juridica`,`obiect`,`stadiu`,`complet`,`sala`,`sarcina`) VALUES( '".$array['serial']."', '1', '0', '".str_replace("'","\'",$array['content'])."', '".$array['userid']."', NOW(), '".$array['number_dosar']."', '".command_getCommandIdFromNr($array['fromActAdvId'])."', '".$array['county']."', '".$array['city']."', '".$array['institute']."', '".$array['observation_public']."', '".$array['observation_privat']."', '".$array['clientid']."', '".$array['tip_client']."', '".$array['adversar']."', '".$array['materie_juridica']."', '".$array['obiect']."', '".$array['stadiu']."', '".$array['complet']."', '".$array['sala']."', '".$array['sarcina']."')"; mysql_query($insert) or die($insert." ".mysql_error()); return mysql_insert_id(); } function dosar_modDosar($array){ $update="UPDATE `dosar` SET `active`='1', `content`='".str_replace("'","\'",$array['content'])."', `number_dosar`='".$array['number_dosar']."', `fromActAdvId`='".command_getCommandIdFromNr($array['fromActAdvId'])."', `county`='".$array['county']."', `city`='".$array['city']."', `institute`='".$array['institute']."', `observation_public`='".$array['observation_public']."', `observation_privat`='".$array['observation_privat']."', `clientid`='".$array['clientid']."', `tip_client`='".$array['tip_client']."', `adversar`='".$array['adversar']."', `materie_juridica`='".$array['materie_juridica']."', `obiect`='".$array['obiect']."', `stadiu`='".$array['stadiu']."', `complet`='".$array['complet']."', `sala`='".$array['sala']."', `sarcina`='".$array['sarcina']."' WHERE `id`='".$array['inserted']."'"; mysql_query($update) or die($update." ".mysql_error()); return true; } function dosar_SearchDosar($page,$number, $orderby, $ordermode, $from , $to, $searchval, $searchCriteria, $county='',$material='',$obiect='',$stadiu='' ){ if ($orderby=='') $orderby='id'; if ($from=='') $datum="WHERE "; else $datum="WHERE `ondate` BETWEEN '$from' AND '$to 23:59:59'"; if ($searchval==''){ if ($datum=="WHERE "){ $keres=""; $datum="";}else $keres=""; } else if ($searchCriteria=='name'){ if ($datum=="WHERE ") $keres=" `clientid` in $searchval"; else $keres=" AND `clientid` in $searchval"; }else{ if ($datum=="WHERE ") $keres=" `$searchCriteria` $searchval"; else $keres=" AND `$searchCriteria` $searchval"; } if ($page=='') $lim=''; else $lim=" LIMIT ".($page*$number-$number).", $number"; if ($county=='0' || $county=='') $jud=''; else if ($datum=="WHERE ") $jud=" `county`='$county'"; else $jud=" AND `county`='$county'"; if ($material=='0' || $material=='') $mat=''; else if ($datum=="WHERE ") $mat=" `materie_juridica`='$material'"; else $mat=" AND `materie_juridica`='$material'"; if ($obiect=='0' || $obiect=='') $ob=''; else if ($datum=="WHERE ") $ob=" `obiect`='$obiect'"; else $ob=" AND `obiect`='$obiect'"; if ($stadiu=='0' || $stadiu=='') $st=''; else if ($datum=="WHERE ") $st=" `stadiu`='$stadiu'"; else $jud=" AND `stadiu`='$stadiu'"; $query="SELECT * FROM `dosar` $datum $keres $jud $mat $ob $st ORDER BY $orderby $ordermode $lim"; $result=mysql_query($query) or die($query." ".mysql_error()); $lista=array(); while ($row=mysql_fetch_array($result)) $lista[]=$row; return $lista; } function dosar_SearchCountDosar($orderby, $ordermode, $from , $to, $searchval, $searchCriteria , $county='',$material='',$obiect='',$stadiu='' ){ if ($orderby=='') $orderby='id'; if ($from=='') $datum="WHERE "; else $datum="WHERE `ondate` BETWEEN '$from' AND '$to 23:59:59'"; if ($searchval==''){ if ($datum=="WHERE "){ $keres=""; $datum="";}else $keres=""; } else if ($searchCriteria=='name'){ if ($datum=="WHERE ") $keres=" `clientid` in $searchval"; else $keres=" AND `clientid` in $searchval"; }else{ if ($datum=="WHERE ") $keres=" `$searchCriteria` $searchval"; else $keres=" AND `$searchCriteria` $searchval"; } if ($county=='0' || $county=='') $jud=''; else if ($datum=="WHERE ") $jud=" `county`='$county'"; else $jud=" AND `county`='$county'"; if ($material=='0' || $material=='') $mat=''; else if ($datum=="WHERE ") $mat=" `materie_juridica`='$material'"; else $mat=" AND `materie_juridica`='$material'"; if ($obiect=='0' || $obiect=='') $ob=''; else if ($datum=="WHERE ") $ob=" `obiect`='$obiect'"; else $ob=" AND `obiect`='$obiect'"; if ($stadiu=='0' || $stadiu=='') $st=''; else if ($datum=="WHERE ") $st=" `stadiu`='$stadiu'"; else $jud=" AND `stadiu`='$stadiu'"; $query="SELECT * FROM `dosar` $datum $keres $jud $mat $ob $st "; $result=mysql_query($query) or die($query." ".mysql_error()); return mysql_affected_rows(); } function institutii_addInstitutii($city, $name){ $q="SELECT `id` FROM `institutii` WHERE `name`='$name' AND `citi_id`='$city'"; mysql_query($q); if (mysql_affected_rows()<1){ $query="INSERT INTO `institutii` (`city_id`,`name`) VALUES ('$city','$name')"; if (mysql_query($query)) return true; else return false; }else return false; } function institutii_getInstitutiiById($id){ $q="SELECT * FROM `institutii` WHERE `id`='$id' "; $result=mysql_query($q) or die($q." ".mysql_error()); return mysql_fetch_array($result); } function tipclient_addTipClient($name, $lang){ $q="SELECT `id` FROM `tip_client` WHERE `name`='$name' AND `lang`='$lang'"; mysql_query($q); if (mysql_affected_rows()<1){ $query="INSERT INTO `tip_client` (`ondate`,`name`,`lang`) VALUES (NOW(),'$name','$lang')"; if (mysql_query($query)) return true; else return false; }else return false; } function tipclient_getTipClientById($id){ $q="SELECT * FROM `tip_client` WHERE `id`='$id' "; $result=mysql_query($q) or die($q." ".mysql_error()); return mysql_fetch_array($result); } function materiejuridica_addMaterieJuridica($name, $lang){ $q="SELECT `id` FROM `materie_juridica` WHERE `name`='$name' AND `lang`='$lang'"; mysql_query($q); if (mysql_affected_rows()<1){ $query="INSERT INTO `materie_juridica` (`ondate`,`name`,`lang`) VALUES (NOW(),'$name','$lang')"; if (mysql_query($query)) return true; else return false; }else return false; } function materiejuridica_getMaterieJuridicaById($id){ $q="SELECT * FROM `materie_juridica` WHERE `id`='$id' "; $result=mysql_query($q) or die($q." ".mysql_error()); return mysql_fetch_array($result); } function obiectdosar_addObiectDosar($name, $lang){ $q="SELECT `id` FROM `obiect_dosar` WHERE `name`='$name' AND `lang`='$lang'"; mysql_query($q); if (mysql_affected_rows()<1){ $query="INSERT INTO `obiect_dosar` (`ondate`,`name`,`lang`) VALUES (NOW(),'$name','$lang')"; if (mysql_query($query)) return true; else return false; }else return false; } function obiectdosar_getObiectDosarById($id){ $q="SELECT * FROM `obiect_dosar` WHERE `id`='$id' "; $result=mysql_query($q) or die($q." ".mysql_error()); return mysql_fetch_array($result); } function stadiuprocesual_addStadiuProcesual($name, $lang){ $q="SELECT `id` FROM `stadiu_procesual` WHERE `name`='$name' AND `lang`='$lang'"; mysql_query($q); if (mysql_affected_rows()<1){ $query="INSERT INTO `stadiu_procesual` (`ondate`,`name`,`lang`) VALUES (NOW(),'$name','$lang')"; if (mysql_query($query)) return true; else return false; }else return false; } function stadiuprocesual_getStadiuProcesualById($id){ $q="SELECT * FROM `stadiu_procesual` WHERE `id`='$id' "; $result=mysql_query($q) or die($q." ".mysql_error()); return mysql_fetch_array($result); } function HasChitantaFromDp($dp) { $query="SELECT * FROM `bills` WHERE `fromdp`='$dp'"; $result=mysql_query($query) or die(mysql_error()); return mysql_num_rows($result)>0; } function GetFacturaBillOpForFisaClient($clientid) { $query="SELECT * FROM `facturi` WHERE `active`='1' AND `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $facturi[$row["id"]]=$row; } $query="SELECT * FROM `bills` WHERE `active`='1' AND `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $bills[$row["id"]]=$row; } $query="SELECT * FROM `op` WHERE `clientid`='$clientid'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { while($row=mysql_fetch_array($result)) $op[$row["id"]]=$row; } $all["facturi"]=$facturi; $all["bills"]=$bills; $all["op"]=$op; return $all; } function factura_getStornoFactura( $facturaId ) { $query = "SELECT * FROM `facturi` WHERE `id`=$facturaId AND `active` ='1' AND `type`='1'"; $results = mysql_query( $query ) or die(mysql_error()); if( mysql_affected_rows() <= 0 )return NULL; $row = mysql_fetch_array( $results ); $questFacturaRawValue = $row["rawvalue"]; $questFacturaClientId = $row["clientid"]; $questFacturaRonValue = convertNumber( ($row["rawvalue"] * $row["cursValue"])*(-1) ); $hossz = strlen($questFacturaRonValue); $questFacturaRonValueFinal1 = $questFacturaRonValue+0.01; $questFacturaRonValueFinal2 = $questFacturaRonValue-0.01; $questFacturaCursValue = $row["cursValue"]; $questFacturaId = $row["id"]; $questFacturaFromCommandForClientId = $row["fromActId"]; $questFacturaFromCommandAdvForClientId = $row["fromActAdvId"]; $questFacturaDate = $row["ondate"]; $negativeQuestFacturaRawValue = 0 - $questFacturaRawValue; $paidFactura = factura_getPaidValueWithoutCurrency($questFacturaId); $queryFactura = "SELECT * FROM `facturi` WHERE `rawvalue`<0 AND `clientid`='$questFacturaClientId' AND (`fromActId`='$questFacturaFromCommandForClientId' OR `fromActAdvId`='$questFacturaFromCommandAdvForClientId') AND (`rawvalue` = '$negativeQuestFacturaRawValue' OR `rawvalue` = ('$negativeQuestFacturaRawValue'*'$questFacturaCursValue') OR `rawvalue` = ('$negativeQuestFacturaRawValue'/'$questFacturaCursValue') ) AND `rawvalue` * `cursValue` > '$questFacturaRonValueFinal2' AND `rawvalue` * `cursValue` < '$questFacturaRonValueFinal1' AND `ondate`>='$questFacturaDate' AND `active` ='1' AND `type`='1'"; $resultsFactura = mysql_query( $queryFactura ) or die(mysql_error()); if( mysql_num_rows($resultsFactura) <= 0 ) { return NULL; } else { if($paidFactura==0) { $row=mysql_fetch_array($resultsFactura); return $row; } else return NULL; } } function GetLastFacturat($serviciu) { $query="SELECT * FROM `facturi_items` WHERE `modelid`='".$serviciu->prodid."' AND `factid` IN (SELECT `id` FROM `facturi` WHERE `fromActAdvId`='".$serviciu->comid."') ORDER BY `id` DESC LIMIT 1"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) $row=mysql_fetch_array($result); return $row["endDate"]; } function GetNextFacturaDate($serviciu) { $query="SELECT * FROM `comandaForClientAdvItems` WHERE `id`='".$serviciu->rowid."'"; $result=mysql_query($query) or die(mysql_error()); if($result&&mysql_num_rows($result)>0) { $row=mysql_fetch_array($result); } if($row["period"]=="unic") { $ison=factura_getServiceDateNotonFactura( $serviciu->prodid,$serviciu->comid,date("Y-m-d"),$serviciu->rowid); if($ison==NULL) return ""; else { $row=mysql_fetch_array($ison); return $row["date"]; } } else if($row["period"]=="zilnic") { if($serviciu->lastfacturatlastfacturat<$serviciu->enddate) { return date("Y-m-d"); } else return ""; } else if($row["period"]=="saptamanal") { $nowday=date("w"); $tombz["0"]="sunday"; $tombz["1"]="monday"; $tombz["2"]="tuesday"; $tombz["3"]="wednesday"; $tombz["4"]="thursday"; $tombz["5"]="friday"; $tombz["6"]="saturday"; if($serviciu->lastfacturat>date("Y-m-d")) { return ""; } else if($nowday!=$serviciu->ziua&&$serviciu->lastfacturat<$serviciu->enddate) { return date( 'Y-m-d', strtotime( 'next '.$tombz[$serviciu->ziua] )); } else if ($nowday==$serviciu->ziua&&$serviciu->lastfacturat<$serviciu->enddate) { return date("Y-m-d"); } else return ""; } if($row["period"]=="lunar") { if($serviciu->lastfacturat<=date("Y-m-d")&&$serviciu->lastfacturat<$serviciu->enddate) { $nowy=intval(date("Y")); $nowm=intval(date("n")); $nowd=intval(date("j")); if($nowd<$serviciu->data) { $nowd=$serviciu->data; } else { $nowm=$nowm+1; if($nowm==13) { $nowm=1; $nowy++; } $nowd=$serviciu->data; } if(intval($nowd)>intval(date("t"))) { $nowd=date("t"); } if($nowd<10) $nowd="0".$nowd; if($nowm<10) $nowm="0".$nowm; return $nowy."-".$nowm."-".$nowd; } else { return ""; } } if($row["period"]=="anual") { if($serviciu->lastfacturat<=date("Y-m-d")&&$serviciu->lastfacturat<$serviciu->enddate) { $Date = strtotime($serviviu->lastfacturat); return date("Y-m-d",strtotime('+1 year',$Date)); }