campaignTabData.blade.php 10.3 KB
<?php

use App\Models\Campaign;

ini_set("precision", 15);

include_once(app_path().'/lib/phpexcel/PHPExcel.php');

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
	$errorMsg = ""; $successMsg = "";$successCount = 0;

	if($_FILES['file']['tmp_name'])
	{
		if($_FILES['file']['type'] == "application/vnd.ms-excel")
		{
			$fileUploadLimit = 52428800; // files size is in bytes
			if($_FILES['file']['size'] < $fileUploadLimit)
			{
				if ($_POST["uploadFileType"] == "customerInfo" && $_POST["campaignName"] != "")
				{
					$inputFileType = "Excel5";
					$objReader = PHPExcel_IOFactory::createReader($inputFileType);
					$objPHPExcel = $objReader->load($_FILES['file']['tmp_name']);
					$objWorksheet = $objPHPExcel->getActiveSheet();
					$highestColumn = PHPExcel_Cell::columnIndexFromString($objPHPExcel->getActiveSheet()->getHighestColumn());
					$highestrow=$objPHPExcel->getActiveSheet()->getHighestRow();
					$excelarray=array();$keys=array();
					$listId = time();

					$dataColumns = ['id'=>'Id','unique_id'=>'Customer Unique Id','firstname'=>'First Name','lastname'=>'Last Name','mobile'=>'Mobile','phones'=>'Other Phones'];
					
					$campaign=Campaign::where('mkey','=',$_POST["campaignName"])->where('mtype','=','company')->first();
					if($campaign->crm != ""){
						$crmColumns = json_decode($campaign->crm);
						$crmColumns = (array)$crmColumns->formFields;
					}

					for($i=1;$i<=$highestrow;$i++){
						$excelarray[$i]=array();
						for($head = 0; $head < $highestColumn; $head++){
							if($i==1){
								$keys[$head]=trim($objWorksheet->getCellByColumnAndRow($head,$i)->getValue());
							}else{
								$excelarray[$i][$keys[$head]]=trim($objWorksheet->getCellByColumnAndRow($head, $i)->getValue());
							}
						}
					}
					// print_r($crmColumns);exit;
					for($i=3;$i<=$highestrow;$i++)
					{
						if($excelarray[$i]["id"]==""){
							$crmData = [];
							if(isset($crmColumns)){
								foreach ($crmColumns as $key => $value) {
									array_push($crmData, [$key => $excelarray[$i][$key]]);
								}
							}
							$data = ["list_id"=>$listId,
									"unique_id"=>$excelarray[$i]["unique_id"],
									"firstname"=>$excelarray[$i]["firstname"],
									"lastname"=>$excelarray[$i]["lastname"],
									"mobile"=>$excelarray[$i]["mobile"],
									"phones"=>$excelarray[$i]["phones"],
									"crm"=>serialize($crmData),
									"client"=>$_POST["campaignName"],
									"status"=>"New",
									'created'=>date('Y-m-d H:i:s'),
									'modified'=>date('Y-m-d H:i:s')];
							$addToDB = DB::table('records')->insert($data);
							$successCount++;
						}else{
							$excelarray[$i]["id"]=intval($excelarray[$i]["id"]);	
						}
						continue;
						// $lanq = DB::table('records')->select('id')->where('lan', '=', $excelarray[$i]["lan"])->first();
						// if($lanq){
						// 	$excelarray[$i]["id"]=intval($lanq->id);
						// }else{
						// 	$excelarray[$i]["id"]=$wakka->Query("insert into","","records",array('created'=>date('Y-m-d H:i:s')));
						// }

						if($wakka->getCount("records","id='".$excelarray[$i]["id"]."'")==1)
						{
							$empdata=$wakka->getPerson($excelarray[$i]["id"]);
							// $ppldata=$empdata["peopledata"];
							// $createdlog=$empdata['modifylog'];
							// $fdirty=$empdata['dirty'];

							// $createdlog[$updatetime]=$username."::";
							// $createdlog["updated"]=$updatetime;
							
							$newdata=$ppldata;
							if($isadmin||strstr($clientlst,$ppldata['client']))
							{
								$editflag=0;
								foreach($excelarray[$i] as $key => $value)
								{
									$value = preg_replace('/[^A-Za-z0-9\., -]/', '', $value);

									if(isset($kformlib->HRFieldNames[$key]))
									{
										if($value!="")
										{
											if("A".$ppldata[$key]!="A".$value)//forcing string comparrision //MAGIC
											{
												$value=str_replace("'"," ",$value);
												if(strstr($createdlog[$updatetime],$key)==FALSE)$createdlog[$updatetime].="$key|".str_replace(array("|",",")," ",$ppldata[$key])."|".str_replace(array("|",",")," ",$value).",";

												$fdirty[$key]=1;$editflag=1;
													
												if($triggers=='Yes')
												{
													$kformlib->empAnalytics($excelarray[$i]["id"],$ppldata,$key,$value,$ppldata[$key]);
													$kformlib->empWorkflowTrigger($excelarray[$i]["id"],$ppldata['client'],$key,$value,$ppldata[$key],$ppldata,$newdata);
												}
												$newdata[$key]=$value;
											}
												//else $message.="same $excelarray[$i][id]:$key:$value, ";
										}
											//else $message.="empty $excelarray[$i][id]:$key, ";
									}else{
										// $message.="Invalid key :$key, ";
									}
								}
								if($editflag)
								{
									$empdata["peopledata"]=$newdata;
									$empdata['modifylog']=$createdlog;
									$empdata['dirty']=$fdirty;

									$wakka->setPerson($excelarray[$i]["id"],$empdata);
									$success.=$excelarray[$i]["id"].",";
									$successCount++;
								}
							}else{
								$errorMsg.="No access to $excelarray[$i][id], ";
							}
						}
					}
					$successMsg .= "Data Uploaded ($successCount)."; // : $success.";
				}
			}else{
				$errorMsg .= "File size too large, Please check file size should be less then ".($fileUploadLimit / (1024*1024))."mb.";
			}
		}else{
			$errorMsg .= "File format not valid, Please attach Excel file (.xls) and try upload again.";
		}
		@unlink($_FILES['file']);
	}else{
		$errorMsg .= "File not found, Please attach file and try upload again.";
	}
	if(isset($successMsg) && $successMsg!="")echo "Success! <br/>".$successMsg;
	if(isset($errorMsg) && $errorMsg!="")echo "Error! <br/>".$errorMsg;
}
else
{
	if(isset($_GET['format']) && $_GET['format'] == 'dataUpload'){
		if(isset($_GET['campaign']) && $_GET['campaign'] != ''){
			$dataColumns = ['id'=>'Id','unique_id'=>'Customer Unique Id','firstname'=>'First Name','lastname'=>'Last Name','mobile'=>'Mobile','phones'=>'Other Phones'];
			
			$campaign=Campaign::where('mkey','=',$_GET['campaign'])->where('mtype','=','company')->first();
			if($campaign->crm != ''){
				$crmColumns = json_decode($campaign->crm);
				if($crmColumns->formFields)$dataColumns = array_merge($dataColumns,(array) $crmColumns->formFields);
			}
			$PHPExcelObj = new PHPExcel(); $head=0;
			foreach($dataColumns as $key => $value){
				$colstr=PHPExcel_Cell::stringFromColumnIndex($head);
				$PHPExcelObj->getActiveSheet()->setCellValue($colstr."1", $key);
				$PHPExcelObj->getActiveSheet()->setCellValue($colstr."2", $value);
				$head++;
			}
			$objWriter = PHPExcel_IOFactory::createWriter($PHPExcelObj, 'Excel5');
			$objWriter->save('php://output');

			header('Content-Type: application/vnd.ms-excel');
			header('Content-Disposition: attachment;filename="DataUploadFormat.xls"');
			header('Cache-Control: max-age=0');
			return;
		}else{
			echo "Campaign not found";
			return;
		}
	}
?>
<div class="row">
	<div class="col-sm-12">
		<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
			<div class="panel panel-info">
				<div class="panel-heading" role="tab" id="headingOne"  role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
					<strong><i class="fa fa-upload"></i> Data Upload</strong>
					<span class="badge pull-right"><i class="fa fa-sort"></i></span>
				</div>
				<div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
					<div class="panel-body">
						<div class="tab_generic">
							<p><span style="color:#f00;"><strong>Instruction</strong></span> (Works only if you have 'Write access" to the records) Please create an Excel-2003 format file with header as field-keys and rows containing record data. Extream Care is should be taken during bulk upload as previous values will be overwritten and lost.</p>
							<hr style="margin-bottom: 10px;" />
							<div class="row">
								<div class="col-sm-3">
									<p><strong>Get Format</strong></p>
									<button type="submit" class="btn btn-success" onclick="getDataFormat();return false;"><i class="fa fa-download"></i> Get Format</button>
								</div>
								<div class="col-sm-9">
									<p><strong>Upload File</strong></p>
									<form method="POST" enctype="multipart/form-data" target="resultArea" action="campaign?action=dataUpload" class="form-inline">
										<input type="hidden" name="_token" value="{{ csrf_token() }}" />
										<input type="hidden" name="uploadFileType" value="customerInfo"/>
										<input type="hidden" name="campaignName" value="{{ $campaignDetails->mkey }}"/>
										<div class="form-group">
											<input type="file" class="form-control" name="file" required="required" />
										</div>
										<div class="form-group">
											<button type="submit" class="btn btn-success"><i class="fa fa-upload"></i> Upload</button>
										</div>
									</form>
								</div>
							</div>
							<hr style="margin-top: 10px;margin-bottom: 10px;" />
							<span>Result</span>
							<iframe name=resultArea id="resultArea" style="width: 100%;border:1px solid #ccc;"></iframe>
						</div>
					</div>
				</div>
			</div>

			<div class="panel panel-info">
				<div class="panel-heading" role="tab" id="headingTwo" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
					<strong><i class="fa fa-table"></i> Data List</strong>
					<span class="badge pull-right"><i class="fa fa-sort"></i></span>
				</div>
				<div id="collapseTwo" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingTwo">
					<div class="panel-body">
						@if(isset($dataList) && count($dataList))
							<table class="table table-bordered" style="margin-bottom: 0;">
								<head><tr class="active">
									<th>List Id</th>
									<th>Record Count</th>
								</tr></head>
								<body>
								@foreach($dataList as $data)
									<tr>
										<td>{{ $data->list_id }}</td>
										<td>{{ $data->recordCount }}</td>
									</tr>
								@endforeach
								</body>
							</table>
						@else
							<p>No data found</p>
						@endif
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script type="text/javascript">
	function getDataFormat(){
		var campaign = $("#selectCampaignField").val();
		window.open('campaign/getDataFormat?format=dataUpload&campaign='+campaign);return false;
	}
</script>

<?php
}
?>