Beispiel #1
0
def m_events_update():
    id = _g("id")
    if not id :
        flash("No id supplied !", MESSAGE_ERROR)
        return redirect(url_for("m_events_list"))
    action_type = _g("action_type")
    if not action_type in ["m", "c", "p"]:
        flash("No such action !", MESSAGE_ERROR)
        return redirect(url_for("m_events_list"))

    e = DBSession.query(Events).get(id)
#    e = connection.Events.one({"id" : int(id)})

    if action_type == "m":
        return render_template("m_events_update.html", event = e)
    elif action_type == "c": #cancel       
        e.status = 2
        DBSession.add(Message(subject = u"Cancel Booking Event", user_id = e.user_id,
                              content = u"%s cancel the booking request." % session['user_profile']['name']))
        DBSession.commit()
        return jsonify({"success" : True, "message" : "Update successfully !"})
    elif action_type == "p": #confirmed
        e.status = 1
        DBSession.add(Message(subject = u"Confirm Booking Event", user_id = e.user_id,
                              content = u"%s confirm the booking request." % session['user_profile']['name']))
        DBSession.commit()
        return jsonify({"success" : True, "message" : "Update successfully !"})
Beispiel #2
0
    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"))
Beispiel #3
0
def register():
    fields = ["email", "password", "repassword"]
    if _check_params(fields) != 0:
        return jsonify({"result": 0, "msg": MSG_PARAMS_MISSING})

    email = _g("email")
    password = _g("password")
    repassword = _g("repassword")

    if not email:
        return jsonify({"result": 0, "msg": MSG_EMAIL_BLANK_ERROR})
    if not password:
        return jsonify({"result": 0, "msg": MSG_PASSWORD_BLANK_ERROR})
    if password != repassword:
        return jsonify({"result": 0, "msg": MSG_PASSWORD_NOT_MATCH})

    try:
        DBSession.query(User).filter(and_(User.active == 0, func.upper(User.email) == email.upper())).one()
        return jsonify({"result": 0, "msg": MSG_EMAIL_EXIST})
    except:
        traceback.print_exc()
        pass
    display_name = _g("display_name") or email
    try:
        u = User(email=email, password=password, display_name=display_name)
        DBSession.add(u)
        DBSession.commit()
        return jsonify({"result": 1, "msg": MSG_SAVE_SUCCESS, "id": u.id, "point": u.point})
    except:
        traceback.print_exc()
        return jsonify({"result": 0, "msg": MSG_SERVER_ERROR})
Beispiel #4
0
 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'))
Beispiel #5
0
def save_register():
    cid = _g('customer_id' , None)
    user_params = {
                "name" : _g('name'),
                "password" : _g('password'),
                "email" : _g('email'),
                "first_name" : _g('first_name'),
                "last_name" : _g('last_name'),
                "phone" : _g('phone'),
                "mobile" : _g('mobile'),
                   }


    if cid and cid != 'OTHER':
        c = DBSession.query(Customer).get(cid)
        user_params['customer_profile_id'] = c.profile.id
    else:
        cname = _g('name').strip()
        cp = CustomerProfile(name = "PROFILE_%s" % cname.strip().upper().replace(' ', '_'))
        DBSession.add(cp)
        DBSession.flush()
        c = Customer(
                     name = cname,
                     address = _g('address'),
                     profile = cp
                     )
        user_params['customer_profile_id'] = cp.id
        DBSession.add(c)

    DBSession.add(User(**user_params))

    DBSession.commit()
    flash(MSG_SAVE_SUCC, MESSAGE_INFO)
    return redirect(url_for('bpAuth.login'))
Beispiel #6
0
    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'))
Beispiel #7
0
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 !"})
Beispiel #8
0
    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)
Beispiel #9
0
    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))
Beispiel #10
0
 def permission(self):
     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(Permission).filter(Permission.active == 0).order_by(Permission.name).all()
         def url_for_page(**params): return url_for('bpAdmin.view', action = 'permission', 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/permission_index.html', records = records)
     elif method == 'NEW':
         groups = Group.all()
         return render_template('admin/permission_new.html', groups = groups)
     elif method == 'UPDATE':
         id = _g('id', None)
         if not id :
             flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         obj = Permission.get(id)
         if not obj :
             flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         gids = map(lambda v:v.id, obj.groups)
         all_groups = Group.all()
         return render_template('admin/permission_update.html', v = obj.populate(), gids = gids, all_groups = all_groups)
     elif method == 'DELETE':
         id = _g('id', None)
         if not id :
             flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         obj = Permission.get(id)
         if not obj :
             flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         obj.active = 1
         obj.groups = []
         DBSession.commit()
         flash(MSG_DELETE_SUCC, MESSAGE_INFO)
         return redirect(url_for('.view', action = 'permission'))
     elif method == 'SAVE_NEW':
         obj = Permission.saveAsNew(request.values)
         obj.groups = DBSession.query(Group).filter(Group.id.in_(_gl("gids"))).all()
         DBSession.commit()
         flash(MSG_SAVE_SUCC, MESSAGE_INFO)
         return redirect(url_for('.view', action = 'permission'))
     elif method == 'SAVE_UPDATE':
         id = _g('id', None)
         if not id :
             flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         obj = Permission.get(id)
         if not obj :
             flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
             return redirect(url_for('.view', action = 'permission'))
         obj.saveAsUpdate(request.values)
         obj.groups = DBSession.query(Group).filter(Group.id.in_(_gl('gids'))).all()
         obj.commit()
         flash(MSG_UPDATE_SUCC, MESSAGE_INFO)
         return redirect(url_for('.view', action = 'permission'))
Beispiel #11
0
 def saveProfile(self):
     uid = session['user_profile']['id']
     user = DBSession.query(User).get(uid)
     user.mobile = _g('mobile')
     DBSession.commit()
     flash(MSG_SAVE_SUCC, MESSAGE_INFO)
     return redirect(url_for('.view'))
Beispiel #12
0
    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))
Beispiel #13
0
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()
Beispiel #14
0
def import_supplier(payment1):
    print "insert supplier"
    DBSession.add_all([
               Supplier(name = u'中深翔', display_name = u'中深翔', address = u'布吉丹竹头金鹏物流园A区A栋18-20号', mobile = '13600432849', contact_person = u'全总', remark = u'上海', payment = payment1),
               Supplier(name = u'深中联', display_name = u'深中联', address = u'布吉丹竹头金鹏物流园A栋5-6号', mobile = '13392826777,18902480211', contact_person = u'王总,丁小姐', remark = u'温州、台州、温岭、临海、黄岩', payment = payment1),
               Supplier(name = u'旺平达', display_name = u'旺平达', address = u'龙华明治大道华通源物流中心B2栋263-266号', mobile = '15099917300', contact_person = u'李飞章', remark = u'苏州、无锡、昆山、张家港、宜兴、常熟、太仓、吴江', payment = payment1),
               Supplier(name = u'顺福', display_name = u'顺福', address = u'丹竹头白泥坑宇达物流园3栋301-318号', phone = '89575677', mobile = '13316895558', contact_person = u'陈老板', remark = u'徐州、南通、淮安、盐城、连云港、启东', payment = payment1),
               Supplier(name = u'鑫金叶', display_name = u'鑫金叶', address = u'布吉李朗东西干道南岭大龙山物流园G栋1-3号', mobile = '13906667228', contact_person = u'金经理        ', remark = u'温州苍南', payment = payment1),
               Supplier(name = u'华发', display_name = u'华发', address = u'金鹏物流园B区9栋7-12号', mobile = '15999677737', contact_person = u' 陈老板', remark = u'南京、常州、扬州、泰州、镇江、靖江', payment = payment1),
               Supplier(name = u'京鹏', display_name = u'京鹏', address = u'华通源物流中心C4栋138-152号', mobile = '13066815788,13066815788', contact_person = u'老板娘           傅总', remark = u'杭州、上虞、湖州、德清、临安、丽水、桐乡、长兴、云南省', payment = payment1),
               Supplier(name = u'凯林瑞', display_name = u'凯林瑞', address = u'龙岗区丹竹头金鹏物流园B区D栋41-42号', phone = '0755-82432843', mobile = '', contact_person = u'杨总', remark = u'浙江嘉兴', payment = payment1),
               Supplier(name = u'海联', display_name = u'海联', address = u'华通源物流中心', mobile = '18688838882', contact_person = u'李老板', remark = u'宁波、义乌、绍兴、衢州、诸暨、金华、慈溪、余姚、舟山、奉化', payment = payment1),
               Supplier(name = u'荣晖', display_name = u'荣晖', address = u'金鹏A区B栋15-18号,40-42号', mobile = '13631528080', contact_person = u'胡总', remark = u'南昌、赣州、新余、吉安、九江、萍乡、宜春、鹰潭', payment = payment1),
               Supplier(name = u'深湘', display_name = u'深湘', address = u'长城货代市场83档', mobile = '13902485137', contact_person = u'丘总', remark = u'长沙、常德、衡阳、株洲、湘阴、岳阳、怀化、湘潭', payment = payment1),
               Supplier(name = u'澳跃', display_name = u'澳跃', address = u'金鹏', mobile = '13902311565', contact_person = u'肖总', remark = u'武汉、黄冈、黄石、荆州、咸宁、孝感、襄樊、恩施、十堰、襄阳', payment = payment1),
               Supplier(name = u'金鹏行', display_name = u'金鹏行', address = u'', mobile = '18926534999', contact_person = u'俞总', remark = u'合肥、淮南、黄山、桐城、芜湖、宣城、安庆、铜陵、涡阳、滁州、怀远', payment = payment1),
               Supplier(name = u'京鹏', display_name = u'京鹏', address = u'华通源物流中心C4栋138-152号', mobile = '13066815788', contact_person = u'傅小姐', remark = u'昆明、大理、曲靖、景洪', payment = payment1),
               Supplier(name = u'鑫辉', display_name = u'鑫辉', address = u'布吉丹平路闽鹏程货运市场11栋1-4号', mobile = '13925234059', contact_person = u'刘先生', remark = u'龙岩、三明', payment = payment1),
               Supplier(name = u'广运物流', display_name = u'广运物流', address = u'龙岗丹竹头闽鹏程货运市场5栋29-30号', mobile = '18923724600', contact_person = u'徐先生', remark = u'顺德', payment = payment1),
               Supplier(name = u'金华航', display_name = u'金华航', address = u'华通源物流园', phone = '0755-23022756', mobile = '', contact_person = u'刘先生', remark = u'中山', payment = payment1),
               Supplier(name = u'速速达', display_name = u'速速达', address = u'龙岗区布吉上李朗方鑫路22号速速达物流', phone = None, mobile = '13392831936', contact_person = u'王晓刚', remark = u'南宁、桂林、柳州、钦州', payment = payment1),
               Supplier(name = u'盛丰', display_name = u'盛丰', address = u'龙岗区南湾街道吉厦社区早禾坑工业区15号A栋', phone = None, mobile = '13798363667', contact_person = u'周总', remark = u'泉州、福州、莆田、福清', payment = payment1),
               Supplier(name = u'美泰', display_name = u'美泰', address = u'龙岗布吉大龙山物流园F栋10号美泰物流', phone = None, mobile = '18926795962', contact_person = u'毛主管', remark = u'广州', payment = payment1),
               Supplier(name = u'凯利', display_name = u'凯利', address = u'布吉单竹头金鹏物流园B区E栋1-5号 ', phone = '61217611,61217600', mobile = '', contact_person = u'熊小姐', remark = u'三亚、海口、琼海、万宁', payment = payment1),
               Supplier(name = u'骏兴顺', display_name = u'骏兴顺', address = u'龙华民治大道华通源物流中心C1栋58-60号', phone = None, mobile = '15914055308', contact_person = u'曾经理', remark = u'贵阳、金沙、安顺', payment = payment1),
               Supplier(name = u'澳跃', display_name = u'澳跃', address = u'金鹏A区栋13-15号', phone = None, mobile = '18923411132', contact_person = u'李峰', remark = u'漳州', payment = payment1),
               Supplier(name = u'勤威', display_name = u'勤威', address = u'金鹏B区C栋33号', phone = None, mobile = '13728866595', contact_person = u'石总', remark = u'厦门', payment = payment1),
               ])
    DBSession.commit()
Beispiel #15
0
    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())
Beispiel #16
0
    def barcode(self):
        method = _g('m', 'LIST')
        if method not in ['LIST', 'NEW', 'PRINT', 'SAVE_NEW']:
            flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR);
            return redirect(url_for('.view', action = 'index'))

        DBObj = Barcode
        index_page = 'admin/barcode_index.html'
        new_page = 'admin/barcode_new.html'
        print_page = 'admin/barcode_print.html'
        action = 'barcode'

        if method == 'LIST':
            if _g('SEARCH_SUBMIT'):  # come from search
                values = {'page' : 1}
                for f in ['value', 'ref_no', 'status', 'create_time_from', 'create_time_to'] :
                    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_barcode_values', {})
                if _g('page') : values['page'] = int(_g('page'))
                elif 'page' not in values : values['page'] = 1

            session['master_barcode_values'] = values

            conditions = [DBObj.active == 0]
            if values.get('value', None):  conditions.append(DBObj.value.op('like')('%%%s%%' % values['value']))
            if values.get('ref_no', None):  conditions.append(DBObj.ref_no.op('like')('%%%s%%' % values['ref_no']))
            if values.get('status', None):  conditions.append(DBObj.status == values['status'])
            if values.get('create_time_from', None):  conditions.append(DBObj.create_time > values['create_time_from'])
            if values.get('create_time_to', None):    conditions.append(DBObj.create_time < '%s 23:59' % values['create_time_to'])

            field = values.get('field', 'create_time')
            if values.get('direction', 'desc') == 'desc':
                result = DBSession.query(DBObj).filter(and_(*conditions)).order_by(desc(getattr(DBObj, field)))
            else:
                result = DBSession.query(DBObj).filter(and_(*conditions)).order_by(getattr(DBObj, field))

            def url_for_page(**params): return url_for('bpAdmin.view', action = action, m = 'LIST', page = params['page'])
            records = paginate.Page(result, values['page'], show_if_single_page = True, items_per_page = 100, url = url_for_page)
            return render_template(index_page, records = records, action = action, values = values)

        elif method == 'NEW':
            return render_template(new_page, action = action)
        elif method == 'PRINT':
            ids = _gl('ids')
            records = DBSession.query(DBObj).filter(DBObj.id.in_(ids)).order_by(desc(DBObj.create_time))
            return render_template(print_page, records = records)
        elif method == 'SAVE_NEW':
            qty = _g('qty')
            records = [DBObj.getOrCreate(None, None, status = 1) for i in range(int(qty))]
            DBSession.commit()
            if _g('type') == 'CREATE':
                flash(MSG_SAVE_SUCC, MESSAGE_INFO)
                return redirect(url_for('.view', action = action))
            else:
                return render_template(print_page, records = records)
Beispiel #17
0
 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))
Beispiel #18
0
    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})
Beispiel #19
0
 def _save_update(self):
     try:
         result = self.dbObj.save_update(self.get_argument("id", None), self)
         DBSession.commit()
         self.flash("Save the record successfully!")
     except Exception as e:
         logging.error(traceback.print_exc())
         DBSession.rollbak()
         self.flash(getattr(e, "msg", None) or "This operation is not available now!")
         self._update()
     self.redirect("%s?action=view&id=%d" % (self.url_prefix, result.id))
Beispiel #20
0
 def delete(self):
     header = getOr404(OrderHeader, _g('id'), redirect_url = self.default())
     header.active = 1
     DBSession.add(SystemLog(
                             type = header.__class__.__name__,
                             ref_id = header.id,
                             remark = u"%s 删除该记录。" % session['user_profile']['name'],
                             ))
     DBSession.commit()
     flash(MSG_DELETE_SUCC, MESSAGE_INFO)
     return redirect(url_for('.view', action = 'index'))
Beispiel #21
0
 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())
Beispiel #22
0
 def delete(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'))
     obj.active = 1
     DBSession.commit()
     flash(MSG_DELETE_SUCC, MESSAGE_INFO)
     return redirect(url_for('.view'))
Beispiel #23
0
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()
Beispiel #24
0
    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'))
Beispiel #25
0
def check():
    try:
        u = DBSession.query(User).filter(and_(User.active == 0, User.name == _g('name'))).one()
    except:
        _error(traceback.print_exc())
        flash(MSG_USER_NOT_EXIST, MESSAGE_ERROR)
        return redirect(url_for('bpAuth.login', next = _g('next')))
    else:
        if not _g('password'):
            flash(MSG_WRONG_PASSWORD, MESSAGE_ERROR)
            return redirect(url_for('bpAuth.login', next = _g('next')))

        if not u.validate_password(_g('password')):
            flash(MSG_WRONG_PASSWORD, MESSAGE_ERROR)
            return redirect(url_for('bpAuth.login', next = _g('next')))
        else:
            #fill the info into the session
            session['login'] = True
            session['user_profile'] = u.populate()
            permissions = set()
            for g in u.groups:
                for p in g.permissions:
                    permissions.add(p.name)
            session['user_profile']['groups'] = [g.name for g in u.groups]
            session['user_profile']['permissions'] = list(permissions)

            if in_group('CUSTOMER'):
                for g in u.groups:
                    if g.type != 0 :
                        for p in g.customer_profile:
                            if p and p.customer_id:
                                session['customer_profile'] = p.customer.populate()
                                break

            if in_group('SUPPLIER'):
                for g in u.groups:
                    if g.type != 0 :
                        for p in g.supplier_profile:
                            if p and p.supplier_id:
                                session['supplier_profile'] = p.supplier.populate()
                                break

            u.last_login = dt.now()

            session.permanent = True

            DBSession.commit()
            if _g('next') : return redirect(_g('next'))
            return redirect(index_url())
Beispiel #26
0
    def out_note_save_update(self):
        id = _g('id')
        if not id :
            flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
            return redirect(url_for(".view", action = "out_note"))
        obj = DBSession.query(InventoryOutNote).get(id)
        for f in ['customer_id', 'so', 'po', 'dn', 'ref', 'remark' ] : setattr(obj, f, _g(f))

        total_qty = total_weight = total_area = 0
        details_mapping = {}
        for d in obj.details : details_mapping['%s' % d.id] = d

        for qk, qv in _gp("qty_"):
            id = qk.split("_")[1]
            if id not in details_mapping : continue
            d = details_mapping[id]

            qty = self._p(_g('qty_%s' % id), int, 0)
            weight = self._p(_g('weight_%s' % id), float, 0)
            area = self._p(_g('area_%s' % id), float, 0)

            total_qty += qty
            total_area += area
            total_weight += weight

            if obj.status != 2:
                # update the locaion-item relation
                t = DBSession.query(InventoryLocationItem).filter(and_(InventoryLocationItem.location_id == d.location_id,
                                                                   InventoryLocationItem.item_id == d.item_id)).with_lockmode("update").one()

                if obj.status == 1:  # if the record is approved,update the real qty/weight/area
                    t.qty -= qty - d.qty
                    t.weight -= weight - d.weight
                    t.area -= area - d.area
                t.exp_qty -= qty - d.qty
                t.exp_weight -= weight - d.weight
                t.exp_area -= area - d.area

            d.qty = qty
            d.weight = weight
            d.area = area

        obj.qty = total_qty
        obj.area = total_area
        obj.weight = total_weight

        DBSession.commit()
        flash(MSG_UPDATE_SUCC, MESSAGE_INFO)
        return redirect(url_for(".view", action = "out_note_review", id = obj.id))
Beispiel #27
0
 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))
Beispiel #28
0
    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'))
Beispiel #29
0
 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'))
Beispiel #30
0
 def ratio(self):
     method = _g('m', 'LIST')
     if method not in ['UPDATE', 'SAVE_UPDATE']:
         flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR);
         return redirect(url_for('.view', action = 'index'))
     if method == 'UPDATE':
         ratios = {}
         for r in DBSession.query(Ratio).filter(Ratio.active == 0):
             ratios[r.type] = r.value
         return render_template('admin/ratio.html', ratios = ratios)
     elif method == 'SAVE_UPDATE':
         for r in DBSession.query(Ratio).filter(Ratio.active == 0):
             if r.type in request.values:
                 r.value = _g(r.type) or 0
         DBSession.commit()
         flash(MSG_SAVE_SUCC, MESSAGE_INFO)
         return redirect(url_for('bpAdmin.view'))