# -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab import json import subprocess import time import datetime import uuid import Activity import Converter import m7z_mod import notify_activity import status_mod import FileIface __author__ = 'frank' import FilePaths import fsio from collections import OrderedDict # Fake globals for syntax check if False: response = None request = None session = None db = None status_mod.sessionUserMgr.setLastVisit(session, request) categoryMap = { -1: "System", 0: "All", 1: "1: Tightening", 2: "2: Prelim. torque", 3: "3: End torque", 4: "4: Loosen", 5: "5: Rework", 6: "6: Function A", 7: "7: Function B", 8: "8: Function C", 9: "9: Function D", 10: "10: Function E", 11: "11: Start" } reversedCategoryMap = dict((v, k) for k, v in categoryMap.iteritems()) def transferCategory(currentQCode, el): if el.get('categoryList') is None or len(el.get('categoryList')) == 0: if el.get('RdOnly') == True: currentQCode["Category"] = [-1] else: currentQCode["Category"] = [0] elif len(el.get('categoryList')) == 1: if el.get('categoryList')[0].get('data').get('value') == "All": currentQCode["Category"] = [0] if el.get('categoryList')[0].get('data').get('value') == "System": currentQCode["Category"] = [-1] else: currentQCode["Category"] = [reversedCategoryMap.get(el.get('categoryList')[0].get('data').get('value'))] else: currentQCode["Category"] = [] for c in el.get('categoryList'): if not c.get('data').get('value') in ["All", "System"]: currentQCode["Category"].append(reversedCategoryMap.get(c.get('data').get('value'))) @auth.requires(request.ajax==True, requires_login=True) def qcodes(): if request.env.request_method == "GET": qcode = fsio.jsonload(FilePaths.QCODE_FILENAME) id = 0 res = {} res['qcodes'] = [] # qcode['Quality codes'] res['rcodes'] = [] # Rework codes rcodeId = 1 for rc in qcode['Rework codes']: res['rcodes'].append({ 'id': rcodeId, 'instruction': rc }) rcodeId += 1 id = 0 for qc in qcode['Quality codes']: if qc.get('Category') == None: if qc['RdOnly'] == True: qc['Category'] = [-1] else: qc['Category'] = [0] id += 1 entry = { 'reworkCode': int(qc['Rework code']), 'id': id, 'RdOnly': qc['RdOnly'], 'qcode': qc['Id'], 'category': ", ".join(map(lambda a: categoryMap.get(a), qc['Category'])), 'categoryList': qc['Category'], 'mfAllOther': qc['All Other MF OK'], } if len(qc['Category']) == 1 and qc['Category'][0] == 0 and qc['RdOnly'] is True: entry['category'] = "System" entry['categoryList'] = [-1] if 'MF NOK' in qc: entry['mfNok'] = ", ".join(qc['MF NOK']) entry['mfNokList'] = map(lambda a: {'value': a}, qc['MF NOK']) if 'MF OK' in qc: entry['mfOk'] = ", ".join(qc['MF OK']) entry['mfOkList'] = map(lambda a: {'value': a}, qc['MF OK']) else: entry['mfOk'] = "" entry['mfOkList'] = [] res['qcodes'].append(entry) return response.json(res) if request.env.request_method == "POST": data = json.loads(request.body.read()) filedata = fsio.jsonload(FilePaths.QCODE_FILENAME) res = {'Quality codes': [], "Rework codes": filedata.get('Rework codes')} for el in data: mfNokRes = [] for n in el.get('mfNokList'): mfNokRes.append(n.get('data').get('value')) mfOkRes = [] for n in el.get('mfOkList'): mfOkRes.append(n.get('data').get('value')) currentQCode = {'Id': el.get("qcode"), "RdOnly": el.get('RdOnly'), "Rework code": el.get('reworkCode'), "All Other MF OK": Converter.toBoolean(el.get("mfAllOther"))} if len(mfNokRes) > 0: currentQCode["MF NOK"] = mfNokRes if len(mfOkRes) > 0: currentQCode["MF OK"] = mfOkRes transferCategory(currentQCode, el) res.get('Quality codes').append(currentQCode) if len(el.get('categoryList')) == 0: if el.get('RdOnly') == True: el.get('categoryList').append(-1) else: el.get('categoryList').append(0) sort_order = ['Id', 'RdOnly', 'Rework code', 'MF NOK', 'MF OK', 'All Other MF OK', 'Category'] res['Quality codes'] = [OrderedDict(sorted(item.iteritems(), key=lambda (k, v): sort_order.index(k))) for item in res.get('Quality codes')] fsio.jsondump(FilePaths.QCODE_FILENAME, res) notify_activity.configChanged(FilePaths.QCODE_FILENAME, Activity.QCODE_CHANGED, session=session) @auth.requires(request.ajax==True, requires_login=True) def rcodes(): if request.env.request_method == "GET": data = fsio.jsonload(FilePaths.QCODE_FILENAME) rcodes = data.get('Rework codes') result = [[0, "0:"]] i = 1 for rcode in rcodes: result.append([i, str(i) + ": " + rcode]) i += 1 return response.json(result) if request.env.request_method == "POST": data = json.loads(request.body.read()) newdata = [] for e in data: newdata.append(e.get('instruction')) filedata= fsio.jsonload(FilePaths.QCODE_FILENAME) filedata['Rework codes'] = newdata fsio.jsondump_sorted(FilePaths.QCODE_FILENAME, filedata) notify_activity.configChanged(FilePaths.QCODE_FILENAME, Activity.QCODE_CHANGED, session=session) @auth.requires_login() def importQCodes(): session.forget(response) res = {'success': True, 'msg': ''} fsio.fsXngLock.acquire() try: UUID = uuid.uuid4() with open('/tmp/{0}.zip'.format(UUID.hex), 'w') as f: f.write(request.vars.cfg.value) pwd = FilePaths.gen_rev_pwd(FileIface.CFG_LIST_QCODE) returncode = m7z_mod.test_pwd('/tmp/{0}.zip'.format(UUID.hex), pwd) if returncode != 0: return response.json(m7z_mod.get_import_impossible_msg()) p = subprocess.Popen([FilePaths.SEVEN_ZIP_BIN, "e", '/tmp/{0}.zip'.format(UUID.hex), "-o{0}".format(FilePaths.CONFIG_PATH), "-p{0}".format(pwd), "-y"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode != 0: # Failure res['success'] = False res['msg'] = str(stderr) if res['success']: notify_activity.configChanged(FilePaths.QCODE_FILENAME, Activity.QCODE_CHANGED, session=session) except Exception, e: res['success'] = False res['msg'] = str(e) finally: fsio.fsXngLock.release() return response.json(res) def __genExportFileName(): name = 'qcodes' ts = time.time() dateStamp = datetime.datetime.fromtimestamp(ts).strftime('%Y_%m_%d') return dateStamp + '_' + name.strip() + '.nxqc' @auth.requires(request.ajax==True, requires_login=True) def exportQCodes(): session.forget(response) expfname = __genExportFileName() res = {'success': False, 'msg': 'Unknown error'} fsio.fsXngLock.acquire() try: res = {'success': True, 'msg': '/tmp/' + expfname} pwd = FilePaths.gen_rev_pwd(FileIface.CFG_LIST_QCODE) p = subprocess.Popen([FilePaths.SEVEN_ZIP_BIN, "u", "/tmp/" + expfname, "-p"+pwd, "/home/tool/config/QCode.json"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode != 0: # Failure res['success'] = False res['msg'] = str(stderr) except Exception, e: res['success'] = False res['msg'] = str(e) finally: fsio.fsXngLock.release() return response.json(res) @auth.requires(request.ajax==True, requires_login=True) def resetToFactory(): fsio.shcopyfile(FilePaths.QCODE_DEFAULT_FILENAME, FilePaths.QCODE_FILENAME) notify_activity.configChanged(FilePaths.QCODE_FILENAME, Activity.QCODE_CHANGED, session=session) return ''