ATS_AIM_data_input.js 23.8 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


/*
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:
Scott Sun's avatar
Scott Sun committed
29
	V1.01 2020-04-20 Scott Sun
Scott Sun's avatar
Scott Sun committed
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
	    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
var process = require('process');
Scott Sun's avatar
Scott Sun committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
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
81 82
				current_process_title: $.process_title,
				progress: 0
Scott Sun's avatar
Scott Sun committed
83 84 85 86 87 88 89
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];
Scott Sun's avatar
Scott Sun committed
90 91
var import_info = [];
var inputState = [];
Scott Sun's avatar
Scott Sun committed
92 93
var cam_workflow_info = IKM.get_jobinfo({jobid:JobId, jobinfo:"cam_workflow_info"});
if(cam_workflow_info){
Scott Sun's avatar
Scott Sun committed
94 95 96 97
	IKM.crud("deleteRow", {
		table: "pdm_job_jobattr",
		where:{job_id:JobId, attr_name:"cam_workflow_info"},
	})
Scott Sun's avatar
Scott Sun committed
98 99
	IKM.save_job_info({jobid:JobId, jobinfohash:{cam_workflow_info:""}})
}
Scott Sun's avatar
Scott Sun committed
100
try {
Scott Sun's avatar
s  
Scott Sun committed
101
	global._ERRORMAG = null;
Scott Sun's avatar
Scott Sun committed
102 103 104 105 106 107 108 109 110
	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"}
Scott Sun's avatar
Scott Sun committed
111
	if(!par.path || par.path == "") {
Scott Sun's avatar
s  
Scott Sun committed
112 113
		script_info({ msg: "Find data path", result_severity:"error" });
		global._ERRORMAG = "The data path does not exist";
Scott Sun's avatar
Scott Sun committed
114
		throw "path error"}
Scott Sun's avatar
Scott Sun committed
115
	if(!par.hasOwnProperty("config_path") || par.config_path==""){
Scott Sun's avatar
Scott Sun committed
116
		console.log("===================cfg");
Scott Sun's avatar
Scott Sun committed
117 118 119 120 121 122 123 124 125 126 127 128 129
		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}
		})
	});
Scott Sun's avatar
Scott Sun committed
130
	if(_.isEmpty(db_customer)){
Scott Sun's avatar
s  
Scott Sun committed
131 132
		script_info({ msg: "Find customer", result_severity:"error" });
		global._ERRORMAG = "No customer was found";
Scott Sun's avatar
Scott Sun committed
133
		throw "customer error"}
Scott Sun's avatar
Scott Sun committed
134 135 136 137 138 139 140 141 142 143 144
	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}
		})
	});
Scott Sun's avatar
Scott Sun committed
145
	if (!cfg || cfg == ""){
Scott Sun's avatar
s  
Scott Sun committed
146 147
		script_info({ msg: "Find  customer config", result_severity:"error" });
		global._ERRORMAG = "No customer config was found";
Scott Sun's avatar
Scott Sun committed
148
		throw "cfg can not find"}  
Scott Sun's avatar
Scott Sun committed
149
	var config = eval(cfg);
Scott Sun's avatar
Scott Sun committed
150
	if(!config.hasOwnProperty("customer")){
Scott Sun's avatar
s  
Scott Sun committed
151 152
		script_info({ msg: "Find  customer config", result_severity:"error" });
		global._ERRORMAG = "No customer config was found";
Scott Sun's avatar
Scott Sun committed
153
		throw "config error"}
Scott Sun's avatar
Scott Sun committed
154 155 156 157 158 159 160 161
	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
Scott Sun's avatar
s  
Scott Sun committed
162
	var step = custCfg.step.toLowerCase() || "cad";
Scott Sun's avatar
Scott Sun committed
163 164
	// 获取路径下文件信息
	var path = par.path
Scott Sun's avatar
Scott Sun committed
165
	if(!fs.exists(path)){
Scott Sun's avatar
s  
Scott Sun committed
166 167
		script_info({ msg: "Find PN folder", result_severity:"error" });
		global._ERRORMAG = "No PN file was found in folder";
Scott Sun's avatar
Scott Sun committed
168
		throw "path error"}
Scott Sun's avatar
Scott Sun committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182
	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
	// }
	var jobFile = pathInfo.filter(function(v){return v.baseName.toLowerCase() == job_file_baseName})
Scott Sun's avatar
Scott Sun committed
183
	if(jobFile.length == 0){
Scott Sun's avatar
s  
Scott Sun committed
184 185
		script_info({ msg: "Find PN folder", result_severity:"error" });
		global._ERRORMAG = "No PN file was found in folder";
Scott Sun's avatar
Scott Sun committed
186
		throw "job file is not exist"}
Scott Sun's avatar
Scott Sun committed
187 188 189 190 191 192
	var jobFiles = []  // 记录要分析的文件
	if (!jobFile[0].isDir) {
		jobFiles.push(jobFile[0])
	} else {
		jobFiles = fs.listDir(jobFile[0].path)
	}
Scott Sun's avatar
Scott Sun committed
193

Scott Sun's avatar
Scott Sun committed
194 195
	// 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
196 197
	
	// 将jobFile下的zip解压
Scott Sun's avatar
s  
Scott Sun committed
198 199
	script_info({ msg: "unzip the file", result_severity:"info" })
	global._ERRORMAG = "Failed to unzip the file";
Scott Sun's avatar
s  
Scott Sun committed
200

Scott Sun's avatar
Scott Sun committed
201 202 203 204 205
	var change_files = [];

	decompression(jobFile[0].path, [],change_files);

	changePath2(jobFile[0].path);
Scott Sun's avatar
s  
Scott Sun committed
206

Scott Sun's avatar
Scott Sun committed
207 208 209 210 211 212 213 214
	var job_attrs = db.query("",function(q){
		return q.selectValue({
			table:'pdm_job',
			field_format:{job_attrs:'json'},
			field:'job_attrs',
			where:{id : JobId}
		})
	});
Scott Sun's avatar
s  
Scott Sun committed
215
	if (!job_attrs ) { job_attrs = {}}
Scott Sun's avatar
Scott Sun committed
216
	job_attrs.readin_result = "Readin"
Scott Sun's avatar
Scott Sun committed
217 218 219 220 221 222 223 224
	db.query("",function(q){
		return q.updateRow({
			table:'pdm_job',
			data:{job_attrs:job_attrs},
			update_policy:{attr_data:'json_merge'},
			where:{id : JobId}
		})
	});
Scott Sun's avatar
Scott Sun committed
225
	
Scott Sun's avatar
Scott Sun committed
226
	jobFiles = fs.listDir(jobFile[0].path);
Scott Sun's avatar
Scott Sun committed
227
	
Scott Sun's avatar
Scott Sun committed
228 229
	// 分析料号文件 得到料号导入信息 导入类型
	var jobInfo = analyJobFiles({jobFiles:jobFiles.filter(function(v){return v.isFile}),custCfg:custCfg,config:config,job:job })
Scott Sun's avatar
Scott Sun committed
230
	if(jobInfo.data.length == 0){
Scott Sun's avatar
s  
Scott Sun committed
231 232
		script_info({ msg: "Find PN folder", result_severity:"error" });
		global._ERRORMAG = "No PN file was found in folder";
Scott Sun's avatar
Scott Sun committed
233
		throw "file error"}
Scott Sun's avatar
Scott Sun committed
234 235
	var importOk = false;  // 是否成功导入

Scott Sun's avatar
Scott Sun committed
236
	script_info({ progress: 10 ,result_severity:"ok", msg:""});
Scott Sun's avatar
Scott Sun committed
237

Scott Sun's avatar
Scott Sun committed
238
	if(/odb/ig.test(jobInfo.type)){  // odb导入
Scott Sun's avatar
s  
Scott Sun committed
239 240
		script_info({ msg: "Import odb++", result_severity:"error" });
		global._ERRORMAG = "Fail to import odb++";
Scott Sun's avatar
Scott Sun committed
241
		if(jobInfo.data.length == 1){  // 只分析到一个tgz文件 直接导入
Scott Sun's avatar
s  
Scott Sun committed
242 243 244 245 246 247 248 249
			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);
			// 将step改名cad
			var step_tmp = GEN.getStepList({job:job})[0];
			if(step_tmp != "cad"){
				GEN.renameStep({job:job,name:step_tmp,new_name:'cad'})
			}
Scott Sun's avatar
Scott Sun committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
			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 = [];
Scott Sun's avatar
Scott Sun committed
265 266
			// 分析arr_job 和 pcs_job;
			jobs = jobs.filter(function(v){return GEN.isJobExists({job:v.name})});
Scott Sun's avatar
Scott Sun committed
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
			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
						})
					}
				})
Scott Sun's avatar
Scott Sun committed
288
			});
Scott Sun's avatar
Scott Sun committed
289 290 291 292 293 294
			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
Scott Sun's avatar
Scott Sun committed
295
			})[0];
Scott Sun's avatar
Scott Sun committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
			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导入
Scott Sun's avatar
s  
Scott Sun committed
317 318
		script_info({ msg: "Import gerber", result_severity:"error" });
		global._ERRORMAG = "Fail to import gerber";
Scott Sun's avatar
Scott Sun committed
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
		GEN.createJob({name:job,db:custCfg.db});
		// GEN.COM("new_job,name="+job+",db="+custCfg.db+",customer=,disp_name=,notes=,attributes=")
		GEN.createStep({job:job,name:step});
		// GEN.renameStep({job:job,name:'org',new_name:'cad'})
		// GEN.COM("disp_on")
		// GEN.COM("origin_on")
		// GEN.COM("check_inout,mode=out,type=job,job="+job)
		// GEN.COM("check_inout,mode=out,type=job,job="+job)
		// GEN.COM("open_job,job="+job+",open_win=yes,disk_map=,job_map=")
		// GEN.COM("check_inout,job="+job+",mode=out,ent_type=job")
		// GEN.AUX("set_group,group=99")
		// GEN.COM("set_step,name=org")
		// GEN.COM("open_group,job="+job+",step=org,is_sym=no")
		// GEN.AUX("set_group,group=0")
		// GEN.COM("open_entity,job="+job+",type=step,name=org,iconic=no")
		// GEN.COM("set_subsystem,name=ReadIn")
		// GEN.COM("input_create,path=/incam_db/"+custCfg.db+"/jobs/"+job+"/input")
		// GEN.COM("open_job,job="+job+",open_win=yes,disk_map=,job_map=")
		// GEN.COM("disp_on")
		// GEN.COM("origin_on")
		// GEN.COM("disp_on")
		// GEN.COM("origin_on")
		// GEN.COM("create_entity,job="+job+",name="+step+",db=,is_fw=no,type=step,fw_type=form")
		// GEN.COM("disp_on")
		// GEN.COM("origin_on")
		// GEN.COM("disp_on")
		// GEN.COM("origin_on")
		// GEN.COM("show_tab,tab=Script,show=yes")

		jobInfo.data = jobInfo.data.filter(function(v){
			return v.format
		})
Scott Sun's avatar
Scott Sun committed
351 352 353
		var gerberInfo = jobInfo.data.map(function(item){
			var gerberCfg = JSON.parse(JSON.stringify(item.format));
			var file = item.file
Scott Sun's avatar
Scott Sun committed
354
			gerberCfg.layer = file.name.toLowerCase().split(" ").join("-").replace(/[()]/ig,"_")
Scott Sun's avatar
Scott Sun committed
355 356 357 358 359 360
			gerberCfg.path = file.path
			gerberCfg.format = item.type
			gerberCfg.job = job
			gerberCfg.step = step
			return gerberCfg
		})
Scott Sun's avatar
Scott Sun committed
361
		if(GEN.GEN_TYPE == "genesis"){
Scott Sun's avatar
Scott Sun committed
362
			GEN.COM("input_manual_reset")
Scott Sun's avatar
Scott Sun committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
			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")
			})
		} else {
			gerberInfo.forEach(function(v){
				GEN.COM("input_result_reset,step=,category=warnings,close_tab=yes")
				GEN.COM("input_create,path="+v.path)
				GEN.COM("input_selected_reset")
				GEN.COM("input_selected_add,path="+v.path)
				GEN.COM("input_identify_selected,path=,job="+job+",script_path=,gbr_ext=no,drl_ext=no,gbr_units=auto,drl_units=auto,unify=yes,break_sr=yes,gbr_wtp_filter=*,drl_wtp_filter=*,gbr_wtp_units=auto,drl_wtp_units=auto,wtp_dir=,have_wheels=yes,wheel=,gbr_consider_headlines=yes,drl_consider_headlines=yes,board_size_x=0,board_size_y=0")
	
				GEN.COM("input_manual_reset")
				import_info.push({name:v.layer, type:"gerber274x", date:now(),user:$.user_name})
				GEN.COM("input_manual_set",v)
				GEN.COM("input_manual")
			})
		}
Scott Sun's avatar
Scott Sun committed
382 383
		importOk = true
	}
Scott Sun's avatar
Scott Sun committed
384 385 386 387 388 389 390 391 392 393 394 395

	// [{
	// 	"ori_dirname": "/home/toplinker/samba/1352/13520028_128/TLK0802/1streceived20200422/zip_custom0",
	// 	"dirname": "/home/toplinker/samba/1352/13520028_128/TLK0802/1streceived20200422/custom1615366305861",
	// 	"newpath": "/home/toplinker/samba/1352/13520028_128/TLK0802/1streceived20200422/custom1615366305861.zip"
	// }, {
	// 	"ori_dirname": "/home/toplinker/samba/1352/13520028_128/TLK0802/1streceived20200422/custom1615366305861/sh1scmnrlmSMD_VB",
	// 	"dirname": "/home/toplinker/samba/1352/13520028_128/TLK0802/1streceived20200422/custom1615366305861/custom1615366305954",
	// 	"newpath": "/home/toplinker/samba/1352/13520028_128/TLK0802/1streceived20200422/custom1615366305861/custom1615366305954.zip"
	// }]

	change_files.reverse().forEach(function(item){
Scott Sun's avatar
Scott Sun committed
396 397 398
		fs.unlink(item.newpath)
		if(item.dirname != item.ori_dirname && fs.exists(item.ori_dirname)){
			fs.rmdir(item.ori_dirname);
Scott Sun's avatar
Scott Sun committed
399 400 401
		}
		fs.rename(item.dirname, item.ori_dirname);
	})
Scott Sun's avatar
Scott Sun committed
402
	if(!importOk){ throw "import error"}
Scott Sun's avatar
Scott Sun committed
403 404

	script_info({ progress: 20 ,result_severity:"ok", msg:""});
Scott Sun's avatar
Scott Sun committed
405

Scott Sun's avatar
s  
Scott Sun committed
406
	global._ERRORMAG = null;
Scott Sun's avatar
Scott Sun committed
407
	reNameStep(job)
Scott Sun's avatar
Scott Sun committed
408
	if(/2171/.test(par.customer)){
Scott Sun's avatar
Scott Sun committed
409 410 411 412 413 414 415 416 417 418
		// 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
419
	} else if ((/yucca/ig.test(par.customer))) {
Scott Sun's avatar
Scott Sun committed
420 421 422 423 424 425
		// var matrix = GEN.getMatrix({job:job,type:"array"})
		// matrix.layer_type.forEach(function(v, i){
		// 	if( v == "document") {
		// 		GEN.COM("matrix_layer_type,job="+job+",matrix=matrix,layer="+matrix.name[i]+",type=signal")
		// 	}
		// })
Scott Sun's avatar
Scott Sun committed
426
	}
Scott Sun's avatar
Scott Sun committed
427 428
	var steplist = GEN.getStepList({job:job})
	GEN.openStep({job:job,name:steplist[0]})
Scott Sun's avatar
s  
Scott Sun committed
429 430
	// 额外操作
	if (custCfg.extra) {
Scott Sun's avatar
Scott Sun committed
431
		global._extra = true; 
Scott Sun's avatar
s  
Scott Sun committed
432
		custCfg.extra.forEach(function(item){
Scott Sun's avatar
Scott Sun committed
433 434 435 436 437 438 439 440
			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
441 442
		})
	}
Scott Sun's avatar
Scott Sun committed
443
	GEN.closeStep()
Scott Sun's avatar
Scott Sun committed
444 445 446 447 448
	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
449 450
	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){
Scott Sun's avatar
Scott Sun committed
451 452 453 454
		var name = item.name;
		var type = item.type;
		var date = item.date;
		var user = item.user;
Scott Sun's avatar
Scott Sun committed
455 456 457
		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
458
    // name type date user
Scott Sun's avatar
Scott Sun committed
459
    resultData.push({type: "info",title:"导入资料列表",detail: [{ desc: import_html }] })
Scott Sun's avatar
Scott Sun committed
460
	script_info({ msg: "Data Readin" ,result_severity:"ok"})
Scott Sun's avatar
Scott Sun committed
461

Scott Sun's avatar
Scott Sun committed
462 463 464 465
	if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
Scott Sun's avatar
Scott Sun committed
466
				progress: 30
Scott Sun's avatar
Scott Sun committed
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
			},
			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) {
Scott Sun's avatar
Scott Sun committed
489
	script_info({ result_severity: "error",msg:"" })
Scott Sun's avatar
s  
Scott Sun committed
490
	if(global._ERRORMAG){
Scott Sun's avatar
s  
Scott Sun committed
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
		script_info({ msg: global._ERRORMAG });
		var job_attrs = db.query("",function(q){
			return q.selectValue({
				table:'pdm_job',
				field_format:{job_attrs:'json'},
				field:'job_attrs',
				where:{id : JobId}
			})
		});
		if (!job_attrs ) { job_attrs = {}}
		job_attrs.readin_result = global._ERRORMAG
		db.query("",function(q){
			return q.updateRow({
				table:'pdm_job',
				data:{job_attrs:job_attrs},
				update_policy:{attr_data:'json_merge'},
				where:{id : JobId}
			})
		});
Scott Sun's avatar
s  
Scott Sun committed
510
	}
Scott Sun's avatar
Scott Sun committed
511 512 513 514 515
	IKM.crud("deleteRow", {
		table: "pdm_job_jobattr",
		where:{job_id:JobId, attr_name:"cam_workflow_info"},
	})
	IKM.save_job_info({jobid:JobId, jobinfohash:{cam_workflow_info:"err"}})
Scott Sun's avatar
Scott Sun committed
516

Scott Sun's avatar
Scott Sun committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
    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"
        }
    }
}
Scott Sun's avatar
Scott Sun committed
537

Scott Sun's avatar
Scott Sun committed
538 539 540 541 542 543
function analyJobFiles(props){
	var files = props.jobFiles;
	var config = props.config;
	var job = props.job;
	var custCfg = props.custCfg;
	var rules = custCfg.rules;
Scott Sun's avatar
Scott Sun committed
544
	var paramsFile = files.filter(function(file){return /nc_param|ncdrill/ig.test(file.baseName)})
Scott Sun's avatar
Scott Sun committed
545 546 547
	var tmp_hash = {}
	paramsFile.forEach(function(file){
		tmp_hash[file.baseName] = (function(){
Scott Sun's avatar
Scott Sun committed
548
			var tmparr = fs.readFile(file.path).split("\n").filter(function(v){return /^\s?\S+\s+\S/ig.test(v)}).filter(function(v){return !/\(/.test(v)})
Scott Sun's avatar
Scott Sun committed
549 550 551
			var tmp = {}
			tmparr.map(function(v){
				var arr = v.split(/\b\s+\b/)
Scott Sun's avatar
Scott Sun committed
552
				tmp[arr[0].replace(/-/ig,"_").trim()] = arr[1]
Scott Sun's avatar
Scott Sun committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
			})
			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
		}
	}
}
Scott Sun's avatar
Scott Sun committed
592

Scott Sun's avatar
Scott Sun committed
593 594 595 596 597 598 599 600 601 602 603
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";
        }
	}
Scott Sun's avatar
Scott Sun committed
604
	props.path = changePath(props.path)
Scott Sun's avatar
s  
Scott Sun committed
605
	// 如果path的tgz不符合规范 纠正一下
Scott Sun's avatar
Scott Sun committed
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
    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
629
	if(!stepList){return}
Scott Sun's avatar
Scott Sun committed
630 631
	var pcs = [];
	var arr = [];
Scott Sun's avatar
Scott Sun committed
632
	stepList.forEach(function(v){
Scott Sun's avatar
Scott Sun committed
633 634 635 636 637 638 639 640
		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
641 642 643 644 645 646 647 648 649 650 651 652 653 654
		}
	})
	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
655 656 657 658 659 660 661 662 663 664
}

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
665 666
}

Scott Sun's avatar
Scott Sun committed
667
function decompression(path, zips, change_files) {
Scott Sun's avatar
Scott Sun committed
668 669
	var files = fs.listDir(path)
	var zipfiles = files.filter(function(item){
Scott Sun's avatar
Scott Sun committed
670
		if (/zip/ig.test(item.suffix) || item.suffix == "rar" || item.suffix=="7z") {
Scott Sun's avatar
Scott Sun committed
671 672 673
			inputState.push(item.suffix);
			console.log("--->path:" + item.path)
			if(zips.indexOf(item.path) < 0){
Scott Sun's avatar
s  
Scott Sun committed
674
				zips.push(item.path);
Scott Sun's avatar
Scott Sun committed
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
				//if(item.name.length >= 30 && !/�|\?/.test(item.name)) {
				if(/[^\da-zA-Z_]/.test(item.name)){
					var tmp_code = new Date().getTime()
					var ori_dirname = item.path.replace(/\.(zipx|zip|7z|rar)$/ig, "");
					var mvname = "custom" + tmp_code + "." + item.suffix;
					// fs.rename(item.path, item.dir + "/" + mvname); 
					fs.copyFile(item.path,item.dir + "/" + mvname,true);
					item.path = item.dir + "/" + mvname;

					change_files.push({
						ori_dirname: ori_dirname,
						dirname: item.path.replace(/\.(zipx|zip|7z|rar)$/ig, ""),
						newpath: item.path   // 后续删除
					})

					zips.push(item.path);
Scott Sun's avatar
Scott Sun committed
691
				}
Scott Sun's avatar
Scott Sun committed
692
				var dir_name = item.path.replace(/\.(zipx|zip|7z|rar)$/ig, "");
Scott Sun's avatar
Scott Sun committed
693
				autoUn(item.path, dir_name,item.dir);
Scott Sun's avatar
Scott Sun committed
694
				return true
Scott Sun's avatar
Scott Sun committed
695
			}
Scott Sun's avatar
Scott Sun committed
696
		}
Scott Sun's avatar
s  
Scott Sun committed
697 698 699 700 701 702 703 704 705
		//  else if(/7z/.test(item.completeSuffix)){
		// 	inputState.push("7z");
		// 	if(zips.indexOf(item.path) < 0){
		// 		zips.push(item.path);
		// 		var dir_name = item.path.replace(".7z", "");
		// 		autoUn(item.path, dir_name);
		// 		return true
		// 	}
		// }
Scott Sun's avatar
Scott Sun committed
706 707
		return false
	})
Scott Sun's avatar
Scott Sun committed
708
	if(zipfiles.length) {decompression(path, zips, change_files)}
Scott Sun's avatar
Scott Sun committed
709 710 711 712 713
}

function changePath(path) {
    return path.replace(/[^/]+\//ig, function(v){
        if(v.length >= 10 && /\s/ig.test(v)) {
Scott Sun's avatar
Scott Sun committed
714
            v = v.replace(" ", "\\ ");
Scott Sun's avatar
Scott Sun committed
715 716 717 718 719
            return v.slice(0,6) + "~1/"
        } else {
            return v
        }
    })
Scott Sun's avatar
Scott Sun committed
720 721
}

Scott Sun's avatar
Scott Sun committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
function autoUn(path, dirname, dir) {
	// 解压密码逻辑 先获取 /home/toplinker/samba/unzip_pwd.txt
	var pw = "/home/toplinker/samba/unzip_pwd.txt";
	var pws = fs.readFile(pw);

	var strs = pws.split("\n")
	var ret = {};
	strs.map(function(v) {
		var tmp = v.split(/\s+/);
		ret[tmp[0].trim()] = tmp[1].trim()
	});
	var pwd;
	if(ret[Job]){
		pwd = ret[Job]
	}

	if(fs.exists(dir + "/pw.txt")){
		pwd = fs.readFile(dir + "/pw.txt");
	}

Scott Sun's avatar
Scott Sun committed
742
    if(/\.rar$/.test(path)){
Scott Sun's avatar
Scott Sun committed
743 744 745
		fs.mkdir(dirname);
		
		if(pwd){
Scott Sun's avatar
Scott Sun committed
746
			process.exec('/opt/rar/unrar', ['x' , path, dirname, "-o+","-p"+pwd]);
Scott Sun's avatar
Scott Sun committed
747 748 749
		} else {
			process.exec('/opt/rar/unrar', ['x' , path, dirname, "-o+"])
		}
Scott Sun's avatar
Scott Sun committed
750
    } else {
Scott Sun's avatar
Scott Sun committed
751 752 753 754 755
		if(pwd){
			process.exec('/usr/local/lib/p7zip/7za', ['x' , path, "-o"+dirname, "-aoa", "-p"+pwd])
		} else {
			process.exec('/usr/local/lib/p7zip/7za', ['x' , path, "-o"+dirname, "-aoa"])
		}
Scott Sun's avatar
Scott Sun committed
756
    }
Scott Sun's avatar
Scott Sun committed
757 758 759
}

function exportInfo(info){
Scott Sun's avatar
s  
Scott Sun committed
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    fs.writeFile("/home/toplinker/samba/Test_Scott/tmp", _.toString(info))
}

function changePath2(filePath){
    var fileList = fs.listDir(filePath);
    var tmp = [];
    for(var i = 0;i<fileList.length;i++){
        if(fileList[i].isDir){
            var path = fileList[i].path;
            var fileName = fileList[i].baseName;
            var obj = {
                path:path,
                fileName:fileName
            }
        tmp.push(obj);
        }  
    }
    for(var i = tmp.length-1;i>=0;i--){
        var newFileName = tmp[i].fileName.replace(/\s*/g,'');//去除文件名中空格
        newFileName = newFileName.replace(/\?/g,'');//去除文件名中?
Scott Sun's avatar
Scott Sun committed
780
		var newPath = tmp[i].path.replace(/^(.*)\/[^\/]*$/,"$1");
Scott Sun's avatar
Scott Sun committed
781
        if(tmp[i].path != (newPath+'/'+newFileName)){
Scott Sun's avatar
Scott Sun committed
782 783
			// fs.rmdir(newPath+'/'+newFileName)
			// fs.rename(newPath+'/'+newFileName, newPath+'/'+newFileName+"_bk");
Scott Sun's avatar
Scott Sun committed
784 785 786
			fs.rename(tmp[i].path,newPath+'/'+newFileName);
		}
	}
Scott Sun's avatar
Scott Sun committed
787
}