ATS_AIM_data_input.js 14.2 KB
Newer Older
Scott Sun's avatar
Scott Sun committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54


/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'path',
			title : '资料路径',
			type : 'LineEdit',
			property : {tool_tip : '资料路径,必填'},
		},
		{
			name : 'db',
			title : '料号db',
			type : 'LineEdit',
			property : {tool_tip : '料号db,默认是genesis'},
		},
		{
			name : 'config_path',
			title : '配置地址',
			type : 'LineEdit',
			property : {tool_tip : '配置的路径'},
		}
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-20 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 客户数据导入 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> 料号 和 客户配置 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// 引入模块 包
console.log("=============================================>input_start");
console.log("=============================================>input_start");
console.log("=============================================>input_start");
console.log("=============================================>input_start");
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
Scott Sun's avatar
Scott Sun committed
55
var zip = require('topsin.zip');
Scott Sun's avatar
Scott Sun committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}

if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
Scott Sun's avatar
Scott Sun committed
80 81
				current_process_title: $.process_title,
				progress: 0
Scott Sun's avatar
Scott Sun committed
82 83 84 85 86 87 88 89 90
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];
var import_info = []
try {
Scott Sun's avatar
Scott Sun committed
91
	script_info({ result_severity: "import start" })
Scott Sun's avatar
Scott Sun committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
	var par = PAR;
	// var db_path = db.query("",function(q){
	// 	return q.selectValue({
	// 		table:'pub_conf',
	// 		field:'text_data',
	// 		where:{path : "quote-data-upload"}
	// 	})
	// });
	// if(_.isEmpty(db_path)){throw "quote-data-upload error"}
	if(!par.path || par.path == "") {throw "path error"}
	if(!par.hasOwnProperty("config_path") || par.config_path==""){
		console.log("========================cfg");
		par.config_path = "cam/input_data"
	};
	if(!par.hasOwnProperty("db") || par.db==""){
		console.log("========================db");
		par.db = "genesis"
	};
	var db_customer = db.query("",function(q){
		return q.selectValue({
			table:'pdm_job',
			field:'customer_code',
			where:{id : JobId}
		})
	});
	if(_.isEmpty(db_customer)){throw "customer error"}
	if(db_customer && !(/^done$/ig.test(db_customer)) && db_customer != "" ){
		par.customer = db_customer
	}
	par.customer = par.customer[0].toUpperCase()+par.customer.slice(1).toLowerCase()
	var cfg = db.query("",function(q){
		return q.selectValue({
			table:'pub_conf',
			field:'text_data',
			where:{path : par.config_path}
		})
	});
	if (!cfg || cfg == ""){throw "cfg can not find"}  
	var config = eval(cfg);
	if(!config.hasOwnProperty("customer")){throw "config error"}
	var job = Job;
	if(_.isEmpty(job)) throw "没有传入料号名!";
	job = job.toLowerCase()
	// 如果genesis已经存在这个料号
	err = delSameJob({job:job,delSame:config.delSameJob}); if(err){throw err};
	var custCfg = config.customer[par.customer]
	if(!custCfg){throw "customer config error:"+par.customer}
	custCfg.db = par.db || custCfg.db
	var step = custCfg.step.toLowerCase()
	// 获取路径下文件信息
	var path = par.path
	if(!fs.exists(path)){throw "path error"}
	var pathInfo = fs.listDir(path + "/" + db_customer.toLowerCase(), 1)
	// 判断存不存在料号文件
	// var vc_position = db.query("",function(q){
	// 	return q.selectValue({
	// 		table:'pdm_job',
	// 		field:'version',
	// 		where:{id : JobId}
	// 	})
	// });
	var job_file_baseName = job
	// if(vc_position && vc_position != "" && !(/null/ig.test(vc_position))){
	// 	job_file_baseName = job_file_baseName + "_" + vc_position
	// }
	console.log("=========  ====>pathInfo:"+ _.toString(pathInfo) + "  job: " + job_file_baseName)
	var jobFile = pathInfo.filter(function(v){return v.baseName.toLowerCase() == job_file_baseName})
	if(jobFile.length == 0){throw "job file is not exist"}
	var jobFiles = []  // 记录要分析的文件
	if (!jobFile[0].isDir) {
		jobFiles.push(jobFile[0])
	} else {
		jobFiles = fs.listDir(jobFile[0].path)
	}
	GEN.COM("config_edit,name=iol_gbr_polygon_break,value=1,mode=user")
	GEN.COM("config_edit,name=iol_fix_ill_polygon,value=yes,mode=user")
Scott Sun's avatar
Scott Sun committed
168 169
	
	// 将jobFile下的zip解压
Scott Sun's avatar
Scott Sun committed
170 171 172
	decompression(jobFile[0].path, [])

	jobFiles = fs.listDir(jobFile[0].path)
Scott Sun's avatar
Scott Sun committed
173

Scott Sun's avatar
Scott Sun committed
174 175 176 177 178
	// 分析料号文件 得到料号导入信息 导入类型
	var jobInfo = analyJobFiles({jobFiles:jobFiles.filter(function(v){return v.isFile}),custCfg:custCfg,config:config,job:job })
	if(jobInfo.data.length == 0){throw "file error"}
	var importOk = false;  // 是否成功导入

Scott Sun's avatar
Scott Sun committed
179 180
	script_info({ progress: 10 })

Scott Sun's avatar
Scott Sun committed
181
	
Scott Sun's avatar
Scott Sun committed
182

Scott Sun's avatar
Scott Sun committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
	if(/odb/ig.test(jobInfo.type)){  // odb导入
		if(jobInfo.data.length == 1){  // 只分析到一个tgz文件 直接导入

			IKM.msg("只分析到一个tgz文件 直接导入")

			import_info.push({name:jobInfo.data[0].file.name, type:"odb++", date:now(),user:$.user_name})
			var err = importJob({name:job,db:custCfg.db,path:jobInfo.data[0].file.path},config.delSameJob)
			
			if(err){throw err}

		} else {  // 多个tgz文件 说明需要合并
			console.log("==========合并的情况");
			var jobs = jobInfo.data.map(function(item, i){
				var path = item.file.path
				var tmp_job_name = job + "_tmp_" + i
				var err = importJob({name:tmp_job_name,db:custCfg.db,path:path},config.delSameJob)
				import_info.push({name:item.file.name, type:"odb++", date:now(),user:$.user_name})
				if(err){throw err}
				return {
					name:tmp_job_name,
					path: path
				}
			})
			var step_all = [];
			// 分析arr_job 和 pcs_job
			jobs.forEach(function(item){
				var jobname = item.name
				GEN.openJob({job:jobname});
				var steps = GEN.getStepList({job:jobname})
				steps.forEach(function(stepname){
					var type = getStepType(stepname) // pcs arr
					if(type == "pcs"){
						step_all.unshift({
							jobname: jobname,
							stepname:  stepname,
							type: type
						})
					}
					if(type == "arr"){
						step_all.push({
							jobname: jobname,
							stepname:  stepname,
							type: type
						})
					}
				})
			})
			var pcs_job_name_tmp = step_all[0].jobname
			step_all = step_all.filter(function(item){
				return item.jobname != pcs_job_name_tmp
			})
			var pcs_job = jobs.filter(function(item){
				return item.name == pcs_job_name_tmp
			})[0]
			importJob({name:job,db:custCfg.db,path:pcs_job.path},config.delSameJob)
			GEN.openJob({job:job});
			step_all.forEach(function(item){
				if(!GEN.isJobOpen({job:item.jobname})){ GEN.openJob({job:item.jobname})};
				GEN.copyStep({  // 合并
					source_job:item.jobname,
					source_name:item.stepname,
					dest_job:job,
					dest_name:item.stepname,
				});
			})
			jobs.forEach(function(item){
				var v = item.name
				if(GEN.isJobOpen({ job: v })){ GEN.closeJob({ job: v }) }
				GEN.deleteJob({ job: v });  // 合并后 删除array的料号
			})
		}
		importOk = true
	}

	if(/gerber/ig.test(jobInfo.type)){  // gerber导入
		GEN.createJob({name:job,db:custCfg.db})
		GEN.createStep({job:job,name:step})
		var gerberInfo = jobInfo.data.map(function(item){
			var gerberCfg = JSON.parse(JSON.stringify(item.format));
			var file = item.file
			gerberCfg.layer = file.name.toLowerCase().split(" ").join("-")
			gerberCfg.path = file.path
			gerberCfg.format = item.type
			gerberCfg.job = job
			gerberCfg.step = step
			return gerberCfg
		})
		GEN.COM("input_manual_reset")
		gerberInfo.forEach(function(v){
			import_info.push({name:v.layer, type:"gerber274x", date:now(),user:$.user_name})
			GEN.COM("input_manual_set",v)
		})
		GEN.COM("input_manual")
		importOk = true
	}
Scott Sun's avatar
Scott Sun committed
278
	if(!importOk){ script_info({ result_severity: "import error" }); throw "import error"}
Scott Sun's avatar
Scott Sun committed
279
	script_info({ progress: 20 })
Scott Sun's avatar
Scott Sun committed
280
	reNameStep(job)
Scott Sun's avatar
Scott Sun committed
281 282 283 284 285 286 287 288 289 290 291 292
	if(/2171/.test(par.customer)){
		var matrix = GEN.getMatrix({job:job});
		comp = Object.keys(matrix).filter(function(v){  // 如果有comp层 删除
			return /^comp_\+_/ig.test(v)
		})
		if (comp.length > 0){
			var tmp = GEN.getStepList({job:job})
			GEN.openStep({job:job,name:tmp[0]})
			GEN.COM("delete_comp")
			GEN.closeStep()
		}
	}
Scott Sun's avatar
Scott Sun committed
293 294 295 296 297

	GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
	GEN.saveJob({ job: job });
	GEN.checkInout({job:job,mode:"in"})
    GEN.closeJob({job:job})
Scott Sun's avatar
Scott Sun committed
298 299
	var steplist = GEN.getStepList({job:job})
	GEN.openStep({job:job,name:steplist[0]})
Scott Sun's avatar
s  
Scott Sun committed
300 301 302
	// 额外操作
	if (custCfg.extra) {
		custCfg.extra.forEach(function(item){
Scott Sun's avatar
Scott Sun committed
303 304 305 306 307 308 309 310
			var props = {
				type : jobInfo.type,
				fileInfo: jobInfo.data.filter(function(item2){return /Excellon/ig.test(item2.type) }),
				step:steplist[0]
			};
			if(item.verification(props)){
				item.fn(props);
			}
Scott Sun's avatar
s  
Scott Sun committed
311 312 313
		})
	}

Scott Sun's avatar
Scott Sun committed
314 315 316 317 318 319 320 321 322
	var import_html = "<table border=1 align='center' cellpadding=5 cellspacing=0 style=\"text-align: center;\"><tr><th>导入状态/Import Status</th><th>文件/File</th><th>类型/Type</th><th>导入时间/Import Time</th><th>操作用户/User</th></tr>"
	import_info.forEach(function(item){
		var name = item.name
		var type = item.type
		var date = item.date
		var user = item.user
		import_html += "<tr><td>Readin</td><td>"+name+"</td><td>"+type+"</td><td>"+date+"</td><td>"+user+"</td></tr>"
	})
	import_html += "</table>"
Scott Sun's avatar
Scott Sun committed
323
    // name type date user
Scott Sun's avatar
Scott Sun committed
324 325
    resultData.push({type: "info",title:"导入资料列表",detail: [{ desc: import_html }] })
	script_info({ result_severity: "import ok" })
Scott Sun's avatar
Scott Sun committed
326 327 328 329
	if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
Scott Sun's avatar
Scott Sun committed
330
				progress: 30
Scott Sun's avatar
Scott Sun committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}		
}
catch (e) {
    IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}

function delSameJob(props){
    var job = props.job
	var delSame = props.delSame
	console.log("======================>delsame:"+ delSame);
	
    if(GEN.isJobExists({job:job})){   
        if(/^yes$/ig.test(delSame)){
            if(GEN.isJobOpen({job:job})){ GEN.closeJob({job:job}) }
            GEN.deleteJob({job:job})
        } else {
            return "job "+ job+ " exist"
        }
    }
}
function analyJobFiles(props){
	var files = props.jobFiles;
	var config = props.config;
	var job = props.job;
	var custCfg = props.custCfg;
	var rules = custCfg.rules;
	var paramsFile = files.filter(function(file){return /param|ncdrill/ig.test(file.baseName)})
	var tmp_hash = {}
	paramsFile.forEach(function(file){
		tmp_hash[file.baseName] = (function(){
			var tmparr = fs.readFile(file.path).split("\n").filter(function(v){return /^\S+\s+\S/ig.test(v)})
			var tmp = {}
			tmparr.map(function(v){
				var arr = v.split(/\b\s+\b/)
				tmp[arr[0].replace(/-/ig,"_")] = arr[1]
			})
			return tmp
		})() 
	})
	
	var fileInfo = files.reduce(function(a,file){
		try {
			rules.forEach(function(item){
				if(item.valid({file:file, job:job})){
					var format = config.formats[item.format]
					var format1;
					if(item.format_params){
						format1 = item.format_params({params:tmp_hash})
					}
					if(format1){
						throw {file:file,type:item.type,format:format1}
					}else{
						throw {file:file,type:item.type,format:format}
					}
				}
			})
		} catch (info) { 
			a.push(info)
		}
		return a
	},[])

	var odbfiles = fileInfo.filter(function(item){return /odb/ig.test(item.type)})
	if(odbfiles.length == 0){
		return {
			type: "Gerber",
			data: fileInfo
		}
	} else {
		return {
			type: "ODB",
			data: odbfiles
		}
	}
}
function importJob(props,delSameJob){
    var name = props.name
    if (GEN.isJobExists({ job: name })) {
        if (/^yes$/ig.test(delSameJob)) {
            if(GEN.isJobOpen({ job: name })){ GEN.closeJob({ job: name }); }
            GEN.deleteJob({ job: name });
        }
        else {
            return "job "+name+" exist";
        }
	}
	IKM.msg(props)
    GEN.importJob(props);
}

function getStepType(step){
    if(/pcs|cad|orig|pcb/ig.test(step)){
        return "pcs"
    }
    if(/stp|arr/ig.test(step)){
        return "arr"
    }
    return "pcs"
}

function now(){
    var date = new Date()
    var time = _.toString(date)
    res1 = /\d{4}-\d{2}-\d{2}/.exec(time)
    res2 = /\d{2}:\d{2}:\d{2}/.exec(time)
    return res1 + " " +res2
}

function reNameStep(job) {
	var stepList = GEN.getStepList({job:job})
Scott Sun's avatar
Scott Sun committed
464
	if(!stepList){return}
Scott Sun's avatar
Scott Sun committed
465 466 467
	var pcs = []
	var arr = []
	stepList.forEach(function(v){
Scott Sun's avatar
Scott Sun committed
468 469 470 471 472 473 474 475
		if(v){
			if(v==="cad"){
				pcs.unshift(v)
			} else if(/pcs|cad|orig|pcb/ig.test(v)){
				pcs.push(v)
			} else if(/stp|arr/ig.test(v)){
				arr.push(v)
			}
Scott Sun's avatar
Scott Sun committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489
		}
	})
	pcs.forEach(function(v, i){
		if (i==0 && v == "cad") {
		} else {
			GEN.renameStep({job:job,name:v,new_name:'cad' + (i == 0? "" : i+1)})
		}
	})
	arr.forEach(function(v, i){
		if (i==0 && v == "stp") {
		} else {
			GEN.renameStep({job:job,name:v,new_name:'stp' + (i == 0? "" : i+1)})
		}
	})
Scott Sun's avatar
Scott Sun committed
490 491 492 493 494 495 496 497 498 499 500
}


function script_info(props){  // result_severity  progress
	if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: props,
			where: { id: $.task_id }
		});
	}
Scott Sun's avatar
Scott Sun committed
501 502 503 504 505 506 507 508 509 510 511 512 513
}

function decompression(path, zips) {
	var files = fs.listDir(path)
	var zipfiles = files.filter(function(item){
		if(item.suffix === "zip" && zips.indexOf(item.path) < 0){
			zips.push(item.path)
			zip.unzip(item.path);
			return true
		}
		return false
	})
	if(zipfiles.length) {decompression(path, zips)}
Scott Sun's avatar
Scott Sun committed
514
}