Esempio n. 1
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())
Esempio n. 2
0
def getDoctorList():
    fields = ["lang", "locationIndex"]
    if _check_params(fields) != 0:
        return jsonify({"result": 0, "msg": MSG_PARAMS_MISSING})

    ds = []
    lang = _g("lang")
    locationIndex = _g("locationIndex")
    for c in DBSession.query(Clinic).filter(and_(Clinic.active == 0, Clinic.area_id == locationIndex)):
        latitude = longtitude = None
        if c.coordinate:
            latitude, longtitude = c.coordinate.split(",")
        for d in c.doctors:
            ds.append(
                {
                    "doctorID": d.id,
                    "clinicID": c.id,
                    "name": {"zh_HK": c.name_tc, "zh_CN": c.name_sc}.get(lang, c.name),
                    "latitude": latitude,
                    "longtitude": longtitude,
                    "address": {"zh_HK": c.address_tc, "zh_CN": c.address_sc}.get(lang, c.address),
                }
            )

    return jsonify({"result": 1, "data": ds})
Esempio n. 3
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 = 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
        e.save()
        msg = connection.Message()
        msg.id = msg.getID()
        msg.subject = u"Cancel Booking Event"
        msg.content = u"%s cancel the booking request." % session[
            'user_profile']['name']
        msg.uid = e.uid
        msg.save()
        return jsonify({"success": True, "message": "Update successfully !"})
    elif action_type == "p":  #confirmed
        e.status = 1
        e.save()
        msg = connection.Message()
        msg.id = msg.getID()
        msg.subject = u"Confirm Booking Event"
        msg.content = u"%s confirm the booking request." % session[
            'user_profile']['name']
        msg.uid = e.uid
        msg.save()
        return jsonify({"success": True, "message": "Update successfully !"})
Esempio n. 4
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})
Esempio n. 5
0
def getDoctorDetail():
    fields = ["lang", "doctorID", "clinicID"]
    if _check_params(fields) != 0:
        return jsonify({"result": 0, "msg": MSG_PARAMS_MISSING})

    lang = _g("lang")
    dp = DBSession.query(DoctorProfile).get(_g("doctorID"))
    base_info = dp.getUserProfile()

    c = DBSession.query(Clinic).get(_g("clinicID"))
    latitude = longtitude = None
    if c.coordinate:
        latitude, longtitude = c.coordinate.split(",")

    return jsonify(
        {
            "result": 1,
            "data": {
                "doctorID": dp.id,
                "name": {"zh_HK": base_info["display_name_tc"], "zh_CN": base_info["display_name_sc"]}.get(
                    lang, base_info["display_name"]
                ),
                "desc": dp.desc,
                "tel": c.tel,
                "address": {"zh_HK": c.address_tc, "zh_CN": c.address_sc}.get(lang, c.address),
                "image": base_info["image_url"],
                "mapLocationX": longtitude,
                "mapLocationY": latitude,
                "rating": dp.rating,
            },
        }
    )
Esempio n. 6
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))
Esempio n. 7
0
    def item_detail(self):
        if _g('SEARCH_SUBMIT'):  # come from search
            values = {'page' : 1}
            for f in ['create_time_from', 'create_time_to', 'id'] :
                values[f] = _g(f)
        else:  # come from paginate or return
            values = session.get('inventory_item_detail_values', {})
            if _g('page') : values['page'] = int(_g('page'))
            elif 'page' not in values : values['page'] = 1
            values['id'] = _g('id')

        if not values.get('create_time_from', None) and not values.get('create_time_to', None):
            values['create_time_to'] = dt.now().strftime("%Y-%m-%d")
            values['create_time_from'] = (dt.now() - timedelta(days = 30)).strftime("%Y-%m-%d")

        session['inventory_item_detail_values'] = values

        conditions = [InventoryNoteDetail.active == 0, InventoryNoteDetail.item_id == values.get('id', None)]
        result = DBSession.query(InventoryNoteDetail).filter(and_(*conditions)).order_by(InventoryNoteDetail.create_time)

        def url_for_page(**params): return url_for('.view', action = "item_detail", id = values.get('id', None), 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 {
                "records" : records,
                "values"  : values,
                }
Esempio n. 8
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'))
Esempio n. 9
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'))
Esempio n. 10
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 !"})
Esempio n. 11
0
    def ajax_save(self):
        id = _g("id")
        type = _g('form_type')
        if type not in ['sendout', 'transit', 'exception', 'arrived']:
            return jsonify({'code' :-1, 'msg' : unicode(MSG_NO_SUCH_ACTION)})

        header = DeliverHeader.get(id)
        if type == 'sendout':
            header.status = SEND_OUT[0]
            DBSession.add(TransferLog(
                                      refer_id = header.id,
                                      transfer_date = _g('send_out_time'),
                                      type = 1,
                                      remark = _g('send_out_remark')
                                      ))
            header.sendout_time = _g('send_out_time')

            DBSession.add(SystemLog(
                                    type = header.__class__.__name__,
                                    ref_id = header.id,
                                    remark = u'%s 确认该记录状态为已发货。' % session['user_profile']['name']
                                    ))


            DBSession.commit()
            self._sms(header, u'已发货。')
            return jsonify({'code' : 0 , 'msg' : unicode(MSG_SAVE_SUCC)})

        if type == 'transit':
            DBSession.add(TransferLog(
                                      refer_id = header.id,
                                      transfer_date = _g('transit_time'),
                                      type = 1,
                                      remark = _g('transit_remark')
                                      ))
            DBSession.commit()
            return jsonify({'code' : 0 , 'msg' : unicode(MSG_SAVE_SUCC)})


        if type == 'arrived' :
            header.status = GOODS_ARRIVED[0]
            DBSession.add(TransferLog(
                                      refer_id = header.id,
                                      transfer_date = _g('arrived_time'),
                                      type = 1,
                                      remark = _g('arrived_remark')
                                      ))
            DBSession.add(SystemLog(
                                    type = header.__class__.__name__,
                                    ref_id = header.id,
                                    remark = u'%s 确认记录状态为货物已到达目的站。' % session['user_profile']['name']
                                    ))

            for d in header.details:
                order_header = d.order_header
                order_header.actual_time = _g('arrived_time')
            DBSession.commit()
            self._sms(header, u'已到达。')
            return jsonify({'code' : 0 , 'msg' : unicode(MSG_SAVE_SUCC)})
Esempio n. 12
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})
Esempio n. 13
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)
Esempio n. 14
0
    def compute_by_diqu(self):
        province_id = _g('province_id')
        city_id = _g('city_id')
        customer_id = _g('customer_id')

        # count the ratio
        ratio_result = self._compute_ratio(customer_id, province_id, city_id)
        # count the day
        day_result = self._compute_day(province_id, city_id)

        ratio_result.update(day_result)
        ratio_result.update({'code' : 0})
        return jsonify(ratio_result)
Esempio n. 15
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))
Esempio n. 16
0
 def vendor_select(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"))
     result = DBSession.query(DeliverHeader).filter(and_(
                                                         DeliverHeader.active == 0,
                                                         DeliverHeader.status.in_([SEND_OUT[0], IN_TRAVEL[0], GOODS_ARRIVED[0]]),
                                                         DeliverHeader.supplier_id == session['supplier_profile']['id'],
                                                         )).order_by(DeliverHeader.create_time)
     return {'result' : result , 'values' : {
                                             'no' : _g('no'),
                                             'destination_address' : _g('destination_address'),
                                             'create_time_from' : _g('create_time_from'),
                                             'create_time_to' : _g('create_time_to'),
                                             }}
Esempio n. 17
0
def save_profile():
    id = session['user_profile']["id"]
    u = connection.User.one({"id" : id})
    u.first_name = _g("first_name")
    u.last_name = _g("last_name")
    u.phone = _g("phone")
    u.birthday = _g("birthday")
    try:
        f = upload("image_url")
        u.image_url = f.id
    except:
        app.logger.error(traceback.format_exc())
    u.save()
    flash("Update the profile successfully!", MESSAGE_INFO)
    return redirect(url_for("index"))
Esempio n. 18
0
def save_profile():
    id = session['user_profile']["id"]
    u = connection.User.one({"id": id})
    u.first_name = _g("first_name")
    u.last_name = _g("last_name")
    u.phone = _g("phone")
    u.birthday = _g("birthday")
    try:
        f = upload("image_url")
        u.image_url = f.id
    except:
        app.logger.error(traceback.format_exc())
    u.save()
    flash("Update the profile successfully!", MESSAGE_INFO)
    return redirect(url_for("index"))
Esempio n. 19
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"))
Esempio n. 20
0
    def revise(self):
        header = getOr404(DeliverHeader, _g('id'), redirect_url = self.default())

        if header.destination_province_id:
            destination_cites = header.destination_province.children()
        else: destination_cites = []
        return {'header' : header, 'destination_cites' : destination_cites}
Esempio n. 21
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'))
Esempio n. 22
0
def getComment():
    fields = ["lang", "doctorID"]
    if _check_params(fields) != 0:
        return jsonify({"result": 0, "msg": MSG_PARAMS_MISSING})
    comments = (
        DBSession.query(DoctorComment, User)
        .filter(
            and_(
                DoctorComment.active == 0,
                User.active == 0,
                DoctorComment.create_by_id == User.id,
                DoctorComment.doctor_id == _g("doctorID"),
            )
        )
        .order_by(desc(DoctorComment.create_time))
    )
    return jsonify(
        {
            "result": 1,
            "data": [
                {"userID": comment.create_by_id, "name": unicode(user), "comment": comment.content}
                for (comment, user) in comments
            ],
        }
    )
Esempio n. 23
0
 def out_note_review(self):
     id = _g('id')
     if not id :
         flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
         return redirect(self.default())
     obj = DBSession.query(InventoryOutNote).get(id)
     return {'obj' : obj}
Esempio n. 24
0
    def review(self):
        id = _g('id') or None
        if not id :
            flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
            return redirect(self.default())

        try:
            header = DBSession.query(OrderHeader).get(id)

            logs = []
            logs.extend(header.get_logs())
            try:
                deliver_detail = DBSession.query(DeliverDetail).filter(and_(DeliverDetail.active == 0, DeliverDetail.order_header_id == header.id)).one()
                deliver_heaer = deliver_detail.header
    #            for f in deliver_heaer.get_logs() : _info(f.remark)
                logs.extend(deliver_heaer.get_logs())
            except:
                pass
            logs = sorted(logs, cmp = lambda x, y: cmp(x.transfer_date, y.transfer_date))

            return {
                    'header' : header ,
                    'transit_logs' : logs,
                    }
        except:
            _error(traceback.print_exc())
            flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
            return  redirect(self.default())
Esempio n. 25
0
 def view(self):
     id = _g('id')
     if not id :
         flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
         return redirect(url_for('.view'))
     obj = DBSession.query(Customer).get(id)
     return {'obj' : obj}
Esempio n. 26
0
def m_events_list():
    try:
        page = _g("page", 1)
    except:
        page = 1
    es = list(connection.Events.find({"active" : 0}).sort("date", pymongo.DESCENDING))
    paginate_events = Page(es, page = page, items_per_page = ITEM_PER_PAGE, url = lambda page:"%s?page=%d" % (url_for("m_events_list"), page))
    return {"paginate_events" : paginate_events}
Esempio n. 27
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'))
Esempio n. 28
0
    def ajax_check_before_save(self):
        try:
            note_id = _g('note_id')
            note_no = _g('note_no')
            note = DBSession.query(Note).get(note_id)
            note_no = int(note_no)
            if not (int(note.begin_no) <= int(note_no) <= int(note.end_no)):
                return jsonify({'code' : 0 , 'result' : 1, 'msg' : u'该票据不在可用范围内(%s~%s),请修改!' % (note.begin_no, note.end_no)})

            ref_no = _g('ref_no')
            if DBSession.query(OrderHeader).filter(and_(OrderHeader.active == 0, OrderHeader.ref_no == ref_no)).count() > 0:
                return jsonify({'code' : 0 , 'result' : 1, 'msg' : u'已经存在重复的订单号码!'})

            return jsonify({'code' : 0 , 'result' : 0})
        except:
            _error(traceback.print_exc())
            return jsonify({'code' : 1 , 'msg' : MSG_SERVER_ERROR})
Esempio n. 29
0
    def print_barcode(self):
        header = OrderHeader.get(_g('id'))

        if not header :
            flash(MSG_RECORD_NOT_EXIST)
            return redirect(self.default())

        return {'header' : header}
Esempio n. 30
0
 def revise_by_barcode(self):
     barcode = _g('no')
     try:
         header = DBSession.query(OrderHeader).filter(OrderHeader.no == barcode).one()
         return redirect(url_for('.view', action = 'revise', id = header.id))
     except:
         flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
         return redirect(url_for("bpRoot.view", action = "index"))
Esempio n. 31
0
 def view_by_no(self):
     no = _g('no')
     try:
         h = DBSession.query(DeliverHeader).filter(and_(DeliverHeader.active == 0, DeliverHeader.no == no)).one()
         return {'header' : h, 'values' : h.populate() , 'details' : h.details}
     except:
         flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
         return redirect(self.default())
Esempio n. 32
0
def m_events_list():
    try:
        page = _g("page", 1)
    except:
        page = 1
    es = DBSession.query(Events).filter(Events.active == 0).order_by(desc(Events.date))
    paginate_events = Page(es, page = page, items_per_page = ITEM_PER_PAGE, url = lambda page:"%s?page=%d" % (url_for("m_events_list"), page))
    return {"paginate_events" : paginate_events}
Esempio n. 33
0
def m_user_update():
    id = _g("id")
    redirect_url = url_for("m_user_list")
    if not id:
        flash("No id supplied !", MESSAGE_ERROR)
        return redirect(redirect_url)
    action_type = _g("action_type")
    if not action_type in ["v", "c"]:
        flash("No such action !", MESSAGE_ERROR)
        return redirect(redirect_url)
    u = connection.User.one({"id": int(id)})

    if action_type == "v":
        return render_template("m_user_view.html", user=u)
    elif action_type == "c":  #cancel
        u.active = 1
        e.save()
        return jsonify({"success": True, "message": "Update successfully !"})
Esempio n. 34
0
def save_password():
    id = session['user_profile']["id"]
    u = connection.User.one({"id": int(id)})
    if u.password != _g("old_password", None):
        flash("Old Password is wrong", MESSAGE_ERROR)
        return redirect(url_for("change_password"))

    if not _g("new_password", None):
        flash("The new password could not be blank", MESSAGE_ERROR)
        return redirect(url_for("change_password"))
    if _g("new_password", None) != _g("new_repassword", None):
        flash("The new password and the confirm password are not the same !",
              MESSAGE_ERROR)
        return redirect(url_for("change_password"))

    u.password = _g("new_password")
    u.save()
    flash("Update the password successfully !", MESSAGE_INFO)
    return redirect(url_for("change_password"))
Esempio n. 35
0
def m_events_list():
    try:
        page = _g("page", 1)
    except:
        page = 1
    es = list(
        connection.Events.find({
            "active": 0
        }).sort("date", pymongo.DESCENDING))
    paginate_events = Page(es,
                           page=page,
                           items_per_page=ITEM_PER_PAGE,
                           url=lambda page: "%s?page=%d" %
                           (url_for("m_events_list"), page))
    return {"paginate_events": paginate_events}
Esempio n. 36
0
def save_register():
    u = connection.User.one({'active': 0, 'email': _g("email")})
    if u:
        flash("The user has been already exist !", MESSAGE_ERROR)
        return redirect(url_for("register"))
    if _g("password") != _g("repassword"):
        flash("The password and confirmed password are not the same !",
              MESSAGE_ERROR)
        return redirect(url_for("register"))
    if not _g("first_name") or not _g("last_name"):
        flash("The first name or the last name is not supplied !",
              MESSAGE_ERROR)
        return redirect(url_for("register"))

    nu = connection.User()
    nu.id = nu.getID()
    nu.email = _g("email")
    nu.password = _g("password")
    nu.first_name = _g("first_name")
    nu.last_name = _g("last_name")
    nu.phone = _g("phone")
    nu.birthday = _g("birthday")

    r = connection.Role.one({"name": "NORMALUSER"})
    nu.roles = [r.id]
    r.users = r.users + [nu.id]
    nu.save()
    r.save()

    flash("Register successfully", MESSAGE_INFO)
    return redirect(url_for("login"))
Esempio n. 37
0
def m_doctor_save():
    required_fields = ["email", "first_name", "last_name"]
    for f in required_fields:
        if not _g(f):
            flash("The required field is not supplied !", MESSAGE_ERROR)
            return redirect(url_for("m_doctor_list"))

    action_type = _g("action_type")
    _gl = request.form.getlist  #could not move it outside the function , don't know why
    if action_type == "NEW":
        if not _g("password") or not _g("repassword"):
            flash("The required field is not supplied !", MESSAGE_ERROR)
            return redirect(url_for("m_doctor_list"))

        if _g("password") != _g("repassword"):
            flash("The password and the confirmed password are not the same !",
                  MESSAGE_ERROR)
            return redirect(url_for("m_doctor_list"))

        u = connection.User()
        u.id = u.getID()
        u.email = _g("email")
        u.password = _g("password")
        u.first_name = _g("first_name")
        u.last_name = _g("last_name")
        u.phone = _g("phone")
        u.birthday = _g("birthday")
        r = connection.Role.one({'active': 0, 'name': 'DOCTOR'})
        r.users.append(u.id)
        u.roles = [r.id]
        try:
            f = upload("image_url")
            u.image_url = f.id
        except:
            app.logger.error(traceback.format_exc())
        r.save()
        u.save()

        d = connection.DoctorProfile()
        d.id = d.getID()
        d.uid = u.id
        d.desc = _g("desc")
        #        d.qty = int(_g("qty"))  if _g("qty") else 10
        #map the relation
        d.category = map(int, _gl("category"))
        for c in d.category:
            connection.Category.one({'id': c}).doctors.append(d.id)
        d.clinic = map(int, _gl("clinic"))
        for c in d.clinic:
            connection.Clinic.one({"id": c}).doctors.append(d.id)

        #        d.avaiable_day = map(int, _gl("avaiable_day"))
        for day in [
                "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY",
                "SATURDAY", "SUNDAY", "HOLIDAY"
        ]:
            app.logger.info(request.form.getlist("time_" + day))
            ts = [
                map(lambda v: ("0" + v)[-5:], t.split("|"))
                for t in request.form.getlist("time_" + day)
            ]
            ts.sort(cmp=lambda a, b: cmp(a[0], b[0]))
            app.logger.info(ts)
            d.worktime_setting[day] = ts

        d.save()
        flash("Save the new doctor successfully!", MESSAGE_INFO)
        return redirect(url_for("m_doctor_list"))

    elif action_type == 'UPDATE':
        id = _g("id")
        if not id:
            flash("No doctor id supplied!", MESSAGE_ERROR)
            return redirect(url_for("m_doctor_list"))
        d = connection.DoctorProfile.one({'id': int(id)})
        d.desc = _g("desc")
        #map the relation
        d.category = map(int, _gl("category"))
        for c in d.category:
            connection.Category.one({'id': c}).doctors.append(d.id)
        d.clinic = map(int, _gl("clinic"))
        for c in d.clinic:
            connection.Clinic.one({"id": c}).doctors.append(d.id)

        for day in [
                "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY",
                "SATURDAY", "SUNDAY", "HOLIDAY"
        ]:
            app.logger.info(request.form.getlist("time_" + day))
            ts = [
                map(lambda v: ("0" + v)[-5:], t.split("|"))
                for t in request.form.getlist("time_" + day)
            ]
            ts.sort(cmp=lambda a, b: cmp(a[0], b[0]))
            app.logger.info(ts)
            d.worktime_setting[day] = ts


#        d.avaiable_day = map(int, _gl("avaiable_day"))
        d.save()
        u = connection.User.one({'id': d.uid})
        u.email = _g("email")
        u.first_name = _g("first_name")
        u.last_name = _g("last_name")
        u.phone = _g("phone")
        u.birthday = _g("birthday")
        try:
            f = upload("image_url")
            u.image_url = f.id
        except:
            app.logger.error(traceback.format_exc())
        u.save()

        flash("Save the update successfully !", MESSAGE_INFO)
        return redirect(url_for("m_doctor_list"))
    else:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_doctor_list"))
Esempio n. 38
0
def m_clinic_save():
    name = _g("name")
    if not name:
        flash("The clinic's name is not supplied!", MESSAGE_ERROR)
        return redirect(url_for("m_clinic_list"))

    action_type = _g("type")
    if action_type == "NEW":
        c = connection.Clinic()
        c.id = c.getID()
        c.name = name
        c.website = _g("website")
        c.address = _g("address")
        c.desc = _g("desc")
        lat = float(_g("lat")) if _g("lat") else None
        lng = float(_g("lng")) if _g("lng") else None
        c.location = (lat, lng)
        c.save()
        flash("Save the new clinic successfully!", MESSAGE_INFO)
        return redirect(url_for("m_clinic_list"))
    elif action_type == 'UPDATE':
        id = _g("id")
        if not id:
            flash("No clinic id supplied!", MESSAGE_ERROR)
            return redirect(url_for("m_clinic_list"))
        c = connection.Clinic.one({'id': int(id)})
        c.name = _g("name")
        c.website = _g("website")
        c.address = _g("address")
        c.desc = _g("desc")
        if _g("lat"): c.location[0] = float(_g("lat"))
        if _g("lng"): c.location[1] = float(_g("lng"))
        c.save()
        flash("Save the update successfully !", MESSAGE_INFO)
        return redirect(url_for("m_clinic_list"))
    else:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_clinic_list"))
Esempio n. 39
0
def m_nurse_save():
    required_fields = ["email", "first_name", "last_name"]
    for f in required_fields:
        if not _g(f):
            flash("The required field is not supplied !", MESSAGE_ERROR)
            return redirect(url_for("m_nurse_list"))

    action_type = _g("action_type")
    _gl = request.form.getlist
    if action_type == "NEW":
        if not _g("password") or not _g("repassword"):
            flash("The required field is not supplied !", MESSAGE_ERROR)
            return redirect(url_for("m_nurse_list"))

        if _g("password") != _g("repassword"):
            flash("The password and the confirmed password are not the same !",
                  MESSAGE_ERROR)
            return redirect(url_for("m_nurse_list"))
        u = connection.User()
        u.id = u.getID()
        u.email = _g("email")
        u.password = _g("password")
        u.first_name = _g("first_name")
        u.last_name = _g("last_name")
        u.phone = _g("phone")
        u.birthday = _g("birthday")
        r = connection.Role.one({'active': 0, 'name': 'NURSE'})
        r.users.append(u.id)
        u.roles = [r.id]
        try:
            f = upload("image_url")
            u.image_url = f.id
        except:
            app.logger.error(traceback.format_exc())
        r.save()
        u.save()

        n = connection.NurseProfile()
        n.id = n.getID()
        n.uid = u.id
        n.desc = _g("desc")

        n.clinic = map(int, _gl("clinic"))
        for c in n.clinic:
            connection.Clinic.one({"id": c}).nurses.append(n.id)
        n.save()
        flash("Save the new nurse successfully!", MESSAGE_INFO)
        return redirect(url_for("m_nurse_list"))

    elif action_type == 'UPDATE':
        id = _g("id")
        if not id:
            flash("No nurse id supplied!", MESSAGE_ERROR)
            return redirect(url_for("m_doctor_list"))
        n = connection.NurseProfile.one({'id': int(id)})
        n.desc = _g("desc")
        #map the relation
        n.clinic = map(int, _gl("clinic"))
        for c in n.clinic:
            connection.Clinic.one({"id": c}).nurses.append(n.id)
        n.save()
        u = connection.User.one({'id': n.uid})
        u.email = _g("email")
        u.first_name = _g("first_name")
        u.last_name = _g("last_name")
        u.phone = _g("phone")
        u.birthday = _g("birthday")
        try:
            f = upload("image_url")
            u.image_url = f.id
        except:
            app.logger.error(traceback.format_exc())
        u.save()
        flash("Save the update successfully !", MESSAGE_INFO)
        return redirect(url_for("m_nurse_list"))
    else:
        flash("No such action type !", MESSAGE_ERROR)
        return redirect(url_for("m_nurse_list"))
Esempio n. 40
0
def check_email():
    u = connection.User.one({"active": 0, "email": _g("email")})
    return jsonify({"is_exist": bool(u)})