티스토리 뷰

반응형

레이져업체의 의뢰를 받아서 구현중인 시스템에서 xml파일을 파싱해서 불러와서 견적내고 판매가도 산출하는 프로그램을 만드는 중....

기본적으로 정보를 담는 파일을 신규로 작성한다고 하면,

보통 파일 작성시 새로운 데이터를 만들때는 서버에 저장 전이기 때문에 번호를 부여하지 않는데,

xml파일 불러오기 루틴을 하나 만든다고 하면 부모데이터, 즉 신규레코드의 값이 기본적으로 필요한 것이 사실이다.

왜냐하면 먼저 불러올때 parentKey값을 주고 저장을 해야...서버에 기록이 되는데,

안 그런다면 임시로 값을 갖고 있다가, 저장버튼을 누를때 Grid를 저장하는 방식으로 바꾸면 될 것 같다.

기존방식에서 벗어나지 않으면 코드가 개선되지 않는다.

'생각의 틀을 혁파하라'

오늘 나에게 주는 교훈같다.

 <?php session_start();  

include $_SERVER['DOCUMENT_ROOT'] . '/common.php';


ini_set('display_errors','0');  // 화면에 warning 없애기
 
$user_name= $_SESSION["name"];
$user_id= $_SESSION["userid"];
$ecountID= $_SESSION["ecountID"];

// 환경파일 읽어오기 (자재비등) 개발자인 경우
if($user_id=='es' || $user_id=='a')
{
    $tmp_name = "../settings.ini";
   }
   else
   {
	   $tmp_name = "../ini/" . $user_id . "_settings.ini";
	   
	   if (!file_exists($tmp_name)) {
               copy("../settings.ini", $tmp_name);
			  }
   }	   

$readIni = array();   // 환경파일 불러오기
$readIni = parse_ini_file($tmp_name,false);	

$relativedensity=$readIni['relativedensity'];
$sus_relativedensity=$readIni['sus_relativedensity'];
$al_relativedensity=$readIni['al_relativedensity'];
$bendingFeePerUnit=(int)$readIni['bendingFeePerUnit'];
$PaintingFeePerUnit=$readIni['PaintingFeePerUnit'];
$laserfee_PO=$readIni['laserfee_PO'];
$laserfee_SUS=$readIni['laserfee_SUS'];
$laserfee_AL=$readIni['laserfee_AL'];
$iron_fee=$readIni['iron_fee'];
$ST_fee=$readIni['ST_fee'];
$PO_fee=$readIni['PO_fee'];
$CR_fee=$readIni['CR_fee'];
$GI_fee=$readIni['GI_fee'];
$EGI_fee=$readIni['EGI_fee'];
$sus_fee=$readIni['sus_fee'];
$al_fee=$readIni['al_fee'];

// var_dump($readIni);

  $description = array();
  $length = array();
  $width = array();
  $material = array();
  $thickness = array();
  $donenum = array();
  $donetime = array();
  $unitfee = array();
  $bendingNum = array();
  $bendingAmount = array();
  $paintingArea = array();
  $bendingUnitFee = array();
  $paintingChoice = array();
  $paintingUnitFee = array();
  $paintingUnit = array();
  $paintingAmount = array();
  $painting = array();
  $lastworkUnitFee = array();
  $lastwork = array();
  $weights = array();
  $laserfee = array();
  $unit_Amount = array();
  $est_Amount = array();
  $device = array();

//  읽어올 input name
$filechoice = 'upload_file';

$myfiles = $_FILES[$filechoice]['name'];

// var_dump($myfiles);

$countfiles = count($myfiles);

$count=0;		

for($i=0;$i<$countfiles;$i++){
	
	$filename = $_FILES[$filechoice]['name'][$i];	
	//  move_uploaded_file($tmp_file, $file_path); 함수 사용시  name이 아닌 tmp_name이 첫번째 parameter임을 명심하자.
	$tmp_file = $_FILES[$filechoice]['tmp_name'][$i];
	
	// 중요~~~~
	// 중요~~~~
	// 중요~~~~
	// 중요~~~~ target dir 없으면 에러발생 ... 한참 찾고 고생함
	
	$target_dir = "./";
	$target_file = $target_dir . $_FILES[$filechoice]["name"][$i];
	$uploadOk = 1;
	
	@chmod("$target_dir", 0707);
	if ($uploadOk == 0) {
	 // echo "Sorry, your file was not uploaded.";
	// if everything is ok, try to upload file
	} else {
	  if (move_uploaded_file($tmp_file, $target_file)) {
		//echo "The file  has been uploaded.";
	  } else {
		//echo "Sorry, there was an error uploading your file.";
	  }
	}	
	
if($target_file !='') {   			

	   // xml파일 파싱하기	
	   
		$xml = file_get_contents(rtrim($target_file));				
		$result_xml = simplexml_load_string($xml);
		// $file = explode(".", $file_name);
		$tmp_material = $result_xml->JobNote ;												
		$tmp_thickness = $result_xml->RawMaterialThickness;    // 두께 파싱한다.
		$tmp_device = $result_xml->Workplace['WorkplaceName'];
		$arr_device =(array) $tmp_device;
		
		$arr = (array) $tmp_material;
		$arr_thickness = (array) $tmp_thickness;
		$tmp = substr($arr[0], strlen($arr[0])-8);						
		$tmp_spec = strtoupper(preg_replace('/\r\n|\r|\n/','',$arr[0]));			                
						
		foreach ($result_xml->Parts->Part as $key)
		{
			$count ++;														
			$text = strtoupper(preg_replace('/\r\n|\r|\n/','',$key->Description));						
			$text = strtoupper($text);  // 대문자로 변환
			$description[$count-1] = $text;			             
			$length[$count-1] = ceil( json_decode($key->Dimensions->Length , true)) + 10 ;   // 10mm 키워서 계산함
			$width[$count-1] = ceil(json_decode( $key->Dimensions->Width , true)) + 10 ;     // 10mm 키워서 계산함.
		    // $weight[$count-1] = json_decode( $key->Weight, true);
			
		  // php  "PO 1.6T에서 파싱을 통해 1.6T를 찾는 구문	파싱으로 ST 구문은 철판으로 SS는 SUS 구분하기															
			preg_match('/PO(.*?)T|CR(.*?)T|EGI(.*?)T|GI(.*?)T|SUS(.*?)T|ST(.*?)T|SS(.*?)T|AL(.*?)T/', $text, $output);
			$extract_mat = preg_replace('/\r\n|\r|\s+|\.|\d|\n/','',$output[0]); // 공백제거 숫자제거 .(점) 제거
			$extract_mat =  substr($extract_mat, 0, -1);  // 마지막문자 'T' 지워줌
			$material[$count-1] = $extract_mat;							
			$thickness[$count-1] =$arr_thickness[0];											
			
			$donenum[$count-1] = (int) json_decode( $key->TotalQuantityInJob , true);
			$set_donenum = $donenum[$count-1];
			$donetime[$count-1] = ceil((float)json_decode($key->TargetProcessingTimePerPiece , true) * 60)  ;
			$bendingFee[$count-1] = (int)$bendingFeePerUnit;
			
				if($material[$count-1]=='PO' || $material[$count-1]=='CR' || $material[$count-1]=='EGI' || $material[$count-1]=='ST' || $material[$count-1]=='GI') 
				  {
					$set_weight = (float) $relativedensity ;    // 재질별 무게 비중적용 계산
					
					if($material[$count-1]=='ST')
						$material_fee = conv_num($ST_fee) ;  	 // 재료기준에 따른 재료비 산출부분
					if($material[$count-1]=='PO')	
						$material_fee = conv_num($PO_fee) ;  	 // 재료기준에 따른 재료비 산출부분								
					if($material[$count-1]=='CR')
						$material_fee = conv_num($CR_fee) ;  	 // 재료기준에 따른 재료비 산출부분
					if($material[$count-1]=='GI')	
						$material_fee = conv_num($GI_fee) ;  	 // 재료기준에 따른 재료비 산출부분								
					if($material[$count-1]=='EGI')
						$material_fee = conv_num($EGI_fee) ; 	 // 재료기준에 따른 재료비 산출부분								
					$set_laserfee = conv_num($laserfee_PO) ;
					
				 }
					  else if ($material[$count-1]=='SUS' || $material[$count-1]=='SS')
					  {
						$set_weight = (float) $sus_relativedensity ;    // 재질별 무게 비중적용 계산
						$material_fee = conv_num( $sus_fee) ;  	 // 재료기준에 따른 재료비 산출부분
						$set_laserfee = conv_num($laserfee_SUS) ;
					  }
							else {
								$set_weight = (float) $al_relativedensity ;    // 재질별 무게 비중적용 계산
								$material_fee = conv_num($al_fee) ;  	 // 재료기준에 따른 재료비 산출부분
								$set_laserfee = conv_num($laserfee_AL) ;
							} 
							
			 // set_weigh 비중임
			 $unitweight = ($set_weight* (int)$length[$count-1] * (int)$width[$count-1] * (float)$thickness[$count-1]) / 1000000;   //비중*길이*폭*두께 = 중량
			 $unitweight = round($unitweight, 2);
			//  echo "중량 $unitweight set_laser_fee $set_laserfee length $length[$count-1] " ;
			
			// 재료비 산출부분
			$unitfee[$count-1] = ceil($material_fee * $set_donenum * $unitweight/100)*100 ;	
			$bendingNum[$count-1] = '';
			$bendingAmount[$count-1] = '';
			$bendingUnitFee[$count-1] = '';
			
			$paintingArea[$count-1] = '';
			$paintingChoice[$count-1] = '1';
			$paintingUnitFee[$count-1] = '';
			$paintingUnit[$count-1] = '';
			$paintingAmount[$count-1] = '';								
			
			$painting[$count-1] ='';
			$lastworkUnitFee[$count-1] = '';
			$lastwork[$count-1] = '';
			$weights[$count-1] =  number_format($unitweight , 2) ; // 소주점 두째자리까지만 표현
			$laserfee[$count-1] = ceil($set_laserfee * $donetime[$count-1] * $set_donenum /100 )*100 ;	
			// echo " $set_laserfee 수량 $set_donenum 무게 $unitweight ";

			$unit_Amount[$count-1] = 0;					
			$est_Amount[$count-1] = 0;			
			$device[$count-1] = $arr_device[0];	

			}	  
		}  // end of if			

      //파싱이 끝난 파일은 삭제
     unlink($target_file);	  

	} // end of for statement    
 

// header('Content-type: application/json'); 

 $data = [   'description' => $description ,
 'length' => $length ,
 'width' => $width ,
 'material' => $material ,
 'thickness' => $thickness ,
 'donenum' => $donenum ,
 'donetime' => $donetime ,
 'unitfee' => $unitfee ,
 'bendingFee' => $bendingFee ,
 'bendingNum' => $bendingNum ,
 'bendingAmount' => $bendingAmount ,
 'paintingArea' => $paintingArea ,
 'bendingUnitFee' => $bendingUnitFee ,
 'paintingChoice' => $paintingChoice ,
 'paintingUnitFee' => $paintingUnitFee ,
 'paintingUnit' => $paintingUnit ,
 'paintingAmount' => $paintingAmount ,
 'painting' => $painting ,
 'lastworkUnitFee' => $lastworkUnitFee ,
 'lastwork' => $lastwork ,
 'weights' => $weights ,
 'laserfee' => $laserfee ,
 'unit_Amount' => $unit_Amount ,
 'est_Amount' => $est_Amount ,
 'device' => $device   ];
 
 echo json_encode($data, JSON_UNESCAPED_UNICODE);
?>

 

위는 실제 xml파일을 불러오는 루틴을 작성해서 JSON형태로 받아서 처리하는 루틴 중 

xml파일을 불러오기 위한 코드이다.

저장하는 과정을 실제 저장할때 처리하는 방법으로 하면 문제점은 다시 xml버튼을 눌러서 수정할때

메모리에 있는 코드를 가져와야 한다는 것...

임시로 파일을 저장한 후 저장할때 parentkey를 부여하는 방식으로 짜면 가장 좋을 것 같다.

임시로 key를 하나 발급해서 실제 저장이 이뤄지면 그 임시key를 부여해 주는 방식....

그게 가장 맞는 것 같다.

지금 만들어 놓은 루틴을 활용하며... 재사용 가능하고 효율적인 방식...

해결방안 모색 연구

1) 임시key 발급 후 부여

2) 임시key 모듈을 나가기 전까지 메모리에 보관

3) '저장'버튼 클릭이 일어났을때 임시key 모듈의 번호를 전부 수정하는 방식으로 저장...

이걸 코딩으로 구현해 봐야겠다.

// 전달값이 있다면 result에 찍어줌
if(isset($_REQUEST["num"])) 
{
	$num=$_REQUEST["num"];	  
}
if(isset($_REQUEST["tmpKey"])) 
{
	$tmpKey=$_REQUEST["tmpKey"];	  
}


// num이 0 또는 ''인 경우 임시키 발급
$tmpKey = '';
if((int)$num === 0 )
    $tmpKey = random_string(7);

임시키를 랜덤으로 생성하는 함수 만듬

$tmpKey를 생성해서 저장버튼을 누를때까지 메모리에 저장하고 저장하고 나가면 

초기화하는 루틴을 작성해서 활용한다.

// 랜덤값 생성 임시key생성시 유용함
// 사용방법 $get = random_string(5); //5자리의 랜덤값을 돌려줍니다.
function random_string($length) {
    $randomcode = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'd', 'E', 'F', 'G', 'H', 'x', 'J', 'K', 'b', 'M', 'N', 'y', 'P', 'r', 'R', 'S', 'T', 'u', 'V', 'W', 'X', 'Y', 'Z');
   
	mt_srand((double)microtime()*1000000);
    for($i=1;$i<=$length;$i++) $Rstring .= $randomcode[mt_rand(1, count($randomcode))];
    return $Rstring;
}

parentKey값으로 불러오는 구문도 수정함.

	  // tmpKey가 존재하면 tmpKey로 parentKey를 지정한다.
	  if($tmpKey!=='')
		  $stmh->bindValue(1,$tmpKey,PDO::PARAM_STR); 
		  else
			$stmh->bindValue(1,$num,PDO::PARAM_STR);

 

정상적으로 작동함을 보고 마친다.

결국 새로운 데이터를 추가하는 루틴에서 번호가 정해지지 않으면

임시 Key를 만들어서 사용하는 것이 제일 좋다

반응형
댓글