Exemple #1
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())
Exemple #2
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'))
Exemple #3
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"))
Exemple #4
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))
Exemple #5
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())
Exemple #6
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})
Exemple #7
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())
Exemple #8
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'))
Exemple #9
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())
Exemple #10
0
    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"))
Exemple #11
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})
Exemple #12
0
    def ajax_order_info(self):
        ref_no = _g('order_no')
        try:
            header = DBSession.query(OrderHeader).filter(and_(OrderHeader.active == 0, OrderHeader.ref_no == ref_no)).one()
            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
                logs.extend(deliver_heaer.get_logs())
            except:
                pass
            logs = sorted(logs, cmp = lambda x, y: cmp(x.transfer_date, y.transfer_date))

            return jsonify({'code' : 0 , 'msg' : '', 'data' : {
                                                               'no' : header.no,
                                                               'ref_no' :header.ref_no,
                                                               'status' : header.status,
                                                               'source_company' : unicode(header.source_company),
                                                               'source_province' : unicode(header.source_province),
                                                               'source_city' : unicode(header.source_city) or '',
                                                               'source_address' : header.source_address or '',
                                                               'source_contact' : header.source_contact or '',
															   'source_tel' : header.source_tel or '',
                                                               'destination_company' : unicode(header.destination_company),
                                                               'destination_province' : unicode(header.destination_province),
                                                               'destination_city' : unicode(header.destination_city) or '',
                                                               'destination_address' : header.destination_address or '',
                                                               'destination_contact' : header.destination_contact or '',
															   'destination_tel' : header.destination_tel or '',
															   'qty' : header.qty or '',
															   'weight' : header.weight or '',
                                                               'create_time' : date2text(header.create_time),
															   'expect_time' : header.expect_time or '',
                                                               'actual_time' : header.actual_time or '',
															   'signed_contact' : header.signed_contact or '',
                                                               'logs' : [{
                                                                          'transfer_date' : l.transfer_date,
                                                                          'remark' : l.remark,
                                                                          } for l in logs]
                                                               }})

        except:
            _error(traceback.print_exc())
            return jsonify({'code' : 1, 'msg' : MSG_RECORD_NOT_EXIST})
Exemple #13
0
    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})
Exemple #14
0
 def _sms(self, header, suffix):
     try:
         for detail in header.details:
             order_header = detail.order_header
             users = []
             if order_header.source_sms and order_header.source_mobile:
                 users.append(order_header.source_mobile)
             if order_header.destination_sms and order_header.destination_mobile:
                 users.append(order_header.destination_mobile)
             if users:
                 content = u'订单:%s[目的站:%s,发货人:深福合力,收货人:%s,数量:%s件]%s' % (order_header.ref_no,
                                                                        order_header.destination_city or order_header.destination_province,
                                                                        order_header.destination_contact,
                                                                        order_header.qty, suffix)
                 send_sms(users, content)
     except:
         _error(traceback.print_exc())
         pass
Exemple #15
0
    def ajax_todo_list(self):

        def f(v):
            result = []
            data = DBSession.query(OrderHeader).filter(and_(OrderHeader.active == 0 , OrderHeader.status == v)).order_by(OrderHeader.create_time)
            for l in data[:5]:
                result.append({'id' : l.id, 'ref_no' : l.ref_no})
            return {'list' : result, 'count' : data.count()}

        try:
            data = {
                "order_draft" : f(ORDER_DRAFT[0]),
                "orders_new" : f(ORDER_NEW[0]),
                "order_receiver" : f(ASSIGN_RECEIVER[0]),
                "order_inhouse" : f(IN_WAREHOUSE[0]),
                "order_sorted" : f(SORTING[0]),
                    }
            return jsonify(result = 0, data = data)
        except:
            _error(traceback.print_exc())
            return jsonify(result = 1, data = [])
def generate_barcode_file(s, ext = '.jpg'):
    if not s : return None
    try:
        if len(s) % 2 != 0 :    s = '0' + s
        codestring = '^105%s' % s  #code 128 C format
        c = code128.Code128()

        f = c.render(str(codestring), options = dict(includetext = True, height = 0.4, textxalign = 'center'), scale = 2, margin = 5)
        file_name = "%s%.4d%s" % (dt.now().strftime("%Y%m%d%H%M%S"), random.randint(1, 1000), ext)
        file_dir = os.path.join(UPLOAD_FOLDER_PREFIX, UPLOAD_FOLDER)
        if not os.path.exists(file_dir): os.makedirs(file_dir)
        full_path = os.path.join(file_dir, file_name)
        f.save(full_path)
        return UploadFile(name = file_name,
                   path = os.path.join(UPLOAD_FOLDER, file_name),
                   url = "/".join([UPLOAD_FOLDER_URL, file_name]),
                   size = os.path.getsize(full_path),
                   type = ext[1:],
                   )
    except:
        _error(traceback.print_exc())
        return None
Exemple #17
0
    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})
Exemple #18
0
    def check(self):
        email, password = _gs('email', 'password')
        if not email or not password :
            flash(MSG_NO_ENOUGH_PARAMS, MESSAGE_WARNING)
            return redirect(url_for('bpRoot.view', action = 'login', next = _g('next')))

        try:
#            u = DBSession.query(User).filter(and_(User.active == 0, User.email.op('ilike')(_g('email')))).one()
            u = DBSession.query(User).filter(and_(User.active == 0, User.email == email)).one()
        except:
            _error(traceback.print_exc())
            flash(MSG_USER_NOT_EXIST, MESSAGE_WARNING)
            return redirect(url_for('bpRoot.view', action = 'login', next = _g('next')))
        else:
            if not u.validate_password(_g('password')):
                flash(MSG_WRONG_PASSWORD, MESSAGE_WARNING)
                return redirect(url_for('bpRoot.view', action = '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)

                apps = DBSession.query(AppObject).filter(and_(AppObject.active == 0,
                        AppObject.create_by_id == u.id)).order_by(AppObject.create_time)

                session['apps'] = [(app.id, unicode(app)) for app in apps]
                u.last_login = dt.now()
                session.permanent = True
                DBSession.commit()
                if _g('next') : return redirect(_g('next'))
                return redirect(url_for('bpConsoles.view', action = 'index'))
Exemple #19
0
    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})
Exemple #20
0
    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))
Exemple #21
0
    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})
Exemple #22
0
    def hh(self):
        type = _g('type')
        barcode = _g('barcode')

        if type == 'search':
            try:
                b = DBSession.query(Barcode).filter(and_(Barcode.active == 0, Barcode.value == barcode)).one()

                if b.status == 0 :  # the barcode is used in a order
                    try:
                        h = DBSession.query(OrderHeader).filter(OrderHeader.no == barcode).one()
                        params = {
                                  'no' : h.ref_no,
                                  'source_station' : h.source_province,
                                  'source_company' : h.source_company,
                                  'destination_station' : h.destination_province,
                                  'destination_company' : h.destination_company,
                                  'status' : h.status,
                                  }
                    except:
                        _error(traceback.print_exc())
                        params = {
                          'no' : unicode(MSG_RECORD_NOT_EXIST),
                          'source_station' : '',
                          'source_company' : '',
                          'destination_station' : '',
                          'destination_company' : '',
                          'status' : ''
                          }
                elif b.status == 1 :  # the barcode is reserved ,could be created a new order
                    params = {
                          'no' : 'BARCODE_AVAILABLE',
                          'source_station' : '',
                          'source_company' : '',
                          'destination_station' : '',
                          'destination_company' : '',
                          'status' : '-2'
                          }
                else:  # the barcode is cancel ,equal not existed
                    params = {
                          'no' : unicode(MSG_RECORD_NOT_EXIST),
                          'source_station' : '',
                          'source_company' : '',
                          'destination_station' : '',
                          'destination_company' : '',
                          'status' : ''
                          }

            except:
                _error(traceback.print_exc())
                params = {
                          'no' : unicode(MSG_RECORD_NOT_EXIST),
                          'source_station' : '',
                          'source_company' : '',
                          'destination_station' : '',
                          'destination_company' : '',
                          'status' : ''
                          }

            return self._compose_xml_result(params)
        elif type == 'submit':
            try:
                action_type = _g('action_type')
                action_type = int(action_type)

                # create a draft order by the handheld
                if action_type == -2:
                    no = _g('barcode')
                    ref_no = _g('orderno')

                    b = Barcode.getOrCreate(no, ref_no, status = 0)
                    try:
                        DBSession.add(OrderHeader(no = no, ref_no = ref_no, status = -2))
                        b.status = 0
                        DBSession.commit()
                        return self._compose_xml_response(0)
                    except:
                        DBSession.rollback()
                        _error(traceback.print_exc())
                        return self._compose_xml_response(1)

                h = DBSession.query(OrderHeader).filter(OrderHeader.no == barcode).one()
                h.update_status(action_type)

                if action_type == IN_WAREHOUSE[0]:
                    remark = (u'订单: %s 确认入仓。备注:' % h.ref_no) + (_g('remark') or '')
                elif action_type == OUT_WAREHOUSE[0]:
                    remark = (u'订单: %s 确认出仓。备注:' % h.ref_no) + (_g('remark') or '')
                elif action_type == GOODS_SIGNED[0]:
                    remark = LOG_GOODS_SIGNED + (u'签收人:%s , 签收人电话:%s , 签收时间:%s' % (_g('contact'), _g('tel') or '', _g('time'))),
                    h.signed_time = _g('time')
                    h.signed_remark = _g('remark')
                    h.signed_contact = _g('contact')
                    h.signed_tel = _g('tel')
                elif action_type == GOODS_PICKUP[0]:
                    remark = LOG_GOODS_PICKUPED + (u'提货人: %s, 提货数量: %s , 备注:%s' % (_g('contact'), _g('qty'), (_g('remark') or ''))),
                    params = {
                              'action_time' : _g('time'),
                              'contact' : _g('contact'),
                              'qty' : _g('qty'),
                              'tel' : _g('tel'),
                              'remark' : _g('remark'),
                              }
                    obj = PickupDetail(header = h, **params)
                    DBSession.add(obj)

                DBSession.add(TransferLog(
                                  refer_id = h.id,
                                  transfer_date = _g('time'),
                                  type = 0,
                                  remark = remark,
                                  ))
                DBSession.commit()
                return self._compose_xml_response(0)
            except:
                return self._compose_xml_response(1)
        else:
            return self._compose_xml_response(MSG_NO_SUCH_ACTION)
Exemple #23
0
def server_error(error):
    from sys2do.util.common import _error
    _error(error)
    return render_template("%d.html" % 500)
Exemple #24
0
    def save_update(self):
        id = _g("id")
        if not id:
            flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
            return redirect(self.default())
        header = DBSession.query(OrderHeader).get(id)
        fields = [
                  'customer_id', 'order_time',
                  'source_province_id', 'source_city_id', 'destination_province_id', 'destination_city_id',
                  'ref_no', 'source_company_id', 'source_address', 'source_contact', 'source_tel', 'source_mobile',
                  'payment_id', 'qty', 'weight', 'vol', 'shipment_type_id',
                   'destination_company_id', 'destination_address', 'destination_contact', 'destination_tel', 'destination_mobile',
                  'estimate_time', 'expect_time', 'actual_time', 'qty_ratio', 'weight_ratio', 'vol_ratio', 'amount', 'cost', 'remark',
                  'pickup_type_id', 'pack_type_id',
                  'insurance_charge', 'sendout_charge', 'receive_charge', 'package_charge', 'other_charge', 'load_charge', 'unload_charge',
                  'proxy_charge', 'note_id', 'note_no',
                  'source_sms', 'destination_sms',
                  ]
        _remark = []
        old_info = header.serialize(fields)  # to used for the history log

        checkbox_fields = ['source_sms', 'destination_sms', ]
        try:
            for f in fields: setattr(header, f, _g(f))

            for f in checkbox_fields:
                vs = _gl(f)
                if vs : setattr(header, f, vs[0])
                else : setattr(header, f, None)
            no = _g('no')
            if no != header.no:
                try:
                    old_barcode = DBSession.query(Barcode).filter(Barcode.value == header.no).one()
                    old_barcode.status = 1  # mark the old barcode to be reserved
                except:
                    pass
                try:
                    new_barcode = DBSession.query(Barcode).filter(Barcode.value == no).one()
                    new_barcode.status = 0  # mark the new barcode to be used
                except NoResultFound :
                    DBSession.add(Barcode(value = no))
                except:
                    pass
                header.no = no
                header.barcode = generate_barcode_file(header.no)

            if header.status == -2 : header.status = 0

            item_ids = [c.id for c in header.item_details]
            item_json = _g('item_json', '')
            for c in json.loads(item_json):
                if not c.get('id', None) : continue
                if isinstance(c['id'], basestring) and c['id'].startswith("old_"):  # existing item
                    cid = c['id'].split("_")[1]
                    t = DBSession.query(ItemDetail).get(cid)
                    t.item_id = c.get('item_id', None)
                    t.qty = c.get('qty', None)
                    t.weight = c.get('weight', None)
                    t.vol = c.get('vol', None)
                    t.remark = c.get('remark', None)
                    item_ids.remove(t.id)
                else:
                    DBSession.add(ItemDetail(
                                                header = header,
                                                item_id = c.get('item_id', None),
                                                qty = c.get('qty', None),
                                                weight = c.get('weight', None),
                                                vol = c.get('vol', None),
                                                remark = c.get('remark', None),
                                                  ))

            DBSession.query(ItemDetail).filter(ItemDetail.id.in_(item_ids)).update({'active' : 1}, False)

            # handle the file upload
            old_attachment_ids = map(lambda (k, v) : v, _gp("old_attachment_"))
            old_attachment_ids.extend(multiupload())
            header.attachment = old_attachment_ids

            DBSession.commit()

            # handle the system log
            new_info = header.serialize(fields)
            change_result = header.compare(old_info, new_info)
            header.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 = 'review', id = header.id))
Exemple #25
0
    def deliver_save_new(self):
        try:
            params = {}
            for f in ['ref_no', 'destination_province_id', 'destination_city_id', 'destination_address', 'destination_contact',
                      'destination_tel', 'destination_mobile', 'supplier_id',
                      'supplier_contact', 'supplier_tel', 'expect_time', 'order_time',
                      'insurance_charge', 'sendout_charge', 'receive_charge', 'package_charge', 'load_charge', 'unload_charge',
                      'other_charge', 'proxy_charge', 'amount', 'payment_id', 'pickup_type_id', 'remark', 'carriage_charge',
                      'qty', 'weight', 'vol', 'qty_ratio', 'weight_ratio', 'vol_ratio', 'shipment_type_id',
                      ]:
                params[f] = _g(f)
            header = DeliverHeader(**params)
            DBSession.add(header)
            DBSession.flush()
            header.no = getDeliverNo(header.id)
            total_qty = total_vol = total_weight = 0
            line_no = 1
            for k, id in _gp('detail_'):
                order_header = DBSession.query(OrderHeader).get(id)
                d = DeliverDetail(header = header,
                                            order_header = order_header,
                                            line_no = line_no,
                                            qty = _g('qty_%s' % id),
                                            vol = _g('vol_%s' % id),
                                            weight = _g('weight_%s' % id),
                                            insurance_charge = _g('insurance_charge_%s' % id),
                                            sendout_charge = _g('sendout_charge_%s' % id),
                                            receive_charge = _g('receive_charge_%s' % id),
                                            package_charge = _g('package_charge_%s' % id),
                                            load_charge = _g('load_charge_%s' % id),
                                            unload_charge = _g('unload_charge_%s' % id),
                                            other_charge = _g('other_charge_%s' % id),
                                            proxy_charge = _g('proxy_charge_%s' % id),
                                            carriage_charge = _g('carriage_charge_%s' % id),
                                            amount = _g('amount_%s' % id),
                                            )
                DBSession.add(d)
                if order_header.qty : total_qty += float(d.qty)
                if order_header.vol : total_vol += float(d.vol)
                if order_header.weight : total_weight += float(d.weight)

                order_header.update_status(SORTING[0])
                order_header.cost = _g('amount_%s' % id),
                order_header.deliver_header_ref = header.id
                order_header.deliver_header_no = header.ref_no
                line_no += 1

            header.qty = total_qty
            header.vol = total_vol
            header.weight = total_weight

            DBSession.add(TransferLog(
                                      refer_id = header.id,
                                      transfer_date = dt.now().strftime(SYSTEM_DATETIME_FORMAT),
                                      type = 1,
                                      remark = LOG_GOODS_SORTED
                                      ))

            # handle the upload file
            header.attachment = multiupload()
            DBSession.commit()
        except:
            DBSession.rollback()
            _error(traceback.print_exc())
            flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
            return redirect(self.default())
        else:
            flash(MSG_SAVE_SUCC, MESSAGE_INFO)
            return redirect(self.default())
Exemple #26
0
    def save_new(self):
        try:
            params = {}
            for k in ['customer_id', 'order_time',
                      'source_province_id', 'source_city_id', 'destination_province_id', 'destination_city_id',
                      'source_company_id', 'source_address', 'source_contact', 'source_tel', 'source_mobile',
                      'destination_company_id', 'destination_address', 'destination_contact', 'destination_tel', 'destination_mobile',
                      'ref_no', 'estimate_time', 'expect_time', 'actual_time', 'remark',
                      'payment_id', 'pickup_type_id', 'pack_type_id', 'qty', 'qty_ratio', 'vol', 'vol_ratio',
                      'weight', 'weight_ratio', 'weight_ratio', 'amount', 'insurance_charge', 'sendout_charge', 'receive_charge',
                      'package_charge', 'other_charge', 'load_charge', 'unload_charge', 'proxy_charge', 'note_id', 'note_no',
                      'source_sms', 'destination_sms',
                      ]:
                params[k] = _g(k)
            order = OrderHeader(**params)
            DBSession.add(order)
            DBSession.flush()

            no = _g('no')
            b = Barcode.getOrCreate(no, order.ref_no)
            order.barcode = b.img
            order.no = b.value
            b.status = 0  # mark the barcode is use

            DBSession.add(TransferLog(
                                      refer_id = order.id,
                                      transfer_date = dt.now().strftime(SYSTEM_DATETIME_FORMAT),
                                      type = 0,
                                      remark = LOG_CREATE_ORDER,
                                      ))

            item_json = _g('item_json', '')
            for item in json.loads(item_json):
                DBSession.add(ItemDetail(
                                         header = order, item_id = item['item_id'], qty = item['qty'] or None,
                                         vol = item['vol'] or None, weight = item['weight'] or None,
                                         remark = item['remark'] or None
                                         ))


            # handle the upload file
            order.attachment = multiupload()

            # add the contact to the master
            try:
                DBSession.query(CustomerContact).filter(and_(
                                                         CustomerContact.active == 0,
                                                         CustomerContact.type == "S",
                                                         CustomerContact.refer_id == order.source_company_id,
                                                         CustomerContact.name == order.source_contact
                                                         )).one()
            except:
                # can't find the persons in source's contacts
                DBSession.add(CustomerContact(
                                              customer_id = order.customer_id,
                                              type = "S",
                                              refer_id = order.source_company_id,
                                              name = order.source_contact,
                                              address = order.source_address,
                                              phone = order.source_tel,
                                              mobile = order.source_mobile
                                              ))


            # add the contact to the master
            try:
                DBSession.query(CustomerContact).filter(and_(
                                                         CustomerContact.active == 0,
                                                         CustomerContact.type == "T",
                                                         CustomerContact.refer_id == order.destination_company_id,
                                                         CustomerContact.name == order.destination_contact
                                                         )).one()
            except:
                # can't find the persons in des's contacts
                DBSession.add(CustomerContact(
                                              customer_id = order.customer_id,
                                              type = "T",
                                              refer_id = order.destination_company_id,
                                              name = order.destination_contact,
                                              address = order.destination_address,
                                              phone = order.destination_tel,
                                              mobile = order.destination_mobile
                                              ))
            DBSession.commit()



            flash(MSG_SAVE_SUCC, MESSAGE_INFO)
            return redirect(url_for('.view', action = 'review', id = order.id))
        except:
            _error(traceback.print_exc())
            flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
            DBSession.rollback()
            return redirect(self.default())
Exemple #27
0
    def deliver_save_revise(self):
        id = _g('id')
        if not id :
            flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
            return redirect(self.default())

        try:
            header = DBSession.query(DeliverHeader).get(id)
            fields = [
                      'ref_no', 'destination_province_id', 'destination_city_id', 'destination_address', 'destination_contact',
                      'destination_tel', 'destination_mobile', 'supplier_id', 'supplier_contact', 'supplier_tel',
                      'need_transfer', 'amount', 'remark', 'expect_time', 'order_time',
                      'insurance_charge', 'sendout_charge', 'receive_charge', 'package_charge', 'other_charge', 'carriage_charge',
                      'load_charge', 'unload_charge', 'proxy_charge', 'payment_id', 'pickup_type_id',
                      'qty', 'weight', 'vol', 'qty_ratio', 'weight_ratio', 'vol_ratio', 'shipment_type_id',
                      ]

            _remark = []
            old_info = header.serialize(fields)  # to used for the history log
            for f in fields:    setattr(header, f, _g(f))

            total_qty = total_vol = total_weight = 0

            for d in header.details:
                d.qty = _g('qty_%s' % d.id)
                d.vol = _g('vol_%s' % d.id)
                d.weight = _g('weight_%s' % d.id)
                d.insurance_charge = _g('insurance_charge_%s' % d.id)
                d.sendout_charge = _g('sendout_charge_%s' % d.id)
                d.receive_charge = _g('receive_charge_%s' % d.id)
                d.package_charge = _g('package_charge_%s' % d.id)
                d.load_charge = _g('load_charge_%s' % d.id)
                d.unload_charge = _g('unload_charge_%s' % d.id)
                d.other_charge = _g('other_charge_%s' % d.id)
                d.proxy_charge = _g('proxy_charge_%s' % d.id)
                d.carriage_charge = _g('carriage_charge_%s' % d.id)
                d.amount = _g('amount_%s' % d.id)
                d.order_header.cost = d.amount

                if d.qty : total_qty += float(d.qty)
                if d.vol : total_vol += float(d.vol)
                if d.weight : total_weight += float(d.weight)


            header.qty = total_qty
            header.vol = total_vol
            header.weight = total_weight

            # handle the file upload
            old_attachment_ids = map(lambda (k, v) : v, _gp("old_attachment_"))
            old_attachment_ids.extend(multiupload())
            header.attachment = old_attachment_ids

            DBSession.commit()

            new_info = header.serialize(fields)
            change_result = header.compare(old_info, new_info)
            header.insert_system_logs(change_result)

            flash(MSG_SAVE_SUCC, MESSAGE_INFO)
        except:
            _error(traceback.print_exc())
            DBSession.rollback()
            flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
        return redirect(self.default())
Exemple #28
0
    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))
Exemple #29
0
    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})
Exemple #30
0
    def in_note_save_new(self):
        params = {
                  "customer_id" : _g('customer_id'),
                  "so" : _g('so'),
                  "po" : _g('po'),
                  "dn" : _g('dn'),
                  "ref" : _g('ref'),
                  "remark" : _g('remark'),
                  }
        try:
            header = InventoryInNote(**params)
            DBSession.add(header)
            DBSession.flush()

            total_qty = total_area = total_weight = 0

            item_json = _g('item_json', '')
            for item in json.loads(item_json):
                if item['item_id']:
                    dbItem = DBSession.query(InventoryItem).get(item['item_id'])
                    try:
                        locationItem = DBSession.query(InventoryLocationItem).filter(and_(
                                                                                InventoryLocationItem.active == 0,
                                                                                InventoryLocationItem.item_id == item['item_id'],
                                                                                InventoryLocationItem.location_id == item['location_id'],
                                                                                )).with_lockmode("update").one()
                    except:
                        locationItem = InventoryLocationItem(item = dbItem, location_id = item['location_id'],)
                        DBSession.add(locationItem)
                        DBSession.flush()
                else:
                    dbItem = InventoryItem(name = item['item_name'], desc = item['desc'])
                    locationItem = InventoryLocationItem(item = dbItem, location_id = item['location_id'],)
                    DBSession.add_all([dbItem, locationItem])
                    DBSession.flush()


                d = InventoryNoteDetail(header_id = header.id, type = 'IN' , item = dbItem,
                                                      desc = item['desc'], qty = item['qty'] or 0, weight = item['weight'] or 0,
                                                      area = item['area'] or 0, remark = item['remark'],
                                                      location_id = item['location_id'],
                                                      )
                DBSession.add(d)
                if d.qty :
                    total_qty += int(d.qty)
                    locationItem.qty += int(d.qty)
                    locationItem.exp_qty += int(d.qty)
                if d.area :
                    total_area += float(d.area)
                    locationItem.area += float(d.area)
                    locationItem.exp_area += float(d.area)
                if d.weight :
                    total_weight += float(d.weight)
                    locationItem.weight += float(d.weight)
                    locationItem.exp_weight += float(d.weight)

            header.no = getInNoteNo(header.id)
            header.qty = total_qty
            header.weight = total_weight
            header.area = total_area

            DBSession.commit()
            flash(MSG_SAVE_SUCC, MESSAGE_INFO)
            return redirect(url_for(".view", action = "in_note_review", id = header.id))
        except:
            DBSession.rollback()
            _error(traceback.print_exc())
            flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
            return redirect(url_for(".view", action = "in_note"))