Beispiel #1
0
    def saveNewArticle(self):
        appid, title, sub_title, validate_date, desc, content = _gs('appid', 'title', 'sub_title', 'validate_date', 'desc', 'content')
        if not appid :
            flash(MSG_NO_ID_SUPPLIED, MESSAGE_WARNING)
            return redirect(url_for('.view'))

        if not title:
            flash(MSG_NO_ENOUGH_PARAMS, MESSAGE_WARNING)
            return redirect(url_for('.view', action = 'createArticle', appid = appid))

        try:
            article = AppArticle(
                             app_id = appid,
                             title = title,
                             sub_title = sub_title,
                             desc = desc,
                             content = content,
                             validate_date = validate_date,
                             )
            DBSession.add(article)
            DBSession.flush()
            article.seq = article.id
            DBSession.commit()
            flash(MSG_SAVE_SUCC, MESSAGE_INFO)
            return redirect(url_for(".view", action = "listArticle", appid = appid))
        except:
            DBSession.rollback()
            flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
            traceback.print_exc()
            return redirect(url_for(".view", action = "listArticle", appid = appid))
Beispiel #2
0
    def save_new(self):
        params = {
                   "name" : _g('name'),
                   "address" : _g('address'),
                   "manager" : _g('manager'),
                   "remark" : _g('remark'),
                   "parent_id" : _g('parent_id'),
                  }

        try:
            obj = InventoryLocation(**params)
            DBSession.add(obj)
            DBSession.flush()

            if params['parent_id']:
                parent = DBSession.query(InventoryLocation).get(obj.parent_id)
                obj.full_path = "%s%s" % (parent.full_path or '', params['name'])
                obj.full_path_ids = "%s|%s" % (parent.full_path_ids, obj.id)
            else:
                obj.full_path = params['name']
                obj.full_path_ids = obj.id

            DBSession.commit()
            flash(MSG_SAVE_SUCC, MESSAGE_INFO)
        except:
            DBSession.rollback()
            _error(traceback.print_exc())
        return redirect(self.default())
Beispiel #3
0
def save_register():
    cid = _g('customer_id' , None)
    user_params = {
                "name" : _g('name'),
                "password" : _g('password'),
                "email" : _g('email'),
                "first_name" : _g('first_name'),
                "last_name" : _g('last_name'),
                "phone" : _g('phone'),
                "mobile" : _g('mobile'),
                   }


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

    DBSession.add(User(**user_params))

    DBSession.commit()
    flash(MSG_SAVE_SUCC, MESSAGE_INFO)
    return redirect(url_for('bpAuth.login'))
Beispiel #4
0
 def saveNewApp(self):
     appName, appDesc = _gs('appName', 'appDesc')
     if not appName:
         flash(MSG_NO_APP_NAME, MESSAGE_WARNING)
         return redirect(url_for('.view', action = 'createApp'))
     try:
         DBSession.query(AppObject).filter(and_(AppObject.active == 0,
                                         AppObject.name == appName)).one()
     except:
         try:
             app = AppObject(name = appName, desc = appDesc)
             DBSession.add(app)
             DBSession.flush()
             url = createApp(session['user_profile']['id'],
                                 APP_FOLDER, APP_PACKAGE,
                                 'app%s' % app.id, app.name)
             if not url : raise Exception('App generation error!')
             url = '%s%s' % (WEBSITE_ROOT, url)
             imgFile = createQR(url)
             if not imgFile : raise Exception('QR code generation error!')
             DBSession.add(imgFile)
             app.appfile = imgFile
             DBSession.commit()
             flash(MSG_SAVE_SUCC, MESSAGE_INFO)
             self._updateAppInSession()
             return redirect(url_for('.view'))
         except:
             DBSession.rollback()
             flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
             return redirect(url_for('.view'))
     else:
         flash(MSG_APP_NAME_DUPLICATED, MESSAGE_WARNING)
         return redirect(url_for('.view', action = 'createApp'))
Beispiel #5
0
 def getOrCreate(clz, value, ref_no, status = 0):
     if value: # get the existing
         try:
             b = DBSession.query(clz).filter(clz.value == value).one()
             return b
         except:
             pass
     #create
     b = clz(value = value, ref_no = ref_no, status = status)
     DBSession.add(b)
     DBSession.flush()
     b.value = '%s%06d' % (dt.now().strftime('%y%m%d'), (b.id % 1000000))
     b.img = generate_barcode_file(b.value)
     return b
Beispiel #6
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"))
Beispiel #7
0
def upload(name):
    f = request.files.get(name, None)
    if not f : raise makeException(MSG_NO_FILE_UPLOADED)

    dir_path = os.path.join(UPLOAD_FOLDER_PREFIX, UPLOAD_FOLDER)

    if not os.path.exists(dir_path) : os.makedirs(dir_path)

    (pre, ext) = os.path.splitext(f.filename)

    converted_name = "%s%s" % (dt.now().strftime("%Y%m%d%H%M%S"), ext)
    path = os.path.join(dir_path, converted_name)
    f.save(path)

    db_file_name = os.path.basename(f.filename)
    db_file_path = os.path.join(UPLOAD_FOLDER, converted_name)
    u = UploadFile(create_by_id = session['user_profile']['id'], name = db_file_name, path = db_file_path, url = "/".join([UPLOAD_FOLDER_URL, converted_name]))
    DBSession.add(u)
    DBSession.flush()
    return u
Beispiel #8
0
def upload(name):
    f = request.files.get(name, None)
    if not f : raise makeException("No file upload!")
    if _allowedFile(f.filename):
        if not os.path.exists(UPLOAD_FOLDER) : os.makedirs(UPLOAD_FOLDER)
        converted_name = "%s.%s" % (dt.now().strftime("%Y%m%d%H%M%S"), f.filename.rsplit('.', 1)[1].lower())
        path = os.path.join(UPLOAD_FOLDER, converted_name)
        f.save(path)

        u = UploadFile(create_by_id = session['user_profile']['id'], name = secure_filename(f.filename), path = path, url = "/".join([UPLOAD_FOLDER_URL, converted_name]))
        DBSession.add(u)
        DBSession.flush()
        return u
#        u = connection.UploadFile()
#        u.id = u.getID()
#        u.uid = session['user_profile']['id']
#        u.name = unicode(secure_filename(f.filename))
#        u.path = path
#        u.url = "/".join([UPLOAD_FOLDER_URL, converted_name])
#        u.save()
#        return u
    else:
        raise makeException("Invalid file to upload!")
Beispiel #9
0
    def _subcompany(self, DBObj, _action, _fields, _contact_type, _index_html, _new_html, _update_html):
#        DBObj = CustomerSource
#        _action = "source"
#        _fields = ['name', 'province_id', 'city_id', 'remark', 'payment_id']
#        _contact_type = 'S'
#        _index_html = 'customer/customer_source_index.html'
#        _new_html = 'customer/customer_source_new.html'
#        _update_html = 'customer/customer_source_update.html'

        method = _g('m', 'LIST')
        if method not in ['LIST', 'NEW', 'UPDATE', 'DELETE', 'SAVE_NEW', 'SAVE_UPDATE', ]:
            flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR)
            return redirect(url_for('.view', action = 'index'))

        if method == 'LIST':
            id = _g('id')
            c = DBSession.query(Customer).get(id)
            result = DBSession.query(DBObj).filter(and_(DBObj.active == 0,
                                                        DBObj.customer_id == c.id)).order_by(DBObj.name)

            page = _g('page', 1)
            def url_for_page(**params): return url_for('.view', action = _action, m = 'LIST', page = params['page'], id = id)
            records = paginate.Page(result, page, show_if_single_page = True, items_per_page = PAGINATE_PER_PAGE, url = url_for_page)
            return render_template(_index_html, records = records, customer = c)
        elif method == 'NEW':
            customer_id = _g('customer_id')
            return render_template(_new_html, customer_id = customer_id)
        elif method == 'SAVE_NEW':
            try:
                params = {"customer_id" : _g('customer_id')}
                for f in _fields : params[f] = _g(f)
                obj = DBObj(**params)
                DBSession.add(obj)
                DBSession.flush()
                contact_json = _g('contact_json', '')
                for contact in json.loads(contact_json):
                    DBSession.add(CustomerContact(
                                                  customer_id = _g('customer_id'),
                                                  type = _contact_type,
                                                  refer_id = obj.id,
                                                  name = contact['contact_name'],
                                                  address = contact['contact_address'],
                                                  mobile = contact['contact_mobile'],
                                                  phone = contact['contact_phone'],
                                                  remark = contact['contact_remark'],
                                                  ))
                DBSession.commit()
                flash(MSG_SAVE_SUCC, MESSAGE_INFO)
            except:
                DBSession.rollback()
                flash(MSG_SERVER_ERROR, MESSAGE_ERROR)
            return redirect(url_for('.view', action = _action, id = obj.customer_id))

        elif method == 'UPDATE':
            source = DBSession.query(DBObj).get(_g('id'))
            if source.province_id:
                cities = source.province.children()
            else:
                cities = []
            contact_json = []
            for c in source.contacts():
                contact_json.append({
                                    "id" : "old_%s" % c.id,
                                    "contact_name" : c.name,
                                    "contact_address" : c.address,
                                    "contact_phone" : c.phone,
                                    "contact_mobile" : c.mobile,
                                    "contact_remark" : c.remark,
                                    })
            return render_template(_update_html, cities = cities,
                                   obj = source, contact_json = json.dumps(contact_json))

        elif method == 'SAVE_UPDATE':
            id = _g('id', None)
            if not id :
                flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
                return redirect(url_for('.view', action = _action))
            obj = DBSession.query(DBObj).get(id)
            if not obj :
                flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
                return redirect(url_for('.view', action = _action))

            for f in _fields : setattr(obj, f, _g(f))
            contact_ids = [c.id for c in obj.contacts()]
            contact_json = _g('contact_json', '')
            for c in json.loads(contact_json):
                if not c.get('id', None) : continue
                if isinstance(c['id'], basestring) and c['id'].startswith("old_"):  #existing contact
                    cid = c['id'].split("_")[1]
                    t = DBSession.query(CustomerContact).get(cid)
                    t.name = c.get('contact_name', None)
                    t.address = c.get('contact_address', None)
                    t.mobile = c.get('contact_mobile', None)
                    t.phone = c.get('contact_phone', None)
                    t.remark = c.get('contact_remark', None)
                    contact_ids.remove(t.id)
                else:
                    DBSession.add(CustomerContact(
                                                customer_id = obj.customer_id,
                                                type = _contact_type,
                                                refer_id = obj.id,
                                                name = c.get('contact_name', None),
                                                address = c.get('contact_address', None),
                                                mobile = c.get('contact_mobile', None),
                                                phone = c.get('contact_phone', None),
                                                email = c.get('contact_email', None),
                                                remark = c.get('contact_remark', None),
                                                  ))

            DBSession.query(CustomerContact).filter(CustomerContact.id.in_(contact_ids)).update({'active' : 1}, False)
            DBSession.commit()
            flash(MSG_UPDATE_SUCC, MESSAGE_INFO)
            return redirect(url_for('.view', action = _action, id = obj.customer_id))
        elif method == 'DELETE':
            id = _g('id', None)
            if not id :
                flash(MSG_NO_ID_SUPPLIED, MESSAGE_ERROR)
                return redirect(url_for('.view', action = _action))
            obj = DBSession.query(DBObj).get(id)
            if not obj :
                flash(MSG_RECORD_NOT_EXIST, MESSAGE_ERROR)
                return redirect(url_for('.view', action = _action))
            DBSession.query(DBObj).filter(DBObj.id == id).update({'active' : 1}, False)
            DBSession.commit()
            flash(MSG_DELETE_SUCC, MESSAGE_INFO)
            return redirect(url_for('.view', action = _action))
Beispiel #10
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())
Beispiel #11
0
def import_weiqian_targets(weiqian):
    print 'import weiqian targets'
    t1 = CustomerTarget(customer = weiqian, name = u'深圳市味来道贸易有限公司A', province_id = 19, city_id = 290)
    DBSession.flush()
    t1_c = CustomerContact(customer = weiqian, type = 'T', refer_id = t1.id, name = u'邓梦成', mobile = '13410716458', phone = '0755-89538779,83742178', address = u'南山区沙河西路深宝路交界处白沙物流旁(深圳市粮食集团曙光冷库)', remark = u'深圳代理商')

    t2 = CustomerTarget(customer = weiqian, name = u'广州白云沪苏贸易经营部', province_id = 19, city_id = 290)
    DBSession.flush()
    t2_c = CustomerContact(customer = weiqian, type = 'T', refer_id = t2.id, name = u'吴煌龙', mobile = '13798313454', phone = '0755-28273934', address = u'布吉莲花路莲山庄五村内围42号', remark = u'深圳代理商')

    t3 = CustomerTarget(customer = weiqian, name = u'香港港丰控股有限公司', province_id = 33, city_id = None)
    DBSession.flush()
    t3_c = CustomerContact(customer = weiqian, type = 'T', refer_id = t3.id, name = u'刘德基', mobile = None, phone = '0085292678917,0085225167033', email = '*****@*****.**', address = u'新界将军澳工业村 骏光街9号(惠康超市)- 牛奶公司冷藏货收货区', remark = u'香港代理商')

    t4 = CustomerTarget(customer = weiqian, name = u'深圳市味来道贸易有限公司B', province_id = 19, city_id = 290)
    DBSession.flush()
    t4_c = CustomerContact(customer = weiqian, type = 'T', refer_id = t4.id, name = u'邓梦成', mobile = None, phone = '0755-89538779,83472178', email = None, address = u'龙岗区坪山镇坑梓工业园沃尔玛中心配送仓', remark = u'深圳代理商')

    t5 = CustomerTarget(customer = weiqian, name = u'深圳市农批华兴经营部', province_id = 19, city_id = 290)
    DBSession.flush()
    t5_c = CustomerContact(customer = weiqian, type = 'T', refer_id = t5.id, name = u'邓老板', mobile = '13823636826', phone = None, email = None, address = u'龙岗区布路布吉警署后松园新村', remark = u'深圳代理商')

    t6 = CustomerTarget(customer = weiqian, name = u'深圳市金满源贸易有限公司', province_id = 19, city_id = 290)
    DBSession.flush()
    t6_c1 = CustomerContact(customer = weiqian, type = 'T', refer_id = t6.id, name = u'罗发财', mobile = '18926455915', phone = None, email = None, address = u'布吉镇坂田街道岗头风门坳村亚洲工业园15号', remark = u'深圳代理商')
    t6_c2 = CustomerContact(customer = weiqian, type = 'T', refer_id = t6.id, name = u'王进云', mobile = '13423967408', phone = '0755-29001027', email = '*****@*****.**', address = u'布吉镇坂田街道岗头风门坳村亚洲工业园15号', remark = u'深圳代理商')

    t7 = CustomerTarget(customer = weiqian, name = u'成都永盛食品有限责任公司', province_id = 23, city_id = 326)
    DBSession.flush()
    t7_c = CustomerContact(customer = weiqian, type = 'T', refer_id = t7.id, name = u'蒋志英', mobile = '18980019806', phone = '028-85354318', email = '*****@*****.**', address = u'锦江区琉璃场径天中路上东家园77路公交车总站', remark = u'成都代理商')

    t8 = CustomerTarget(customer = weiqian, name = u'湘潭市兴盛贸易有限公司', province_id = 18, city_id = 27)
    DBSession.flush()
    t8_c1 = CustomerContact(customer = weiqian, type = 'T', refer_id = t8.id, name = u'谭冰艳', mobile = '18608489007', phone = None, email = None, address = u'雨湖区草塘路61号', remark = u'湘潭代现商')
    t8_c2 = CustomerContact(customer = weiqian, type = 'T', refer_id = t8.id, name = u'周卫星', mobile = '13317425511', phone = '0731-55578399', email = None, address = u'雨湖区草塘路61号', remark = u'湘潭代现商')


    t9 = CustomerTarget(customer = weiqian, name = u'惠州市三林贸易有限公司', province_id = 19, city_id = 298)
    DBSession.flush()
    t9_c1 = CustomerContact(customer = weiqian, type = 'T', refer_id = t9.id, name = u'张君', mobile = None, phone = '0752-2695370', email = None, address = u'惠城区镇隆镇皇后村委斜对面', remark = u'惠州代理商')
    t9_c2 = CustomerContact(customer = weiqian, type = 'T', refer_id = t9.id, name = u'徐三林', mobile = '18688335596', phone = '0752-2695370', email = '*****@*****.**', address = u'惠城区镇隆镇皇后村委斜对面', remark = u'惠州代理商')

    t10 = CustomerTarget(customer = weiqian, name = u'佛山顺德区瑞驰贸易有限公司', province_id = 19, city_id = 293)
    DBSession.flush()
    t10_c1 = CustomerContact(customer = weiqian, type = 'T', refer_id = t10.id, name = u'梁友鸿', mobile = '13702622982', phone = '0757-2229201', email = None, address = u'顺德区大良大门小湾村为民街8号', remark = u'顺德代理商')
    t10_c2 = CustomerContact(customer = weiqian, type = 'T', refer_id = t10.id, name = u'温风涛', mobile = None, phone = None, email = None, address = u'顺德区大良大门小湾村为民街8号', remark = u'顺德代理商')

    t11 = CustomerTarget(customer = weiqian, name = u'东莞市良云贸易有限公司', province_id = 19, city_id = 304)
    DBSession.flush()
    t11_c1 = CustomerContact(customer = weiqian, type = 'T', refer_id = t11.id, name = u'钟丽情', mobile = '13431268281', phone = '0769-22467285', email = None, address = u'南城区白马翠园街西二环巷8号', remark = u'东莞代理商')
    t11_c2 = CustomerContact(customer = weiqian, type = 'T', refer_id = t11.id, name = u'朱小毛', mobile = '13728275577', phone = '0769-76922467285', email = '*****@*****.**', address = u'南城区白马翠园街西二环巷8号', remark = u'东莞代理商')

    t12 = CustomerTarget(customer = weiqian, name = u'厦门恒顺联商贸有限公司', province_id = 19, city_id = 288)
    DBSession.flush()
    t12_c = CustomerContact(customer = weiqian, type = 'T', refer_id = t12.id, name = u'朱蔚', mobile = '18927843611', phone = None, email = '*****@*****.**', address = u'白云区沙太北路大源南路自编33号', remark = u'广州代理商')

    t13 = CustomerTarget(customer = weiqian, name = u'广州市领隆贸易有限公司', province_id = 19, city_id = 288)
    DBSession.flush()
    t13_c = CustomerContact(customer = weiqian, type = 'T', refer_id = t13.id, name = u'曹领', mobile = '15989152636', phone = '020-84265759', email = '*****@*****.**', address = u'广州市白云区沙太北路大源南路自编33号', remark = u'广州代理商')

    t14 = CustomerTarget(customer = weiqian, name = u'广州沃奥贸易有限公司', province_id = 19, city_id = 288)
    DBSession.flush()
    t14_c = CustomerContact(customer = weiqian, type = 'T', refer_id = t14.id, name = u'林奇峰', mobile = '15989152636', phone = '020-81795981', email = None, address = u'白云区增槎路东旺市场南二排42档', remark = u'广州代理商')

    DBSession.add_all([
                       t1, t1_c, t2, t2_c, t3, t3_c, t4, t4_c, t5, t5_c, t6, t6_c1, t6_c2, t7, t7_c, t8, t8_c1, t8_c2, t9, t9_c1, t9_c2, t10, t10_c1, t10_c2,
                       t11, t11_c1, t11_c2, t12, t12_c, t13, t13_c, t14, t14_c
                       ])
Beispiel #12
0
def import_kinlong_target(kinlong):
    print "insert kinlong target"
    d = open('kinlong_contact.txt')
    for line in d:
        location, name, mobile = line.strip().split("|")
        location = unicode(location)
        try:
            c = DBSession.query(City).filter(City.name.op('like')('%%%s%%' % location[:2])).one()
            t = CustomerTarget(customer = kinlong, name = location, province_id = c.parent().id, city_id = c.id)
            DBSession.add(t)
            DBSession.flush()
            contact = CustomerContact(customer = kinlong, type = 'T', refer_id = t.id, name = name, mobile = mobile, phone = None, address = None)
            DBSession.add(contact)
        except:
            pass
    d.close()

    hangkou = CustomerTarget(customer = kinlong, name = u'汉口办(公共)', province_id = 17, city_id = 261)
    DBSession.flush()
    hangkou_c = CustomerContact(customer = kinlong, type = 'T', refer_id = hangkou.id, name = u'张明洋', mobile = '13407191121', phone = None, address = u'汉口')
    wuchang = CustomerTarget(customer = kinlong, name = u'武昌办公共、商用建筑销售部', province_id = 17, city_id = 261)
    shanghai = CustomerTarget(customer = kinlong, name = u'上海住宅开发部', province_id = 9, city_id = None)
    DBSession.flush()
    shanghai_c = CustomerContact(customer = kinlong, type = 'T', refer_id = shanghai.id, name = u'李金虎', mobile = '13774413112', phone = None, address = None)
    fuqing = CustomerTarget(customer = kinlong, name = u'福清销售点', province_id = 13, city_id = 207)
    DBSession.flush()
    fuqing_c = CustomerContact(customer = kinlong, type = 'T', refer_id = fuqing.id, name = u'陈文峰', mobile = '18259122060', phone = None, address = u'福清')
    huadu = CustomerTarget(customer = kinlong, name = u'花都办', province_id = 19, city_id = 288)
    DBSession.flush()
    huadu_c = CustomerContact(customer = kinlong, type = 'T', refer_id = huadu.id, name = u'彭双林', mobile = '13060809011', phone = None, address = u'花都')
    changshu = CustomerTarget(customer = kinlong, name = u'常熟办', province_id = 10, city_id = 170)
    DBSession.flush()
    changshu_c = CustomerContact(customer = kinlong, type = 'T', refer_id = changshu.id, name = u'梅陈赓', mobile = '15951100335', phone = None, address = u'常熟')
    kunshang = CustomerTarget(customer = kinlong, name = u'昆山销售点', province_id = 10, city_id = 170)
    DBSession.flush()
    kunshang_c = CustomerContact(customer = kinlong, type = 'T', refer_id = kunshang.id, name = u'肖杰', mobile = '13616218299', phone = None, address = u'昆山')
    wujiang = CustomerTarget(customer = kinlong, name = u'吴江销售点', province_id = 10, city_id = 170)
    DBSession.flush()
    wujiang_c = CustomerContact(customer = kinlong, type = 'T', refer_id = wujiang.id, name = u'向武将', mobile = '13862105593', phone = None, address = u'吴江')
    zjg = CustomerTarget(customer = kinlong, name = u'张家港销售点', province_id = 10, city_id = 170)
    DBSession.flush()
    zjg_c = CustomerContact(customer = kinlong, type = 'T', refer_id = zjg.id, name = u'胡伟', mobile = '15850181896', phone = None, address = u'张家港')
    yx = CustomerTarget(customer = kinlong, name = u'宜兴办', province_id = 10, city_id = 167)
    DBSession.flush()
    yx_c = CustomerContact(customer = kinlong, type = 'T', refer_id = yx.id, name = u'王伟', mobile = '13347926039', phone = None, address = u'宜兴')
    cx = CustomerTarget(customer = kinlong, name = u'慈溪销售点', province_id = 11, city_id = 180)
    DBSession.flush()
    cx_c = CustomerContact(customer = kinlong, type = 'T', refer_id = cx.id, name = u'刘晓', mobile = '13566087866', phone = None, address = u'慈溪')
    zj = CustomerTarget(customer = kinlong, name = u'诸暨销售点', province_id = 11, city_id = 184)
    DBSession.flush()
    zj_c = CustomerContact(customer = kinlong, type = 'T', refer_id = zj.id, name = u'叶坦', mobile = '13575559619', phone = None, address = u'诸暨')
    cn = CustomerTarget(customer = kinlong, name = u'苍南销售点', province_id = 11, city_id = 181)
    DBSession.flush()
    cn_c = CustomerContact(customer = kinlong, type = 'T', refer_id = cn.id, name = u'李志坚', mobile = '13646536682', phone = None, address = u'苍南')
    wl = CustomerTarget(customer = kinlong, name = u'温岭销售点', province_id = 11, city_id = 188)
    DBSession.flush()
    wl_c = CustomerContact(customer = kinlong, type = 'T', refer_id = wl.id, name = u'彭学江', mobile = '13957677975', phone = None, address = u'温岭')
    yw = CustomerTarget(customer = kinlong, name = u'义乌销售点', province_id = 11, city_id = 185)
    DBSession.flush()
    yw_c = CustomerContact(customer = kinlong, type = 'T', refer_id = yw.id, name = u'贡健', mobile = '15057840176', phone = None, address = u'义乌')


    DBSession.add_all([
                       hangkou, hangkou_c, wuchang, shanghai, shanghai_c, fuqing, fuqing_c, huadu, huadu_c, changshu, changshu_c, kunshang, kunshang_c,
                       wujiang, wujiang_c, zjg, zjg_c, yx, yx_c, cx, cx_c, zj, zj_c, cn, cn_c, wl, wl_c, yw, yw_c,
                       ])
Beispiel #13
0
def init():
    try:
        print "create tables"
        metadata.drop_all(engine, checkfirst = True)

        metadata.create_all(engine)

        print "insert default value"
        #add the default value here

        uAdmin = User(name = 'admin', email = '*****@*****.**', password = '******')
#        uKinlong = User(name = u'kinlong', email = '*****@*****.**', password = '******')
#        uWeiqian = User(name = u'weiqian', email = '*****@*****.**', password = '******')
        uKefua = User(name = u'kefu1', email = '*****@*****.**', password = '******')
        uWha = User(name = u'wh1', email = '*****@*****.**', password = '******')
        uFina = User(name = u'fin1', email = '*****@*****.**', password = '******')
        uUser1 = User(name = u'罗凌云', email = '*****@*****.**', password = '******')
        uUser2 = User(name = u'陈龙', email = '*****@*****.**', password = '******')
#        uUser3 = User(name = u'邓二', email = '*****@*****.**', password = '******')
        uUser4 = User(name = u'刘坤', email = '*****@*****.**', password = '******')
        uUser5 = User(name = u'何灿明', email = '*****@*****.**', password = '******')
#        uUser6 = User(name = u'黄燕琴', email = '*****@*****.**', password = '******')
        uUser7 = User(name = u'吴丽玲', email = '*****@*****.**', password = '******')
        uUser8 = User(name = u'徐腾芳', email = '*****@*****.**', password = '******')
        uUser9 = User(name = u'黄霄莹', email = '*****@*****.**', password = '******')
        uUser10 = User(name = u'林凤', email = '*****@*****.**', password = '******')
#        uUser11 = User(name = u'吴秋梅', email = '*****@*****.**', password = '******')
        uUser12 = User(name = u'林秀贤', email = '*****@*****.**', password = '******')
        uUser13 = User(name = u'曾德莲', email = '*****@*****.**', password = '******')
        uUser14 = User(name = u'李时坚', email = '*****@*****.**', password = '******')

        uUser15 = User(name = u'深福合力', email = '*****@*****.**', password = '******')


        pAdminManage = Permission(name = 'AMIN_MANAGE', desc = u'进入管理员控制台')
        pCreateUser = Permission(name = 'CREATE_USER', desc = u'创建新用户')
        pUpdateUser = Permission(name = 'UPDATE_USER', desc = u'更新用户信息')
        pDeleteUser = Permission(name = 'DELETE_USER', desc = u'删除用户')
        pSearchUser = Permission(name = 'SEARCH_USER', desc = u'查询用户')
        pManageUser = Permission(name = 'MANAGE_USER', desc = u'管理所有用户')
        pCreateGroup = Permission(name = 'CREATE_GROUP', desc = u'删除组')
        pUpdateGroup = Permission(name = 'UPDATE_GROUP', desc = u'更新组信息')
        pDeleteGroup = Permission(name = 'DELETE_GROUP', desc = u'删除组')
        pSearchGroup = Permission(name = 'SEARCH_GROUP', desc = u'查询所在组')
        pManageGroup = Permission(name = 'MANAGE_GROUP', desc = u'管理所有组')
        pCreatePermission = Permission(name = 'CREATE_PERMISSION', desc = u'创建新权限')
        pUpdatePermission = Permission(name = 'UPDATE_PERMISSION', desc = u'更新权限')
        pDeletePermission = Permission(name = 'DELETE_PERMISSION', desc = u'删除权限')
        pSearchPermission = Permission(name = 'SEARCH_PERMISSION', desc = u'查询所在权限')
        pManagePermission = Permission(name = 'MANAGE_PERMISSION', desc = u'管理所在权限')
        pCreateMaster = Permission(name = 'CREATE_MASTER', desc = u'创建新的系统设置')
        pUpdateMaster = Permission(name = 'UPDATE_MASTER', desc = u'更新现有的系统设置')
        pDeleteMaster = Permission(name = 'DELETE_MASTER', desc = u'删除系统设置')
        pSearchMaster = Permission(name = 'SEARCH_MASTER', desc = u'查询所有的系统设置')
        pManageMaster = Permission(name = 'MANAGE_MASTER', desc = u'进入系统设置控制台')
        pCreateOrder = Permission(name = 'CREATE_ORDER', desc = u'创建新的订单')
        pUpdateOrder = Permission(name = 'UPDATE_ORDER', desc = u'更新订单信息')
        pDeleteOrder = Permission(name = 'DELETE_ORDER', desc = u'删除订单')
        pSearchOrder = Permission(name = 'SEARCH_ORDER', desc = u'查询订单')
        pManageOrder = Permission(name = 'MANAGE_ORDER', desc = u'管理所有的订单')
        pSearchAllOrder = Permission(name = 'SEARCH_ALL_ORDER', desc = u'查询所有的订单')
        pCreateDeliver = Permission(name = 'CREATE_DELIVER', desc = u'创建新的送货单')
        pUpdateDeliver = Permission(name = 'UPDATE_DELIVER', desc = u'更新送货单信息')
        pDeleteDeliver = Permission(name = 'DELETE_DELIVER', desc = u'删除送货单信息')
        pSearchDeliver = Permission(name = 'SEARCH_DELIVER', desc = u'查询所在的送货单')
        pManageDeliver = Permission(name = 'MANAGE_DELIVER', desc = u'进入送货单管理控制台')
        pSearchAllDeliver = Permission(name = 'SEARCH_ALL_ELIVER', desc = u'查询所有的送货单')
        pCreateCustomer = Permission(name = 'CREATE_CUSTOMER', desc = u'创建新的客户')
        pUpdateCustomer = Permission(name = 'UPDATE_CUSTOMER', desc = u'更新客户信息')
        pDeleteCustomer = Permission(name = 'DELETE_CUSTOMER', desc = u'删除客户')
        pSearchCustomer = Permission(name = 'SEARCH_CUSTOMER', desc = u'查询所有的客户')
        pCreateSupplier = Permission(name = 'CREATE_SUPPLIER', desc = u'创建新的承运商')
        pUpdateSupplier = Permission(name = 'UPDATE_SUPPLIER', desc = u'更新承运商信息')
        pDeleteSupplier = Permission(name = 'DELETE_SUPPLIER', desc = u'删除承运商信息')
        pSearchSupplier = Permission(name = 'SEARCH_SUPPLIER', desc = u'查询所有的承运商信息')
        pCreateWarehouse = Permission(name = 'CREATE_WAREHOUSE', desc = u'创建新的仓存地点')
        pUpdateWarehouse = Permission(name = 'UPDATE_WAREHOUSE', desc = u'更新仓存地点信息')
        pDeleteWarehouse = Permission(name = 'DELETE_WAREHOUSE', desc = u'删除仓存地点')
        pSearchWarehouse = Permission(name = 'SEARCH_WAREHOUSE', desc = u'查询所有仓存地点')
        pManageFin = Permission(name = 'MANAGE_FIN', desc = u'进入财务管理控制台')
        pFinSearch = Permission(name = 'FIN_SEARCH', desc = u'查询订单信息')
        pFinApprove = Permission(name = 'FIN_APPROVE', desc = u'审核通过订单信息')
        pFinPaid = Permission(name = 'FIN_PAID', desc = u'确认客户是否已付款')
        pFinSupplierPaid = Permission(name = 'FIN_SUPPLIER_PAID', desc = u'确认是否已付款予承运商')



        gAdmin = Group(name = u'管理员组', display_name = u'管理员组', type = 0)
        gAdmin.permissions = [pAdminManage, pCreateUser, pUpdateUser, pDeleteUser, pSearchUser, pManageUser,
                              pCreateGroup, pUpdateGroup, pDeleteGroup, pSearchGroup, pManageGroup,
                              pCreatePermission, pUpdatePermission, pDeletePermission, pSearchPermission, pManagePermission,
                              pCreateMaster, pUpdateMaster, pDeleteMaster, pSearchMaster, pManageMaster,
                              pCreateOrder, pUpdateOrder, pDeleteOrder, pSearchOrder, pSearchAllOrder, pManageOrder,
                              pCreateDeliver, pUpdateDeliver, pDeleteDeliver, pSearchDeliver, pSearchAllDeliver, pManageDeliver,
                              pCreateCustomer, pUpdateCustomer, pDeleteCustomer, pSearchCustomer,
                              pCreateSupplier, pUpdateSupplier, pDeleteSupplier, pSearchSupplier,
                              pCreateWarehouse, pUpdateWarehouse, pDeleteWarehouse, pSearchWarehouse,
                              pManageFin, pFinSearch, pFinApprove, pFinPaid, pFinSupplierPaid
                              ]
        gAdmin.users = [uAdmin, ]
        gCustomer = Group(name = u'客户组', display_name = u'客户组', type = 0)
        gCustomer.permissions = [pCreateOrder, pUpdateOrder, pDeleteOrder, pSearchOrder, ]

        gKinlongGroup = Group(name = 'KINLONG_GROUP', display_name = 'KINLONG GROUP', type = 1)

        gWeiqianGroup = Group(name = 'WEIQIAN_GROUP', display_name = 'WEIQIAN GROUP', type = 1)

        gOfficer = Group(name = u'客服组', display_name = u'客服组', type = 0)
        gOfficer.permissions = [
                                pCreateMaster, pUpdateMaster, pDeleteMaster, pSearchMaster, pManageMaster,
                                pCreateOrder, pUpdateOrder, pDeleteOrder, pSearchOrder, pSearchAllOrder, pManageOrder,
                                pCreateDeliver, pUpdateDeliver, pDeleteDeliver, pSearchDeliver, pManageDeliver, pSearchAllDeliver,
                                ]
        gOfficer.users = [uKefua, uUser7, uUser9, uUser10, uUser13 ]

        gFin = Group(name = u'财务组', display_name = u'财务组', type = 0)
        gFin.permissions = [
                              pCreateMaster, pUpdateMaster, pDeleteMaster, pSearchMaster, pManageMaster,
                              pCreateOrder, pUpdateOrder, pDeleteOrder, pSearchOrder, pSearchAllOrder, pManageOrder,
                              pCreateDeliver, pUpdateDeliver, pDeleteDeliver, pSearchDeliver, pSearchAllDeliver, pManageDeliver,
                              pCreateCustomer, pUpdateCustomer, pDeleteCustomer, pSearchCustomer,
                              pCreateSupplier, pUpdateSupplier, pDeleteSupplier, pSearchSupplier,
                              pCreateWarehouse, pUpdateWarehouse, pDeleteWarehouse, pSearchWarehouse,
                              pManageFin, pFinSearch, pFinApprove, pFinPaid, pFinSupplierPaid
                            ]
        gFin.users = [uFina, uUser1, uUser2, uUser4, uUser5, uUser12, uUser15]

        gSupplier = Group(name = u'承运商组', display_name = u'承运商组', type = 0)
        gSupplier.permissions = [pUpdateDeliver, pSearchDeliver ]
#        gSupplier.users = [uSupplier]

        gSupplier1 = Group(name = 'SUPPLIER_1', display_name = 'Supplier1', type = 1)
#        gSupplier1.users = [uSupplier]
        gWarehouse = Group(name = u'仓库组', display_name = u'仓库组', type = 0)
        gWarehouse.permissions = [pUpdateOrder, pSearchOrder, pSearchAllOrder, pManageOrder,
                                  pCreateDeliver, pUpdateDeliver, pSearchDeliver, pSearchAllDeliver, pManageDeliver ]
        gWarehouse.users = [uWha, uUser8, uUser14]


        DBSession.add_all([
                            uAdmin, uKefua, uFina, uWha,
#                            uKefu2, uSupplier, uWarehouse,
                            uUser1, uUser2, uUser4, uUser5, uUser7, uUser8, uUser9, uUser10, uUser12, uUser13, uUser14, uUser15,
                            pCreateUser, pUpdateUser, pDeleteUser, pSearchUser, pManageUser,
                            pCreateGroup, pUpdateGroup, pDeleteGroup, pSearchGroup, pManageGroup,
                            pCreatePermission, pUpdatePermission, pDeletePermission, pSearchPermission, pManagePermission,
                            pCreateMaster, pUpdateMaster, pDeleteMaster, pSearchMaster, pManageMaster,
                            pCreateOrder, pUpdateOrder, pDeleteOrder, pSearchOrder, pSearchAllOrder, pManageOrder,
                            pCreateDeliver, pUpdateDeliver, pDeleteDeliver, pSearchDeliver, pSearchAllDeliver, pManageDeliver,
                            pCreateCustomer, pUpdateCustomer, pDeleteCustomer, pSearchCustomer,
                            pCreateSupplier, pUpdateSupplier, pDeleteSupplier, pSearchSupplier,
                            pCreateWarehouse, pUpdateWarehouse, pDeleteWarehouse, pSearchWarehouse,
                            gAdmin, gCustomer, gOfficer, gSupplier, gWarehouse,
                            gKinlongGroup, gWeiqianGroup,
                            ])


        for n, en, tn in [(u'米', u'meter', u'米'), (u'分米', u'dm', u'分米'), (u'厘米', u'cm', u'釐米'), (u'吨', u'ton', u'噸'), (u'千克', u'kg', u'千克'), (u'克', u'g', u'克'),
                     (u'箱', u'box', u'箱'), (u'瓶', u'bottle', u'瓶'), (u'只', u'pic', u'只'), (u'打', u'dozen', u'打'), ]:
            DBSession.add(ItemUnit(name = n, english_name = en, tradition_name = tn))


        for n, en, tn in [(u'吨', u'ton', u'噸'), (u'千克', u'kg', u'千克'), (u'克', u'g', u'克'), ]:
            DBSession.add(WeightUnit(name = n, english_name = en, tradition_name = tn))

#        location1 = InventoryLocation(name = u"深圳仓库", address = u"仓库地址 1", manager = "李先生", full_path = u"深圳仓库")
#        location1_A = InventoryLocation(name = u"A区", address = u"仓库地址 1", manager = "李先生", full_path = u"A区", parent = location1)
#        location1_B = InventoryLocation(name = u"B区", address = u"仓库地址 1", manager = "李先生", full_path = u"B区", parent = location1)
#        location1_C = InventoryLocation(name = u"C区", address = u"仓库地址 1", manager = "李先生", full_path = u"C区", parent = location1)
#        location2 = InventoryLocation(name = u"东莞仓库", address = u"仓库地址 2", manager = "林先生", full_path = u"东莞仓库")
#        location2_A = InventoryLocation(name = u"A区", address = u"仓库地址 2", manager = "林先生", full_path = u"A区", parent = location2)
#        location2_B = InventoryLocation(name = u"B区", address = u"仓库地址 2", manager = "林先生", full_path = u"B区", parent = location2)
#        location2_C = InventoryLocation(name = u"C区", address = u"仓库地址 2", manager = "林先生", full_path = u"C区", parent = location2)
#
#        DBSession.add_all([location1, location1_A, location1_B, location1_C,
#                           location2, location2_A, location2_B, location2_C,
#                           ])
#        location1.full_path_ids = location1.id
#        location2.full_path_ids = location2.id

        DBSession.flush()

        DBSession.add(ShipmentType(name = u"陆运"))
#        DBSession.add(ShipmentType(name = u"水运"))
#        DBSession.add(ShipmentType(name = u"空运"))

        payment1 = Payment(name = u"月付")
        payment2 = Payment(name = u"到付")
        payment3 = Payment(name = u"现付")
        DBSession.add_all([payment1, payment2, payment3])

        DBSession.add(Ratio(type = "QTY", value = 10))
        DBSession.add(Ratio(type = "VOL", value = 0.33))
        DBSession.add(Ratio(type = "WEIGHT", value = 0.5))

        DBSession.add(PickupType(name = u"自提"))
        DBSession.add(PickupType(name = u"送货"))
        DBSession.add(PickupType(name = u"司机直送"))
        DBSession.add(PickupType(name = u"送货上门"))
        DBSession.add(PickupType(name = u"送货上楼"))

        DBSession.add(PackType(name = u"纸箱"))
        DBSession.add(PackType(name = u"袋装"))
        DBSession.add(PackType(name = u"桶装"))
        DBSession.add(PackType(name = u"林架"))

        DBSession.add(Item(name = u"五金"))
        DBSession.add(Item(name = u"食品"))
        DBSession.add(Item(name = u"器材"))
        DBSession.add(Item(name = u"木料"))
        DBSession.add(Item(name = u"器具"))
        DBSession.add(Item(name = u"家具"))

        print 'insert diqu'
        province_f = open('sys2do/sql/master_province.sql')
        province_sql = "".join(province_f.readlines())
        province_f.close()

        city_f = open('sys2do/sql/master_city.sql')
        city_sql = "".join(city_f.readlines())
        city_f.close()

        conn = DBSession.connection()
        conn.execute(province_sql)
        conn.execute(city_sql)

        DBSession.commit()


        receiver1 = Receiver(code = u'粤BIP092', name = u'黄司机', tel = None, mobile = '15976884544',)
        receiver2 = Receiver(code = u'粤BQ4225', name = '叶司机', tel = None, mobile = '13682553458',)
        receiver3 = Receiver(code = u'粤BJU706', name = u'张司机', tel = None, mobile = '15813808186',)
        receiver4 = Receiver(code = u'粤BJX667', name = u'李司机', tel = None, mobile = '13590435287',)
        receiver5 = Receiver(code = u'粤BPY286', name = u'杨司机', tel = None, mobile = '13554881765',)
        receiver6 = Receiver(code = u'粤BVQ582', name = u'杨司机', tel = None, mobile = '13724255912',)
        receiver7 = Receiver(code = u'粤B2X846', name = u'巍司机', tel = None, mobile = '13410189026',)

        DBSession.add_all([receiver1, receiver2, receiver3, receiver4, receiver5, receiver6, receiver7])

        note1 = Note(code = '0001191-1', name = u'坚朗', province_id = 19, city_id = 290, apply_person_id = 1, apply_time = '2012-08-23',
                     begin_no = '1188000', end_no = '1188599', remark = u'坚朗专用二本')

        note2 = Note(code = '1001191-1', name = u'味千', province_id = 19, city_id = 290, apply_person_id = 1, apply_time = '2012-08-23',
                     begin_no = '2188000', end_no = '2188599', remark = u'味千专用一本')

        DBSession.add_all([
                           note1,
                           ])



        kinlong = Customer(name = u"广东坚朗五金制品股份有限公司", display_name = u'坚朗', province_id = 19, city_id = 304,
                           address = u"塘厦镇大坪村工业区卢地坑路3号", phone = "0769-82166666", contact_person = u'陈先生',
                           mobile = '12800138999', note = note1)

        kinlong_source1 = CustomerSource(customer = kinlong, name = u"坚朗一厂", province_id = 19, city_id = 304, payment = payment1)  #东莞
        kinlong_source2 = CustomerSource(customer = kinlong, name = u"坚朗二厂", province_id = 19, city_id = 304, payment = payment1)  #东莞
        kinlong_source3 = CustomerSource(customer = kinlong, name = u"坚朗三厂", province_id = 19, city_id = 304, payment = payment1)  #东莞


        DBSession.add_all([
                           kinlong, kinlong_source1, kinlong_source2, kinlong_source3,
                           ])

        DBSession.flush()


        kinlong_source1_c1 = CustomerContact(customer = kinlong, type = 'S', refer_id = kinlong_source1.id, name = u'李小明', mobile = u'13880138111', phone = u'1234561', address = u'厚街', is_default = 1)
        kinlong_source1_c2 = CustomerContact(customer = kinlong, type = 'S', refer_id = kinlong_source1.id, name = u'张三', mobile = u'13880138112', phone = u'1234562', address = u'长安',)

        kinlong_source2_c1 = CustomerContact(customer = kinlong, type = 'S', refer_id = kinlong_source2.id, name = u'王二', mobile = u'13880138113', phone = u'1234563', address = u'常平',)
        kinlong_source2_c2 = CustomerContact(customer = kinlong, type = 'S', refer_id = kinlong_source2.id, name = u'王小川', mobile = u'13880138114', phone = u'1234563', address = u'虎门',)

        kinlong_source3_c2 = CustomerContact(customer = kinlong, type = 'S', refer_id = kinlong_source3.id, name = u'钟远', mobile = u'13880138116', phone = u'1234563', address = u'大岭山',)

        DBSession.add_all([
                           kinlong_source1_c1, kinlong_source1_c2, kinlong_source2_c1, kinlong_source2_c2, kinlong_source3_c2,
                           ])

        #import the kinlong target contact
        import_kinlong_target(kinlong)
        #import the supplier
        import_supplier(payment1)


        weiqian = Customer(name = u"味千(中国)控投有限公司", display_name = u'味千', province_id = 19, city_id = 290,
                           address = u"福田区金田路3037号金中环商务大厦主楼23号", phone = "0755-8280 5333", contact_person = None,
                           mobile = None, note = note2)

        weiqian_source1 = CustomerSource(customer = weiqian, name = u"味千一厂", province_id = 19, city_id = 290, payment = payment1)

        DBSession.add_all([
                           weiqian, weiqian_source1
                           ])

        DBSession.flush()

        weiqian_source1_c1 = CustomerContact(customer = weiqian, type = 'S', refer_id = weiqian_source1.id, name = u'陆先生', mobile = u'13880138111', phone = u'1234561', address = u'福田', is_default = 1)
        DBSession.add_all([
                           weiqian_source1_c1,
                           ])

        import_weiqian_targets(weiqian)

        DBSession.commit()
        print "finish init!"
    except:
        traceback.print_exc()
        DBSession.rollback()
Beispiel #14
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())
Beispiel #15
0
def init():
    try:
        metadata.drop_all(engine)
        metadata.create_all(engine)

        #add the HK holiday 
        for d in ["0102", "0123", "0124", "012", "0404", "0406", "0407", "0409", "0428",
              "0501", "0623", "0702", "1001", "1002", "1023", "1225", "1226"]:
            DBSession.add(Holiday(year = 2012, month = d[:2], day = d[2:], region = 'HK'))

        permissions = ["ORDER_ADD", "ORDER_VIEW", "ORDER_CANCEL", "ORDER_UPDATE", "ORDER_VIEW_ALL",
                   "CLINIC_ADD", "CLINIC_VIEW", "CLINIC_VIEW_ALL", "CLINIC_UPDATE", "CLINIC_DELETE",
                   "DOCTOR_ADD", "DOCTOR_UPDATE", "DOCTOR_DELETE",
                   "NURSE_ADD", "NURSE_UPDATE", "NURSER_DELETE",
                   ]
        permissions_mapping = {}
        for p in permissions:
            obj = Permission(name = p)
            DBSession.add(obj)
            permissions_mapping[p] = obj

        groups = [
                 ("ADMINISTRATOR", "Administrator"), ("CLINIC_MANAGER", "Clinic Manager"),
                 ("DOCTOR", "Doctor"), ("NURSE", "Nurse"),
                 ("NORMALUSER", "Normal User"), ("TEMPUSER", "Temp User")
                 ]
        group_mapping = {}
        for g in groups:
            obj = Group(name = g[0], display_name = g[1])
            DBSession.add(obj)
            group_mapping[g[0]] = obj


        users = [
             ("*****@*****.**", "Admin",),
             ("*****@*****.**", "Clinic Manager 1",),
             ("*****@*****.**", "Clinic Manager 2",),
             ("*****@*****.**", "User 1"),
             ("*****@*****.**", "User 2"),
             ]

        users_mapping = {}
        for u in users:
            obj = User(email = u[0], password = '******', display_name = u[1])
            DBSession.add(obj)
            users_mapping[u[0]] = obj

        group_mapping['ADMINISTRATOR'].permissions = permissions_mapping.values()
        group_mapping['ADMINISTRATOR'].users = [users_mapping['*****@*****.**'], ]
        group_mapping['CLINIC_MANAGER'].permissions = [
                                                   permissions_mapping["CLINIC_VIEW"],
                                                   permissions_mapping["CLINIC_UPDATE"],
                                                   permissions_mapping["DOCTOR_ADD"],
                                                   permissions_mapping["DOCTOR_UPDATE"],
                                                   permissions_mapping["DOCTOR_DELETE"],
                                                   permissions_mapping["NURSE_ADD"],
                                                   permissions_mapping["NURSE_UPDATE"],
                                                   permissions_mapping["NURSER_DELETE"],
                                                   permissions_mapping["ORDER_VIEW"],
                                                   permissions_mapping["ORDER_CANCEL"],
                                                   permissions_mapping["ORDER_UPDATE"],
                                                   ]
        group_mapping['CLINIC_MANAGER'].users = [users_mapping['*****@*****.**'], users_mapping['*****@*****.**'], ]
        group_mapping['DOCTOR'].permissions = [
                                               permissions_mapping["ORDER_VIEW"],
                                               permissions_mapping["ORDER_CANCEL"],
                                               permissions_mapping["ORDER_UPDATE"],
                                               ]
        group_mapping['NURSE'].permissions = [
                                               permissions_mapping["ORDER_VIEW"],
                                               permissions_mapping["ORDER_CANCEL"],
                                               permissions_mapping["ORDER_UPDATE"],
                                              ]

        group_mapping['NORMALUSER'].permissions = [
                                               permissions_mapping["ORDER_ADD"],
                                               permissions_mapping["ORDER_VIEW"],
                                               permissions_mapping["ORDER_CANCEL"],
                                               ]
        group_mapping['NORMALUSER'].uses = [users_mapping['*****@*****.**'], users_mapping['*****@*****.**'], ]


        from clinic_list import clinics
        clinics_mapping = {}
        for (code, name, address, address_tc, tel, area_id, coordinate) in clinics:
            obj = Clinic(code = unicode(code.strip()), name = unicode(name.strip()),
                         address = unicode(address.strip()), address_tc = unicode(address_tc.strip()),
                         tel = unicode(tel.strip()), area_id = area_id or None,
                         coordinate = coordinate.strip()
                         )
            DBSession.add(obj)
            clinics_mapping[code] = obj



        default_worktime = {
                          "MONDAY" : [ ],
                          "TUESDAY" : [],
                          "WEDNESDAY" : [],
                          "THURSDAY" : [],
                          "FRIDAY" : [],
                          "SATURDAY" : [],
                          "SUNDAY" : [],
                          "HOLIDAY" : [],
                          "SPECIAL" : [],
                          }


        from doctors_list import doctors
        doctors_count = {}
        for (code, first_name, last_name, worktime) in doctors:

            if code in doctors_count : doctors_count[code] += 1
            else : doctors_count[code] = 1

            email = u"*****@*****.**" % (code, doctors_count[code])

            obj = User(email = email, password = u'aa', display_name = email)
            obj.groups = [group_mapping['DOCTOR']]
            DBSession.add(obj)
            DBSession.flush()

            tempWorkTime = default_worktime.copy()
            tempWorkTime.update(worktime)
            wt = {}
            for k, v in tempWorkTime.items():
                wt[k] = map(lambda o:{"times" : o, "seats" : 4}, v)

            objprofile = DoctorProfile(user_id = obj.id, worktime_setting = wt)
            if code in clinics_mapping : objprofile.clinics = [clinics_mapping[code]]
            DBSession.add(objprofile)

        area = {
            ('香港島', 'Hong Kong') : [('上環', 'Sheung Wan'), '大坑', '山頂', ('中環', 'Central') , '蘇豪', '蘭桂坊', ('天后', 'Tin Hau'), ('太古', 'Tai Koo'), ('北角', 'North Point'), '半山', '石澳', ('西環', 'Sai Wan'), '赤柱', '金鐘', ('柴灣', 'Chai Wan'), ('灣仔', 'Wan Chai') , ('西灣河', 'Sai Wan Ho'), ('杏花村', 'Heng Fa Chuen'), '香港仔', '淺水灣', '深水灣', ('跑馬地', 'Happy Valley'), ('筲箕灣', 'Shau Kei Wan'), ('銅鑼灣', 'Causeway Bay') , ('鴨脷洲', 'Ap Lei Chau'), '薄扶林', '數碼港', ('鰂魚涌', 'Quarry Bay')],
            ('九龍', 'Kowloon') : [('太子', 'Prince Edward'), ('佐敦', 'Jordan'), ('旺角', 'Mong Kok'), '油塘', ('紅磡', 'Hung Hom'), ('美孚', 'Mei Foo'), ('彩虹', 'Choi Hung'), ('樂富', 'Lok Fu'), ('藍田', 'Lam Tin'), ('觀塘', 'Kwun Tong'), ('九龍城', 'Kowloon City'), '九龍塘', ('九龍灣', 'Kowloon Bay'), ('土瓜灣', 'To Kwa Wan'), ('大角咀', 'Tai Kok Tsui'), ('牛頭角', 'Ngau Tau Kok'), ('石硤尾', 'Shek Kip Mei'), ('尖沙咀', 'Tsim Sha Tsui'), '諾士佛臺', ('何文田', 'Ho Man Tin'), ('油麻地', 'Yau Ma Tei'), ('長沙灣', 'Cheung Sha Wan'), ('荔枝角', 'Lai Chi Kok'), ('深水埗', 'Sham Shui Po'), ('黃大仙', 'Wong Tai Sin'), ('慈雲山', 'Tsz Wan Shan'), ('新蒲崗', 'San Po Kong'), ('鯉魚門', 'Lei Yue Mun'), ('鑽石山', 'Diamond Hill')],
            ('新界', 'New Territories') : [('上水', 'Sheung Shui'), ('大埔', 'Tai Po'), ('大圍', 'Tai Wai'), ('元朗', 'Yuen Long'), ('太和', 'Tai Wo'), ('屯門', 'Tuen Mun'), '火炭', ('西貢', 'Sai Kung'), ('沙田', 'Sha Tin'), ('青衣', 'Tsing Yi'), ('粉嶺', 'Fanling'), ('荃灣', 'Tsuen Wan'), '馬灣', ('深井', 'Sham Tseng'), ('葵芳', 'Kwai Fong'), ('葵涌', 'Kwai Chung'), '羅湖', ('天水圍', 'Tin Shui Wai'), '流浮山', ('馬鞍山', 'Ma On Shan'), ('將軍澳', 'Tseung Kwan O'), '落馬洲'],
            ('離島', 'Outlying Islands') : ['大澳', '坪洲', ('東涌', 'Tung Chung'), '長洲', '大嶼山', ('赤鱲角', 'Chek Lap Kok'), '南丫島', '愉景灣', '蒲苔島'],
        }

        for k, v in area.items():
            dis = District(name = unicode(k[1]), name_tc = unicode(k[0]))
            DBSession.add(dis)
            for d in v :
                if type(d) == tuple:
                    DBSession.add(Area(name = unicode(d[0]), name_tc = unicode(d[1]), district = dis))
                else:
                    DBSession.add(Area(name = unicode(d), district = dis))




        DBSession.commit()
    except:
        traceback.print_exc()
        DBSession.rollback()
Beispiel #16
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"))