def out_note_delete(self): id = _g("id") if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for(".view", action = "out_note")) try: note = DBSession.query(InventoryOutNote).get(id) note.active = 1 for d in note.details: location_item = DBSession.query(InventoryLocationItem).filter(and_(InventoryLocationItem.active == 0, InventoryLocationItem.location_id == d.location_id, InventoryLocationItem.item_id == d.item_id)).with_lockmode("update").one() if note.status == 1 : # the record is not approved location_item.qty += d.qty location_item.area += d.area location_item.weight += d.weight location_item.exp_qty += d.qty location_item.exp_area += d.area location_item.exp_weight += d.weight DBSession.add(SystemLog( type = InventoryOutNote.__class__.__name__, ref_id = note.id, remark = u"%s 删除该记录。" % (session['user_profile']['name']) )) DBSession.commit() flash(MSG_DELETE_SUCC, MESSAGE_INFO) except: _error(traceback.print_exc()) DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for(".view", action = "out_note"))
def save_update(self): id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view')) obj = DBSession.query(Customer).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view')) try: fields = ['no', 'name', 'display_name', 'province_id', 'city_id', 'address', 'contact_person', 'mobile', 'phone', 'email', 'note_id', 'remark'] old_info = obj.serialize(fields) # to used for the history log for f in fields: setattr(obj, f, _g(f)) #handle the file upload old_attachment_ids = map(lambda (k, v) : v, _gp("old_attachment_")) old_attachment_ids.extend(multiupload()) obj.attachment = old_attachment_ids DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) # return redirect(url_for('.view',id=obj.id)) new_info = obj.serialize(fields) change_result = obj.compare(old_info, new_info) obj.insert_system_logs(change_result) except: _error(traceback.print_exc()) DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view', action = "view", id = obj.id))
def save_new(self): params = { "name" : _g('name'), "address" : _g('address'), "manager" : _g('manager'), "remark" : _g('remark'), "parent_id" : _g('parent_id'), } try: obj = InventoryLocation(**params) DBSession.add(obj) DBSession.flush() if params['parent_id']: parent = DBSession.query(InventoryLocation).get(obj.parent_id) obj.full_path = "%s%s" % (parent.full_path or '', params['name']) obj.full_path_ids = "%s|%s" % (parent.full_path_ids, obj.id) else: obj.full_path = params['name'] obj.full_path_ids = obj.id DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) except: DBSession.rollback() _error(traceback.print_exc()) return redirect(self.default())
def init(): try: print "create tables" metadata.drop_all(engine, checkfirst = True) metadata.create_all(engine) print "insert default value" DBSession.add(User(name = 'demo', password = '******')) for code in range(9121, 9140): DBSession.add(NFCData(authcode = unicode(code), company = 'RoyalDragonVodka', serial = code - 9000, )) f = open('country.txt', 'r') cs = f.readlines() f.close() for c in cs: n, c, iso = c.split('|') DBSession.add(MLocation(name = n, iso_code = iso, code = c)) DBSession.commit() print "finish init!" except: traceback.print_exc() DBSession.rollback()
def save_new(self): try: obj = Customer( no = _g('no'), name = _g('name'), display_name = _g('display_name'), province_id = _g('province_id'), city_id = _g('city_id'), address = _g('address'), contact_person = _g('contact_person'), mobile = _g('mobile'), phone = _g('phone'), email = _g('email'), remark = _g('remark'), note_id = _g('note_id'), # payment_id = _g('payment_id'), ) DBSession.add(obj) obj.attachment = multiupload() DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'view', id = obj.id)) except: _error(traceback.print_exc()) DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view'))
def save_events(): uid = request.values.get("uid", None) did = request.values.get("did", None) d = request.values.get("d", None) t = request.values.get("t", None) if not uid or not did or not d or not t: return jsonify({"success": False, "message": "The required info is not supplied !"}) format_date = lambda v: "-".join([v[:4], v[4:6], v[-2:]]) try: e = Events(user_id=uid, doctor_id=did, date=d, time=t, remark=request.values.get("remark", None)) DBSession.add(e) doctor = DBSession.query(DoctorProfile).get(did).getUserProfile() m = Message( subject=u"Booking request submit", user_id=session["user_profile"]["id"], content=u"%s make a booking with doctor %s at %s , %s." % (session["user_profile"]["name"], doctor["name"], t, format_date(d)), ) DBSession.add(m) DBSession.commit() return jsonify({"success": True, "message": "Save your request successfully !", "event_time": e.time}) except: DBSession.rollback() app.logger.error(traceback.format_exc()) return jsonify({"success": False, "message": "Error occur when submiting the request !"})
def upload(self, file_name): try: f = self.request.files[file_name][0] original_fname = f['filename'] extension = os.path.splitext(original_fname)[1].lower() fname = Date2Text(dateTimeFormat = "%Y%m%d%H%M%S", defaultNow = True) + ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6)) final_filename = fname + extension d = os.path.join(self.application.settings.get("static_path"), self.application.settings.get("upload_relative_path")) if not os.path.exists(d): os.makedirs(d) full_path = os.path.join(d, final_filename) output_file = open(full_path, 'wb') output_file.write(f['body']) output_file.close() DBSession.add(Attachment(name = final_filename, path = full_path, original_name = original_fname, url = self.static_url("/".join([self.application.settings.get("upload_relative_path"), final_filename])))) DBSession.commit() return (0, original_fname, final_filename, full_path) except: DBSession.rollback() logging.error(traceback.print_exc()) return (1, None, None, None)
def saveNewArticle(self): appid, title, sub_title, validate_date, desc, content = _gs('appid', 'title', 'sub_title', 'validate_date', 'desc', 'content') if not appid : flash(MSG_NO_ID_SUPPLIED, MESSAGE_WARNING) return redirect(url_for('.view')) if not title: flash(MSG_NO_ENOUGH_PARAMS, MESSAGE_WARNING) return redirect(url_for('.view', action = 'createArticle', appid = appid)) try: article = AppArticle( app_id = appid, title = title, sub_title = sub_title, desc = desc, content = content, validate_date = validate_date, ) DBSession.add(article) DBSession.flush() article.seq = article.id DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) return redirect(url_for(".view", action = "listArticle", appid = appid)) except: DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) traceback.print_exc() return redirect(url_for(".view", action = "listArticle", appid = appid))
def saveNewApp(self): appName, appDesc = _gs('appName', 'appDesc') if not appName: flash(MSG_NO_APP_NAME, MESSAGE_WARNING) return redirect(url_for('.view', action = 'createApp')) try: DBSession.query(AppObject).filter(and_(AppObject.active == 0, AppObject.name == appName)).one() except: try: app = AppObject(name = appName, desc = appDesc) DBSession.add(app) DBSession.flush() url = createApp(session['user_profile']['id'], APP_FOLDER, APP_PACKAGE, 'app%s' % app.id, app.name) if not url : raise Exception('App generation error!') url = '%s%s' % (WEBSITE_ROOT, url) imgFile = createQR(url) if not imgFile : raise Exception('QR code generation error!') DBSession.add(imgFile) app.appfile = imgFile DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) self._updateAppInSession() return redirect(url_for('.view')) except: DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view')) else: flash(MSG_APP_NAME_DUPLICATED, MESSAGE_WARNING) return redirect(url_for('.view', action = 'createApp'))
def _save_new(self): try: result = self.dbObj.save_new(self) DBSession.commit() self.flash("Save the record successfully!") except Exception as e: DBSession.rollback() self.flash(getattr(e, "msg", None) or "This operation is not available now!") self._new() self.redirect("%s?action=view&id=%d" % (self.url_prefix, result.id))
def ajax_change_flag(self): try: ids = _g('order_ids', '').split("|") flag = _g('flag') type = _g('type') for r in DBSession.query(OrderHeader).filter(OrderHeader.id.in_(ids)).order_by(OrderHeader.create_time): if type == 'APPROVE': r.approve = flag if flag == '1': # approve remark = u'%s 审核通过该订单。' % session['user_profile']['name'] else: # disapprove remark = u'%s 审核不通过该订单。' % session['user_profile']['name'] elif type == 'PAID': r.paid = flag if flag == '1': remark = u'%s 确认该订单为客户已付款。' % session['user_profile']['name'] else: remark = u'%s 确认该订单为客户未付款。' % session['user_profile']['name'] elif type == 'SUPLLIER_PAID': r.supplier_paid = flag if flag == '1': remark = u'%s 确认该订单为已付款予承运商。' % session['user_profile']['name'] else: remark = u'%s 确认该订单为未付款予承运商。' % session['user_profile']['name'] elif type == 'ORDER_RETURN': r.is_return_note = flag if flag == '1': remark = u'%s 确认该订单为客户已返回单。' % session['user_profile']['name'] else: remark = u'%s 确认该订单为客户未返回单。' % session['user_profile']['name'] elif type == 'EXCEPTION': r.is_exception = flag if flag == '1': remark = u'%s 标记该订单为异常。' % session['user_profile']['name'] else: remark = u'%s 取消该订单的异常标记。' % session['user_profile']['name'] elif type == 'LESS_QTY': r.is_less_qty = flag if flag == '1': remark = u'%s 标记该订单为少货。' % session['user_profile']['name'] else: remark = u'%s 取消该订单的少货标记。' % session['user_profile']['name'] DBSession.add(SystemLog( type = r.__class__.__name__, ref_id = r.id, remark = remark )) DBSession.commit() return jsonify({'code' : 0 , 'msg' : MSG_UPDATE_SUCC}) except: _error(traceback.print_exc()) DBSession.rollback() return jsonify({'code' : 1, 'msg' : MSG_SERVER_ERROR})
def insert_system_logs(self, comare_result): try: _remark = [u"[%s]'%s' 修改为 '%s'" % (name, ov, nv) for (name, ov, nv) in comare_result['update']] DBSession.add(SystemLog( type = self.__class__.__name__, ref_id = self.id, remark = u"%s 修改该记录。%s" % (session['user_profile']['name'], ";".join(_remark)) )) DBSession.commit() except: DBSession.rollback() _error(traceback.print_exc())
def init(): try: print "create tables" metadata.drop_all(engine, checkfirst = True) metadata.create_all(engine) DBSession.add(User(email = '*****@*****.**', password = '******')) DBSession.add(User(email = '*****@*****.**', password = '******')) DBSession.commit() print "finish init!" except: traceback.print_exc() DBSession.rollback()
def vendor_input_save(self): if not session.get('supplier_profile', None) or not session['supplier_profile'].get('id', None): flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR) return redirect(url_for('bpRoot.view', action = "index")) header = DeliverHeader.get(_g('id')) if not header : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = 'vendor_select')) elif header.supplier_id != session['supplier_profile']['id']: flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR) return redirect(url_for('bpRoot.view', action = "index")) if _g('type') == "IN_TRAVEL" : new_status = IN_TRAVEL[0] remark = u'货物在途。备注 :%s' % _g('remark') elif _g('type') == "GOODS_ARRIVED" : new_status = GOODS_ARRIVED[0] remark = u'货物到达。备注 :%s' % _g('remark') elif _g('type') == "GOODS_SIGNED" : new_status = GOODS_SIGNED[0] remark = u'货物签收。备注 :%s' % _g('remark') else: flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR) return redirect(url_for('.view', action = 'vendor_select')) try: header.update_status(new_status) for d in header.details: d.order_detail.update_status(new_status) # log = DeliverLog(deliver_header_id = header.id, remark = _g('remark')) # DBSession.add(log) DBSession.add(TransferLog( refer_id = header.id, transfer_date = dt.now().strftime(SYSTEM_DATETIME_FORMAT), type = 1, remark = remark )) DBSession.commit() except: DBSession.rollback() _error(traceback.print_exc()) flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view', action = 'vendor_select')) else: flash(MSG_SAVE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'vendor_select'))
def delArticle(self): aid = _g('id') if not aid : flash(MSG_NO_ID_SUPPLIED, MESSAGE_WARNING) return redirect(url_for('.view')) try: article = DBSession.query(AppArticle).get(aid) article.active = 1 DBSession.commit() flash(MSG_DELETE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'listArticle', appid = article.app_id)) except: DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view', action = 'updateArticle', id = aid))
def delApp(self): appid = _g('id') try: app = DBSession.query(AppObject).filter(and_(AppObject.id == appid, AppObject.create_by_id == session['user_profile']['id'])).one() except: flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view')) try: app.active = 1 DBSession.commit() self._updateAppInSession() flash(MSG_DELETE_SUCC, MESSAGE_INFO) except: DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view'))
def saveApp(self): appid, appDesc = _gs('id', 'appDesc') try: app = DBSession.query(AppObject).filter(and_(AppObject.id == appid, AppObject.create_by_id == session['user_profile']['id'])).one() except: flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view')) try: app.desc = appDesc DBSession.commit() flash(MSG_UPDATE_SUCC, MESSAGE_INFO) except: DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view'))
def out_note_save_new(self): params = {} for f in ["customer_id", "so", "po", "dn", "ref", "remark", ]: params[f] = _g(f) try: header = InventoryOutNote(**params) DBSession.add(header) DBSession.flush() total_qty = total_area = total_weight = 0 for k, id in _gp("item_"): tmp_qty = int(_g('qty_%s' % id) or 0) tmp_area = float(_g('area_%s' % id) or 0) tmp_weight = float(_g('weight_%s' % id) or 0) total_qty += tmp_qty total_area += tmp_area total_weight += tmp_weight tmp_location_item = DBSession.query(InventoryLocationItem).get(id) tmp_location_item.exp_qty -= tmp_qty tmp_location_item.exp_area -= tmp_area tmp_location_item.exp_weight -= tmp_weight DBSession.add(InventoryNoteDetail( header_id = header.id, type = 'OUT', item_id = tmp_location_item.item_id, desc = tmp_location_item.item.desc, qty = tmp_qty, weight = tmp_weight, area = tmp_area, remark = _g('remark_%s' % id), location_id = tmp_location_item.location_id, )) header.qty = total_qty header.weight = total_weight header.area = total_area header.no = getOutNo(header.id) DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = "out_note_review", id = header.id)) except: DBSession.rollback() _error(traceback.print_exc()) flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for(".view", action = "index"))
def ajax_save_discount(self): id = _g('id') if not id: return jsonify({'code' : 1 , 'msg' : MSG_NO_ID_SUPPLIED}) header = DBSession.query(OrderHeader).get(id) if not header: return jsonify({'code' : 1 , 'msg' : MSG_RECORD_NOT_EXIST}) try: for f in ['discount_return_time', 'discount_return_person_id', 'discount_return_remark', 'actual_proxy_charge']: setattr(header, f, _g(f)) header.is_discount_return = 1 DBSession.commit() return jsonify({'code' : 0 , 'msg' : MSG_SAVE_SUCC}) except: DBSession.rollback() _error(traceback.print_exc()) return jsonify({'code' : 1 , 'msg' : MSG_SERVER_ERROR})
def addComment(): fields = ["lang", "doctorID", "userID", "comment"] if _check_params(fields) != 0: return jsonify({"result": 0, "msg": MSG_PARAMS_MISSING}) doctorID = _g("doctorID") userID = _g("userID") comment = _g("comment") if not doctorID or not userID or not comment: return jsonify({"result": 0, "msg": MSG_PARAMS_EMPTY}) try: DBSession.add(DoctorComment(doctor_id=doctorID, content=comment, create_by_id=doctorID)) DBSession.commit() return jsonify({"result": 1, "msg": MSG_SAVE_SUCCESS}) except: DBSession.rollback() return jsonify({"result": 0, "msg": MSG_SERVER_ERROR})
def ajax_change_flag(self): try: id = _g('id') flag = _g('flag') type = _g('type') remark = None header = DBSession.query(DeliverHeader).get(id) if type == 'SUPLLIER_PAID': header.supplier_paid = flag if flag == '1': remark = u'%s 确认该记录为已付款予承运商。' % session['user_profile']['name'] else: remark = u'%s 确认该记录为未付款予承运商。' % session['user_profile']['name'] for d in header.details: d.supplier_paid = flag d.order_header.supplier_paid = flag DBSession.add(SystemLog( type = d.order_header.__class__.__name__, ref_id = d.order_header_id, remark = remark )) DBSession.add(SystemLog( type = header.__class__.__name__, ref_id = header.id, remark = remark )) DBSession.commit() return jsonify({'code' : 0 , 'msg' : MSG_UPDATE_SUCC}) except: _error(traceback.print_exc()) DBSession.rollback() return jsonify({'code' : 1, 'msg' : MSG_SERVER_ERROR})
def savePassword(self): oldpassword, newpassword, newconfirmpassword = _gs('oldpassword', 'newpassword', 'newconfirmpassword') if not oldpassword or not newpassword or not newconfirmpassword: flash(MSG_NO_ENOUGH_PARAMS, MESSAGE_WARNING) return redirect(url_for('.view')) user = DBSession.query(User).get(session['user_profile']['id']) if not user.validate_password(oldpassword): flash(MSG_WRONG_PASSWORD, MESSAGE_WARNING) return redirect(url_for('.view')) if newconfirmpassword != newpassword: flash(MSG_WRONG_CONFIRM_PASSWORD, MESSAGE_WARNING) return redirect(url_for('.view')) try: user.password = newpassword DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) except: DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view'))
def saveArticle(self): aid, title, sub_title, validate_date, desc, content = _gs('id', 'title', 'sub_title', 'validate_date', 'desc', 'content') if not aid : flash(MSG_NO_ID_SUPPLIED, MESSAGE_WARNING) return redirect(url_for('.view')) if not title: flash(MSG_NO_ENOUGH_PARAMS, MESSAGE_WARNING) return redirect(url_for('.view', action = 'updateArticle', id = aid)) try: article = DBSession.query(AppArticle).get(aid) article.title = title article.sub_title = sub_title article.validate_date = validate_date article.desc = desc article.content = content DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'listArticle', appid = article.app_id)) except: DBSession.rollback() traceback.print_exc() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view', action = 'updateArticle', id = aid))
def out_note_approve(self): ids = _g('note_ids') if not ids : return {"code" : 1 , "msg" : MSG_NO_ID_SUPPLIED} flag = _g('flag') try: for r in DBSession.query(InventoryOutNote).filter(and_(InventoryOutNote.active == 0, InventoryOutNote.id.in_(ids.split("|")))): r.status = flag for d in r.details: tmp_location_item = DBSession.query(InventoryLocationItem).filter(and_(InventoryLocationItem.item_id == d.item_id, InventoryLocationItem.location_id == d.location_id)).with_lockmode("update").one() if flag == "1": # approve this out note tmp_location_item.qty -= d.qty tmp_location_item.area -= d.area tmp_location_item.weight -= d.weight elif flag == "2": # disapprove this out note tmp_location_item.exp_qty += d.qty tmp_location_item.exp_area += d.area tmp_location_item.exp_weight += d.weight msg = None if flag == "1" : msg = u"%s 审批通过该记录。" % (session['user_profile']['name']) elif flag == "2" : msg = u"%s 审批不通过该记录。" % (session['user_profile']['name']) DBSession.add(SystemLog( type = InventoryOutNote.__class__.__name__, ref_id = r.id, remark = msg) ) DBSession.commit() return jsonify({"code" : 0 , "msg" : MSG_SAVE_SUCC}) except: DBSession.rollback() _error(traceback.print_exc()) return jsonify({"code" : 1 , "msg" : MSG_SERVER_ERROR})
def diqu(self): method = _g('m', 'LIST') if method not in ['LIST', 'NEW', 'UPDATE', 'DELETE', 'SAVE_NEW', 'SAVE_UPDATE', 'ADD_CITY', 'DELETE_CITY']: flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR); return redirect(url_for('.view', action = 'index')) if method == 'LIST': page = _g('page') or 1 objs = DBSession.query(Province).filter(Province.active == 0).order_by(Province.name).all() def url_for_page(**params): return url_for('bpAdmin.view', action = 'diqu', m = 'LIST', page = params['page']) records = paginate.Page(objs, page, show_if_single_page = True, items_per_page = PAGINATE_PER_PAGE, url = url_for_page) return render_template('admin/diqu_index.html', records = records) elif method == 'NEW': return render_template('admin/diqu_new.html') elif method == 'UPDATE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = 'customer')) obj = DBSession.query(Province).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = 'diqu')) city_json = [{ 'id' : 'old_%s' % c.id, 'city_name' : c.name, 'city_code' : c.code, 'city_shixiao' : c.shixiao, } for c in obj.children()] return render_template('admin/diqu_update.html', obj = obj, city_json = json.dumps(city_json)) elif method == 'DELETE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = 'diqu')) obj = DBSession.query(Province).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = 'diqu')) obj.active = 1 DBSession.commit() flash(MSG_DELETE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'diqu')) elif method == 'SAVE_NEW': obj = Province(name = _g('name'), code = _g('code'), shixiao = _g('shixiao')) DBSession.add(obj) city_json = _g('city_json', '') for city in json.loads(city_json): DBSession.add(City( name = city.get('city_name', None), code = city.get('city_code', None), shixiao = city.get('city_shixiao', None), parent_code = obj.code )) DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'diqu')) elif method == 'SAVE_UPDATE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = 'diqu')) obj = DBSession.query(Province).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = 'diqu')) for f in ['name', 'code', 'shixiao']: setattr(obj, f, _g(f)) city_json = _g('city_json', '') city_ids = map(lambda v : v.id, obj.children()) for city in json.loads(city_json): if not city.get('id', None) : continue if isinstance(city['id'], basestring) and city['id'].startswith("old_"): #existing target cid = city['id'].split("_")[1] c = DBSession.query(City).get(cid) c.name = city.get('city_name', None) c.code = city.get('city_code', None) c.shixiao = city.get('city_shixiao', None) c.parent_code = obj.code city_ids.remove(c.id) else: DBSession.add(City( name = city.get('city_name', None), code = city.get('city_code', None), shixiao = city.get('city_shixiao', None), parent_code = obj.code )) DBSession.query(City).filter(City.id.in_(city_ids)).update({'active' : 1}, False) DBSession.commit() flash(MSG_UPDATE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'diqu')) elif method == 'ADD_CITY': try: city = City(name = _g('city_name'), code = _g('city_code'), parent_code = _g('code'), shixiao = _g('city_shixiao')) DBSession.add(city) DBSession.commit() return jsonify({'code' : 0 , 'msg' : MSG_SAVE_SUCC , 'data' : city.populate()}) except: _error(traceback.print_exc()) DBSession.rollback() return jsonify({'code' : 1, 'msg' : MSG_SERVER_ERROR}) elif method == 'DELETE_CITY': id = _g('id', None) if not id : return jsonify({'code' : 1, 'msg' : MSG_NO_ID_SUPPLIED}) try: obj = DBSession.query(City).get(id) obj.active = 1 DBSession.commit() return jsonify({'code' : 0 , 'msg' : MSG_DELETE_SUCC}) except: _error(traceback.print_exc()) DBSession.rollback() return jsonify({'code' : 1, 'msg' : MSG_SERVER_ERROR})
def _template(self, DBObj, action, index_page = 'admin/template_index.html', new_page = 'admin/template_new.html', update_page = 'admin/template_update.html', ): method = _g('m', 'LIST') if method not in ['LIST', 'NEW', 'UPDATE', 'DELETE', 'SAVE_NEW', 'SAVE_UPDATE']: flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR); return redirect(url_for('.view', action = 'index')) if method == 'LIST': page = _g('page') or 1 objs = DBSession.query(DBObj).filter(DBObj.active == 0).order_by(DBObj.name) def url_for_page(**params): return url_for('bpAdmin.view', action = action, m = 'LIST', page = params['page']) records = paginate.Page(objs, page, show_if_single_page = True, items_per_page = PAGINATE_PER_PAGE, url = url_for_page) return render_template(index_page, records = records, action = action) elif method == 'NEW': return render_template(new_page, action = action) elif method == 'UPDATE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = action)) obj = DBSession.query(DBObj).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = action)) return render_template(update_page, v = obj.populate(), action = action, obj = obj) elif method == 'DELETE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = action)) obj = DBSession.query(DBObj).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = action)) obj.active = 1 DBSession.commit() flash(MSG_DELETE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = action)) elif method == 'SAVE_NEW': try: obj = DBObj.saveAsNew(request.values) DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) except: _error(traceback.print_exc()) DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view', action = action)) elif method == 'SAVE_UPDATE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = action)) obj = DBSession.query(DBObj).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = action)) try: old_info = obj.serialize(obj._get_fields()) obj.saveAsUpdate(request.values) DBSession.commit() new_info = obj.serialize(obj._get_fields()) change_result = obj.compare(old_info, new_info) obj.insert_system_logs(change_result) flash(MSG_UPDATE_SUCC, MESSAGE_INFO) except: _error(traceback.print_exc()) DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view', action = action))
def supplier(self): method = _g('m', 'LIST') if method not in ['LIST', 'NEW', 'UPDATE', 'DELETE', 'SAVE_NEW', 'SAVE_UPDATE', 'PRICE_LIST_LIST', 'PRICE_LIST_NEW', 'PRICE_LIST_UPDATE', 'PRICE_LIST_SAVE_NEW', 'PRICE_LIST_SAVE_UPDATE', ]: flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR); return redirect(url_for('.view', action = 'index')) if method == 'LIST': if _g('SEARCH_SUBMIT'): # come from search values = {'page' : 1} for f in ['no', 'name', 'contact_person', 'phone', 'mobile', ] : values[f] = _g(f) values['field'] = _g('field', None) or 'create_time' values['direction'] = _g('direction', None) or 'desc' else: #come from paginate or return values = session.get('master_supplier_values', {}) if _g('page') : values['page'] = int(_g('page')) elif 'page' not in values : values['page'] = 1 session['master_supplier_values'] = values conditions = [Supplier.active == 0] if values.get('no', None): conditions.append(Supplier.no.op('like')('%%%s%%' % values['no'])) if values.get('name', None): conditions.append(Supplier.name.op('like')('%%%s%%' % values['name'])) if values.get('contact_person', None): conditions.append(Supplier.contact_person.op('like')('%%%s%%' % values['contact_person'])) if values.get('phone', None): conditions.append(Supplier.phone.op('like')('%%%s%%' % values['phone'])) if values.get('mobile', None): conditions.append(Supplier.mobile.op('like')('%%%s%%' % values['mobile'])) field = values.get('field', 'create_time') if values.get('direction', 'desc') == 'desc': result = DBSession.query(Supplier).filter(and_(*conditions)).order_by(desc(getattr(Supplier, field))) else: result = DBSession.query(Supplier).filter(and_(*conditions)).order_by(getattr(Supplier, field)) def url_for_page(**params): return url_for('bpAdmin.view', action = 'supplier', m = 'LIST', page = params['page']) records = paginate.Page(result, values['page'], show_if_single_page = True, items_per_page = PAGINATE_PER_PAGE, url = url_for_page) return render_template('admin/supplier_index.html', records = records, values = values) elif method == 'NEW': return render_template('admin/supplier_new.html', payment = getMasterAll(Payment)) elif method == 'UPDATE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = 'supplier')) obj = DBSession.query(Supplier).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = 'supplier')) return render_template('admin/supplier_update.html', obj = obj, payment = getMasterAll(Payment)) elif method == 'DELETE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = 'supplier')) obj = DBSession.query(Supplier).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = 'supplier')) obj.active = 1 DBSession.commit() flash(MSG_DELETE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'supplier')) elif method == 'SAVE_NEW': obj = Supplier( no = _g('no'), name = _g('name'), address = _g('address'), phone = _g('phone'), mobile = _g('mobile'), email = _g('email'), contact_person = _g('contact_person'), remark = _g('remark'), payment_id = _g('payment_id'), ) DBSession.add(obj) DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'supplier')) elif method == 'SAVE_UPDATE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = 'supplier')) try: obj = DBSession.query(Supplier).get(id) fields = ['no', 'name', 'address', 'phone', 'mobile', 'contact_person', 'remark', 'email', 'payment_id'] old_info = obj.serialize(fields) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = 'supplier')) for f in fields: setattr(obj, f, _g(f)) DBSession.commit() #handle the system log new_info = obj.serialize(fields) change_result = obj.compare(old_info, new_info) obj.insert_system_logs(change_result) flash(MSG_UPDATE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'supplier')) except: _error(traceback.print_exc()) DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view', action = 'supplier')) elif method == 'PRICE_LIST_LIST': id = _g('id') c = DBSession.query(Supplier).get(id) result = DBSession.query(SupplierDiquRatio).filter(and_(SupplierDiquRatio.active == 0, SupplierDiquRatio.supplier_id == c.id, )).order_by(SupplierDiquRatio.province_id) page = _g('page', 1) def url_for_page(**params): return url_for('.view', action = "supplier", m = method, page = params['page'], id = id) records = paginate.Page(result, page, show_if_single_page = True, items_per_page = PAGINATE_PER_PAGE, url = url_for_page) return render_template("admin/supplier_pricelist_index.html", records = records, obj = c) elif method == 'PRICE_LIST_NEW': supplier_id = _g('supplier_id') return render_template("admin/supplier_pricelist_new.html", supplier_id = supplier_id) elif method == 'PRICE_LIST_SAVE_NEW': try: params = {} for f in ['supplier_id', 'province_id', 'city_id', 'qty_ratio', 'weight_ratio', 'vol_ratio', 'remark'] : params[f] = _g(f) obj = SupplierDiquRatio(**params) DBSession.add(obj) DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) except: DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view', action = 'supplier', m = 'PRICE_LIST_LIST', id = obj.supplier_id)) elif method == 'PRICE_LIST_UPDATE': obj = DBSession.query(SupplierDiquRatio).get(_g('id')) if obj.province_id: cities = obj.province.children() else: cities = [] return render_template("admin/supplier_pricelist_update.html", cities = cities, obj = obj) elif method == 'PRICE_LIST_SAVE_UPDATE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = 'supplier')) obj = DBSession.query(SupplierDiquRatio).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = 'supplier')) for f in ['province_id', 'city_id', 'qty_ratio', 'weight_ratio', 'vol_ratio', 'remark'] : setattr(obj, f, _g(f)) DBSession.commit() flash(MSG_UPDATE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = 'supplier', m = 'PRICE_LIST_LIST', id = obj.supplier_id))
def pricelist(self): method = _g('m', 'LIST') _action = 'pricelist' if method not in ['LIST', 'NEW', 'UPDATE', 'DELETE', 'SAVE_NEW', 'SAVE_UPDATE', ]: flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR) return redirect(url_for('.view', action = 'index')) if method == 'LIST': id = _g('id') c = DBSession.query(Customer).get(id) result = DBSession.query(CustomerDiquRatio).filter(and_(CustomerDiquRatio.active == 0, CustomerDiquRatio.customer_id == c.id, )).order_by(CustomerDiquRatio.province_id) page = _g('page', 1) def url_for_page(**params): return url_for('.view', action = _action, m = 'LIST', page = params['page'], id = id) records = paginate.Page(result, page, show_if_single_page = True, items_per_page = PAGINATE_PER_PAGE, url = url_for_page) return render_template("customer/customer_pricelist_index.html", records = records, customer = c) elif method == 'NEW': customer_id = _g('customer_id') return render_template("customer/customer_pricelist_new.html", customer_id = customer_id) elif method == 'SAVE_NEW': try: params = {} for f in ['customer_id', 'province_id', 'city_id', 'qty_ratio', 'weight_ratio', 'vol_ratio', 'remark'] : params[f] = _g(f) obj = CustomerDiquRatio(**params) DBSession.add(obj) DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) except: DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view', action = _action, id = obj.customer_id)) elif method == 'UPDATE': obj = DBSession.query(CustomerDiquRatio).get(_g('id')) if obj.province_id: cities = obj.province.children() else: cities = [] return render_template("customer/customer_pricelist_update.html", cities = cities, obj = obj) elif method == 'SAVE_UPDATE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = _action)) obj = DBSession.query(CustomerDiquRatio).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = _action)) for f in ['province_id', 'city_id', 'qty_ratio', 'weight_ratio', 'vol_ratio', 'remark'] : setattr(obj, f, _g(f)) DBSession.commit() flash(MSG_UPDATE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = _action, id = obj.customer_id)) elif method == 'DELETE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = _action)) obj = DBSession.query(CustomerDiquRatio).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = _action)) obj.active = 1 DBSession.commit() flash(MSG_DELETE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = _action))
def _subcompany(self, DBObj, _action, _fields, _contact_type, _index_html, _new_html, _update_html): # DBObj = CustomerSource # _action = "source" # _fields = ['name', 'province_id', 'city_id', 'remark', 'payment_id'] # _contact_type = 'S' # _index_html = 'customer/customer_source_index.html' # _new_html = 'customer/customer_source_new.html' # _update_html = 'customer/customer_source_update.html' method = _g('m', 'LIST') if method not in ['LIST', 'NEW', 'UPDATE', 'DELETE', 'SAVE_NEW', 'SAVE_UPDATE', ]: flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR) return redirect(url_for('.view', action = 'index')) if method == 'LIST': id = _g('id') c = DBSession.query(Customer).get(id) result = DBSession.query(DBObj).filter(and_(DBObj.active == 0, DBObj.customer_id == c.id)).order_by(DBObj.name) page = _g('page', 1) def url_for_page(**params): return url_for('.view', action = _action, m = 'LIST', page = params['page'], id = id) records = paginate.Page(result, page, show_if_single_page = True, items_per_page = PAGINATE_PER_PAGE, url = url_for_page) return render_template(_index_html, records = records, customer = c) elif method == 'NEW': customer_id = _g('customer_id') return render_template(_new_html, customer_id = customer_id) elif method == 'SAVE_NEW': try: params = {"customer_id" : _g('customer_id')} for f in _fields : params[f] = _g(f) obj = DBObj(**params) DBSession.add(obj) DBSession.flush() contact_json = _g('contact_json', '') for contact in json.loads(contact_json): DBSession.add(CustomerContact( customer_id = _g('customer_id'), type = _contact_type, refer_id = obj.id, name = contact['contact_name'], address = contact['contact_address'], mobile = contact['contact_mobile'], phone = contact['contact_phone'], remark = contact['contact_remark'], )) DBSession.commit() flash(MSG_SAVE_SUCC, MESSAGE_INFO) except: DBSession.rollback() flash(MSG_SERVER_ERROR, MESSAGE_ERROR) return redirect(url_for('.view', action = _action, id = obj.customer_id)) elif method == 'UPDATE': source = DBSession.query(DBObj).get(_g('id')) if source.province_id: cities = source.province.children() else: cities = [] contact_json = [] for c in source.contacts(): contact_json.append({ "id" : "old_%s" % c.id, "contact_name" : c.name, "contact_address" : c.address, "contact_phone" : c.phone, "contact_mobile" : c.mobile, "contact_remark" : c.remark, }) return render_template(_update_html, cities = cities, obj = source, contact_json = json.dumps(contact_json)) elif method == 'SAVE_UPDATE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = _action)) obj = DBSession.query(DBObj).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = _action)) for f in _fields : setattr(obj, f, _g(f)) contact_ids = [c.id for c in obj.contacts()] contact_json = _g('contact_json', '') for c in json.loads(contact_json): if not c.get('id', None) : continue if isinstance(c['id'], basestring) and c['id'].startswith("old_"): #existing contact cid = c['id'].split("_")[1] t = DBSession.query(CustomerContact).get(cid) t.name = c.get('contact_name', None) t.address = c.get('contact_address', None) t.mobile = c.get('contact_mobile', None) t.phone = c.get('contact_phone', None) t.remark = c.get('contact_remark', None) contact_ids.remove(t.id) else: DBSession.add(CustomerContact( customer_id = obj.customer_id, type = _contact_type, refer_id = obj.id, name = c.get('contact_name', None), address = c.get('contact_address', None), mobile = c.get('contact_mobile', None), phone = c.get('contact_phone', None), email = c.get('contact_email', None), remark = c.get('contact_remark', None), )) DBSession.query(CustomerContact).filter(CustomerContact.id.in_(contact_ids)).update({'active' : 1}, False) DBSession.commit() flash(MSG_UPDATE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = _action, id = obj.customer_id)) elif method == 'DELETE': id = _g('id', None) if not id : flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR) return redirect(url_for('.view', action = _action)) obj = DBSession.query(DBObj).get(id) if not obj : flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR) return redirect(url_for('.view', action = _action)) DBSession.query(DBObj).filter(DBObj.id == id).update({'active' : 1}, False) DBSession.commit() flash(MSG_DELETE_SUCC, MESSAGE_INFO) return redirect(url_for('.view', action = _action))
def ajax_change_flag(self): try: ids = _g('order_ids') if not ids : return jsonify({'code' : 1, 'msg' : MSG_NO_ID_SUPPLIED}) flag = _g('flag') action_type = _g('type') remark = None r = DBSession.query(OrderHeader).filter(and_(OrderHeader.active == 0, OrderHeader.id.in_(ids.split("|")))) def _update(result, attr, value): for t in result : setattr(t, attr, value) if action_type == 'APPROVE': _update(r, "approve", flag) if flag == '1': # approve remark = u'%s 审核通过该订单。' % session['user_profile']['name'] else: # disapprove remark = u'%s 审核不通过该订单。' % session['user_profile']['name'] elif action_type == 'PAID': _update(r, "paid", flag) if flag == '1': remark = u'%s 确认该订单为客户已付款。' % session['user_profile']['name'] else: remark = u'%s 确认该订单为客户未付款。' % session['user_profile']['name'] elif action_type == 'SUPLLIER_PAID': _update(r, "supplier_paid", flag) if flag == '1': remark = u'%s 确认该订单为已付款予承运商。' % session['user_profile']['name'] else: remark = u'%s 确认该订单为未付款予承运商。' % session['user_profile']['name'] elif action_type == 'ORDER_RETURN': _update(r, "is_return_note", flag) if flag == '1': remark = u'%s 确认该订单为客户已返回单。' % session['user_profile']['name'] else: remark = u'%s 确认该订单为客户未返回单。' % session['user_profile']['name'] elif action_type == 'EXCEPTION': _update(r, "is_exception", flag) if flag == '1': remark = u'%s 标记该订单为异常。' % session['user_profile']['name'] else: remark = u'%s 取消该订单的异常标记。' % session['user_profile']['name'] elif action_type == 'LESS_QTY': _update(r, "is_less_qty", flag) if flag == '1': remark = u'%s 标记该订单为少货。' % session['user_profile']['name'] else: remark = u'%s 取消该订单的少货标记。' % session['user_profile']['name'] for t in r: DBSession.add(SystemLog( type = t.__class__.__name__, ref_id = t.id, remark = remark )) DBSession.commit() return jsonify({'code' : 0 , 'msg' : MSG_UPDATE_SUCC}) except: _error(traceback.print_exc()) DBSession.rollback() return jsonify({'code' : 1, 'msg' : MSG_SERVER_ERROR})