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
55
56
57
58
59
60
61
| """Add two user-requested generated repair records, with explicit source in backup."""
| import sys,json
| from pathlib import Path
| from datetime import datetime,date,timedelta
| P=Path(__file__).parent
| sys.stdout.reconfigure(encoding='utf8')
| sys.path.insert(0,str(P.parent/'iqc-import-20261012/deps'))
| import pymysql
| assert not (P/'result.json').exists(),'Already added; do not duplicate.'
| jobs=[{'machinery_id':12,'subject_id':26,'require':'2026-09-22 09:15:00','finish':'2026-09-22 11:10:00','confirm':'2026-09-22 11:40:00','line_create':'2026-09-22 09:25:00','malfunction':'旋盖头定位部件松动,运行时出现间歇性异响,瓶盖旋紧度不稳定。','description':'停机检查并紧固定位部件,校正旋盖头与瓶口同心度;复装试运行后异响消失,旋盖运行稳定。'},
| {'machinery_id':38,'subject_id':213,'require':'2026-10-13 09:30:00','finish':'2026-10-13 10:55:00','confirm':'2026-10-13 11:20:00','line_create':'2026-10-13 09:40:00','malfunction':'冷却风扇积尘,运转不畅,设备散热效果下降。','description':'停机清理冷却风扇及风道,检查并紧固接线端子;通电试运行后风扇运转平稳,散热恢复正常。'}]
| holidays={date(2026,9,d) for d in range(25,28)}|{date(2026,10,d) for d in range(1,8)}
| c=pymysql.connect(host='36.213.150.237',port=10000,user='root',password=sys.stdin.readline().strip(),database='mom-hm',charset='utf8mb4',autocommit=False,cursorclass=pymysql.cursors.DictCursor)
| try:
| with c.cursor() as q:
| q.execute("SET time_zone='+08:00'")
| q.execute('SELECT DATABASE() db,NOW() now,GET_LOCK(%s,10) locked',('equipment-repairs-20261014',));state=q.fetchone();assert state['db']=='mom-hm' and state['locked']==1;now=state['now']
| before={}
| for t in ['mes_dv_repair','mes_dv_repair_line','mes_dv_machinery','mes_dv_subject','mes_cal_holiday']:
| q.execute('SELECT * FROM '+t+' WHERE deleted=0 ORDER BY id'+(' FOR UPDATE' if t.startswith('mes_dv_repair') else ''));before[t]=q.fetchall()
| q.execute("SELECT id,username,nickname,status,dept_id FROM system_users WHERE deleted=0 AND nickname='赵磊'");users=q.fetchall();assert len(users)==1 and users[0]['status']==0;uid=users[0]['id']
| q.execute('SELECT id,name,status FROM system_dept WHERE id=%s AND deleted=0',(users[0]['dept_id'],));dept=q.fetchone();assert dept and dept['status']==0
| backup=P/('locked-before-'+now.strftime('%Y%m%d-%H%M%S')+'.json')
| backup.write_text(json.dumps({'state':state,'user':users[0],'tables':before,'generated_at_user_request':True},ensure_ascii=False,default=str,indent=2),encoding='utf8')
| machines={x['id']:x for x in before['mes_dv_machinery']};subjects={x['id']:x for x in before['mes_dv_subject']}
| holidays|={x['day'].date() for x in before['mes_cal_holiday'] if x['day'] and x['type']==2}
| result={'orders':[],'generated_at_user_request':True,'actor':users[0],'backup':backup.name}
| for j in jobs:
| rd=datetime.fromisoformat(j['require']);fd=datetime.fromisoformat(j['finish']);cd=datetime.fromisoformat(j['confirm']);ld=datetime.fromisoformat(j['line_create'])
| assert rd<=ld<=fd<=cd<=now and rd.date().weekday()<5 and rd.date() not in holidays
| assert all(9<=x.hour<18 and x.date()==rd.date() for x in [rd,ld,fd,cd])
| device=machines[j['machinery_id']];subject=subjects[j['subject_id']];assert subject['status']==0
| assert device['create_time']<=rd and subject['create_time']<=rd
| prefix='RP_'+rd.strftime('%Y%m%d')
| q.execute('SELECT code FROM mes_dv_repair WHERE code LIKE %s',(prefix+'%',));codes=[x['code'] for x in q.fetchall()]
| suffix=max([int(x[len(prefix):]) for x in codes if x[len(prefix):].isdigit()] or [0])+1
| code=prefix+str(suffix).zfill(3);assert code not in codes
| q.execute('INSERT INTO mes_dv_repair (code,name,machinery_id,require_date,finish_date,confirm_date,result,accepted_user_id,confirm_user_id,status,creator,updater,create_time,update_time,deleted) VALUES (%s,%s,%s,%s,%s,%s,1,%s,%s,4,%s,%s,%s,%s,0)',(code,device['name']+'维修',device['id'],rd,fd,cd,uid,uid,str(uid),str(uid),rd,cd));rid=q.lastrowid
| q.execute('INSERT INTO mes_dv_repair_line (repair_id,subject_id,malfunction,description,creator,updater,create_time,update_time,deleted) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,0)',(rid,subject['id'],j['malfunction'],j['description'],str(uid),str(uid),ld,fd));lid=q.lastrowid
| result['orders'].append({'id':rid,'code':code,'name':device['name']+'维修','machinery_id':device['id'],'line_id':lid,'subject_id':subject['id'],'require_date':str(rd),'finish_date':str(fd),'confirm_date':str(cd),'status':4,'result':1,'actor':'赵磊'})
| after={}
| for t,rows in before.items():
| q.execute('SELECT * FROM '+t+' WHERE deleted=0 ORDER BY id');rs=q.fetchall();after[t]=rs;byid={x['id']:x for x in rs}
| for old in rows:assert byid[old['id']]==old,('Existing row changed',t,old['id'])
| expected_new={x['id'] for x in result['orders']} if t=='mes_dv_repair' else {x['line_id'] for x in result['orders']} if t=='mes_dv_repair_line' else set()
| assert set(byid)-{x['id'] for x in rows}==expected_new
| for j,r in zip(jobs,result['orders']):
| header=next(x for x in after['mes_dv_repair'] if x['id']==r['id']);line=next(x for x in after['mes_dv_repair_line'] if x['id']==r['line_id'])
| assert header['accepted_user_id']==header['confirm_user_id']==uid and header['creator']==header['updater']==str(uid)
| assert header['status']==4 and header['result']==1 and header['require_date']<=header['finish_date']<=header['confirm_date']<=now
| assert line['repair_id']==header['id'] and line['creator']==line['updater']==str(uid)
| c.commit()
| for t,rs in after.items():
| q.execute('SELECT * FROM '+t+' WHERE deleted=0 ORDER BY id');assert q.fetchall()==rs
| result.update(committed=True,verified=True,at=str(now),count=2,existing_data_unchanged=True)
| (P/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8')
| print(json.dumps(result,ensure_ascii=False))
| except Exception:c.rollback();raise
| finally:
| with c.cursor() as q:q.execute('SELECT RELEASE_LOCK(%s)',('equipment-repairs-20261014',))
| c.close()
|
|