Exemplo n.º 1
0
def init():
    global index_manager, catalog_manager, parser
    index_manager = IndexManager.IndexManager(FileManager.load_index())
    catalog_manager = CatalogManager.CatalogManager()
    catalog_manager.create_table_catalog(FileManager.load_catalog(0))
    catalog_manager.create_index_catalog(FileManager.load_catalog(1))
    parser = Interpreter.command(catalog_manager)
    RecordManager.init(index_manager, catalog_manager)
Exemplo n.º 2
0
def flush():
    global index_manager, catalog_manager, parser
    RecordManager.buf.save_all()
    FileManager.save_index(index_manager.Store())
    FileManager.save_catalog(0, catalog_manager.store_table_catalog())
    FileManager.save_catalog(1, catalog_manager.store_index_catalog())

    index_manager = IndexManager.IndexManager(FileManager.load_index())
    catalog_manager = CatalogManager.CatalogManager()
    catalog_manager.create_table_catalog(FileManager.load_catalog(0))
    catalog_manager.create_index_catalog(FileManager.load_catalog(1))
    parser = Interpreter.command(catalog_manager)
    RecordManager.init(index_manager, catalog_manager)
    print('All commited.')
Exemplo n.º 3
0
    def get(self):
        record_list = RecordManager.get_unfinished_record()
        for record in record_list:
            # Notifying the User when 30 minutes passed
            if ((datetime.datetime.now() - record[3]) > datetime.timedelta(minutes = 30) and
            (datetime.datetime.now() - record[3]) < datetime.timedelta(minutes = 31)):
                print "sending wechat message"
                WechatMessageManager.record_remind(record[1])

            # set record customer breach when 1 hour passed
            elif (datetime.datetime.now() - record[3]) > datetime.timedelta(hours = 1):
                WechatMessageManager.customer_breach_remind(record[1])
                RecordManager.record_breach(record[0])
            # else:
                # print "record refreshing..."
Exemplo n.º 4
0
    def get(self):
        customer_id = OAuthManager.get_openid_base(self)
        now_date = datetime.datetime.now().date()

        record_list = []
        # get record this month 
        this_month = datetime.datetime.now().date().month
        start_date = now_date.replace(day = 01)
        end_date = now_date.replace(month = this_month + 1,day = 01) - datetime.timedelta(days = 1)
        record_list_this_month = RecordManager.get_records_interval_customer(customer_id, str(start_date), str(end_date))
        for record in record_list_this_month:
            record.append(CommentManager.has_comment(record[0]))
        if len(record_list_this_month) > 0:
            record_list.append(record_list_this_month)

        # get record one month before
        one_month_before = this_month - 1
        if one_month_before == 0:
            one_month_before = 12
            star_date_one_month_before = now_date.replace(year = datetime.datetime.now().date().year - 1, month = one_month_before, day = 01)
            end_date_one_month_before = now_date.replace(day = 01) - datetime.timedelta(days = 1)
        else:
            star_date_one_month_before = now_date.replace(month = one_month_before, day = 01)
            end_date_one_month_before = now_date.replace(month = this_month, day = 01) - datetime.timedelta(days = 1)
        record_list_one_month_before = RecordManager.get_records_interval_customer(customer_id, str(star_date_one_month_before), str(end_date_one_month_before))
        for record in record_list_one_month_before:
            record.append(CommentManager.has_comment(record[0]))
        if len(record_list_one_month_before) > 0:
            record_list.append(record_list_one_month_before)

        # get record two month before
        two_month_before = this_month - 2
        if two_month_before <= 0:
            two_month_before = two_month_before + 12
            star_date_two_month_before = now_date.replace(year = datetime.datetime.now().date().year - 1, month = two_month_before, day = 01)
            end_date_two_month_before = now_date.replace(year = datetime.datetime.now().date().year - 1, month = one_month_before, day = 01) - datetime.timedelta(days = 1)
        else:
            star_date_two_month_before = now_date.replace(month = two_month_before, day = 01)
            end_date_two_month_before = now_date.replace(month = one_month_before, day = 01) - datetime.timedelta(days = 1)
        record_list_two_month_before = RecordManager.get_records_interval_customer(customer_id, str(star_date_two_month_before), str(end_date_two_month_before))
        for record in record_list_two_month_before:
            record.append(CommentManager.has_comment(record[0]))
        if len(record_list_two_month_before) > 0:
            record_list.append(record_list_two_month_before)

        # record_list = [record_list_this_month, record_list_one_month_before, record_list_two_month_before]

        self.render("../static/template/CustomerServiceRecord.html", customer_id=customer_id, record_list = record_list)
Exemplo n.º 5
0
def shop_rank(longitude, latitude):
    """ranking the shop nearby

    Args:
        longitude: customer longitude
        latitude: customer latitude

    Returns:
        shoplist[0][0]:shopId of best shop
        shoplist[0][1]:shopName of best shop
        ...
        shoplist[7][10]:password of eighth shop
    """
    # get shop nearby
    shoplist_tuple = ShopInfoManager.get_shop_nearby(longitude, latitude)
    shoplist = [list(rec) for rec in shoplist_tuple]

    # get shop available (auto_order > 0) in shop nearby
    shop_available = []
    for shop in shoplist:
        auto_order_num = AutoOrderManager.get_order_num(shop[0])
        # print auto_order_num
        if auto_order_num != None and int(auto_order_num) > 0:
            shop_available.append(shop)

    # get shop rank in shop avilable
    shop_ranking = []
    for shop in shop_available:
        # calculate duration
        ori_lng = str(longitude)
        ori_lat = str(latitude)
        des_lng = ShopInfoManager.get_longitude(shop[0])
        des_lat = ShopInfoManager.get_latitude(shop[0])
        # print 'class CustomerShopListHandler shop_rank shop name',shop[1]
        distance_meter = BaiduMapManager.get_distance_by_latlng(
            ori_lat, ori_lng, des_lat, des_lng)
        if distance_meter == -1:
            continue
        distance = float(distance_meter) / 1000
        distance = '%.2f' % distance
        shop.append(distance)
        # calculate busy
        auto_order_num = int(AutoOrderManager.get_order_num(
            shop[0]))  #FIXME:(HXM)是否有可能随时变为0或None
        coming_car = int(RecordManager.get_unfinished_record_num(shop[0]))
        busy = coming_car / (auto_order_num + coming_car)
        # get starRating
        starRating = ShopInfoManager.get_starRating(shop[0])
        # print "duration:" + str(duration)

        # calculate rank using busy, duration, starRating
        rank = 1 * busy + 2 * starRating + 1 * float(distance)
        shop.append(rank)
        shop_ranking.append(shop)

    # get top eight shop
    top_eight = sort_shop(shop_ranking)

    result = top_eight
    return result
    def get(self):
        record_list = RecordManager.get_unfinished_record()
        for record in record_list:
            # Notifying the User when 30 minutes passed
            if ((datetime.datetime.now() - record[3]) >
                    datetime.timedelta(minutes=30)
                    and (datetime.datetime.now() - record[3]) <
                    datetime.timedelta(minutes=31)):
                print "sending wechat message"
                WechatMessageManager.record_remind(record[1])

            # set record customer breach when 1 hour passed
            elif (datetime.datetime.now() -
                  record[3]) > datetime.timedelta(hours=1):
                WechatMessageManager.customer_breach_remind(record[1])
                RecordManager.record_breach(record[0])
Exemplo n.º 7
0
def select_index(table_name, attrs, index_conditions, other_conditions):
    all_attrs = catalog_manager.get_attribute(table_name)
    length_list = []
    for i in attrs:
        for j in all_attrs:
            if j[0] == i:
                if j[1] == 'int' or j[1] == 'float':
                    length_list.append((max((len(i), 12)), 0))
                else:
                    length_list.append((max((len(i), j[2])), 1))
                break
    res = RecordManager.select_index(table_name, attrs, index_conditions,
                                     other_conditions)
    if len(res) == 0:
        print('Empty set ({:.2f} sec)'.format(time.process_time() -
                                              start_time))
    else:
        print(format_record(None, length_list))
        print(format_record(attrs, length_list))
        print(format_record(None, length_list))
        for i in res:
            print(format_record(i, length_list))
        print(format_record(None, length_list))
        print('{} rows in set ({:.2f} sec)'.format(
            len(res),
            time.process_time() - start_time))
Exemplo n.º 8
0
def shop_rank(longitude, latitude):
    """ranking the shop nearby

    Args:
        longitude: customer longitude
        latitude: customer latitude

    Returns:
        shoplist[0][0]:shopId of best shop
        shoplist[0][1]:shopName of best shop
        ...
        shoplist[7][10]:password of eighth shop
    """
    # get shop nearby
    shoplist_tuple = ShopInfoManager.get_shop_nearby(longitude, latitude)
    shoplist = [list(rec) for rec in shoplist_tuple]

    # get shop available (auto_order > 0) in shop nearby
    shop_available = []
    for shop in shoplist:
        auto_order_num = AutoOrderManager.get_order_num(shop[0])
        # print auto_order_num
        if auto_order_num != None and int(auto_order_num) > 0:
            shop_available.append(shop)

    # get shop rank in shop avilable
    shop_ranking = []
    for shop in shop_available:
        # calculate duration
        ori_lng = str(longitude)
        ori_lat = str(latitude)
        des_lng = ShopInfoManager.get_longitude(shop[0])
        des_lat = ShopInfoManager.get_latitude(shop[0])
        # print 'class CustomerShopListHandler shop_rank shop name',shop[1]
        distance_meter = BaiduMapManager.get_distance_by_latlng(ori_lat, ori_lng, des_lat, des_lng)
        if distance_meter==-1:
            continue
        distance = float(distance_meter) / 1000
        distance = '%.2f' % distance
        shop.append(distance)
        # calculate busy
        auto_order_num = int(AutoOrderManager.get_order_num(shop[0]))    #FIXME:(HXM)是否有可能随时变为0或None
        coming_car = int(RecordManager.get_unfinished_record_num(shop[0]))
        busy = coming_car / (auto_order_num + coming_car)
        # get starRating
        starRating = ShopInfoManager.get_starRating(shop[0])
        # print "duration:" + str(duration)

        # calculate rank using busy, duration, starRating
        rank = 1 * busy + 2 * starRating + 1 * float(distance)
        shop.append(rank)
        shop_ranking.append(shop)

    # get top eight shop
    top_eight = sort_shop(shop_ranking)

    result = top_eight
    return result
Exemplo n.º 9
0
 def get(self):
     customer_id = self.get_argument('customer_id')
     record_id = self.get_argument('recordId')
     is_commented = CommentManager.has_comment(record_id)
     shop_name = CommentManager.get_comment_shopname(record_id)[0]
     if customer_id == RecordManager.get_customerId(record_id):
         self.render("../static/template/CustomerComment.html",
                     shop_name=shop_name, recordId = record_id,
                     isCommented=is_commented)
Exemplo n.º 10
0
 def post(self):
     record_id = self.get_argument('recordId')
     star_rating = self.get_argument('starRating')
     content = self.get_argument('comment')
     comment_time = datetime.now().strftime("%y-%m-%d %H:%M:%S")
     CommentManager.set_comment(record_id, star_rating, content, comment_time)
     shopId = RecordManager.get_shopId(recordId)
     ShopInfoManager.update_comment_starRating(shopId)
     self.write("comment success")
Exemplo n.º 11
0
    def post(self):
        # add record when customer make an appointment
        customerId = self.get_argument('customerId')
        shopId_order = self.get_argument('shopId_order')

        plate_number = CustomerPersonInfoManager.get_plateNumber(customerId)

        auto_order_num = AutoOrderManager.get_order_num(shopId_order)
        
        if plate_number == None:
            self.write("unset plate number")
        elif RecordManager.is_customer_breach(customerId):
            self.write("customer breach")
        elif RecordManager.has_customer_unfinished_record(customerId):
            self.write("has unfinished record")
        elif auto_order_num <= 0:
            self.write("has no auto order")
        else:
            auto_order_num = AutoOrderManager.get_order_num(shopId_order)
            auto_order_num = int(auto_order_num) - 1
            AutoOrderManager.set_order_num(shopId_order, auto_order_num)

            if auto_order_num >= 0:
                shopId_order = self.get_argument('shopId_order')
                record_time = str(datetime.datetime.now()).split('.')[0]
                # get customer location
                Location = CustomerPersonInfoManager.get_location(customerId)

                ori_lng = float(Location.split(',')[0])
                ori_lat = float(Location.split(',')[1])

                # calculate journeyTime
                des_lng = ShopInfoManager.get_longitude(shopId_order)
                des_lat = ShopInfoManager.get_latitude(shopId_order)
                duration = BaiduMapManager.get_duration_by_latlng(ori_lat, ori_lng, des_lat, des_lng)
                arrive_time = datetime.datetime.now() + datetime.timedelta(seconds = duration)
                journey_time = str(arrive_time).split('.')[0]

                RecordManager.add_record(customerId, shopId_order, record_time, journey_time)
                WechatMessageManager.customer_order_remind(customerId, shopId_order)
            else:
                AutoOrderManager.set_order_num(shopId_order, 0)
                self.write("has no auto order")
Exemplo n.º 12
0
 def get(self):
     customer_id = self.get_argument('customer_id')
     record_id = self.get_argument('recordId')
     is_commented = CommentManager.has_comment(record_id)
     shop_name = CommentManager.get_comment_shopname(record_id)[0]
     if customer_id == RecordManager.get_customerId(record_id):
         self.render("../static/template/CustomerComment.html",
                     shop_name=shop_name,
                     recordId=record_id,
                     isCommented=is_commented)
Exemplo n.º 13
0
 def post(self):
     record_id = self.get_argument('recordId')
     star_rating = self.get_argument('starRating')
     content = self.get_argument('comment')
     comment_time = datetime.now().strftime("%y-%m-%d %H:%M:%S")
     CommentManager.set_comment(record_id, star_rating, content,
                                comment_time)
     shopId = RecordManager.get_shopId(recordId)
     ShopInfoManager.update_comment_starRating(shopId)
     self.write("comment success")
Exemplo n.º 14
0
def customer_comment_remind(recordId):
    """remind customer when customer arrived shop

    Args:
        recordId:
    """
    # get access_token
    url_request_token = (
        "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
        "&appid=wx97b25a5e35916ef6&secret=eff7f6509ec87516cb0c442aec7dd7e9")
    urlfile = urllib2.urlopen(url_request_token)
    data_token = urlfile.read()
    data_token = json.loads(data_token)
    access_token = data_token["access_token"]

    # send remind message
    url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s" % access_token

    record = RecordManager.get_recordAllInfo(recordId)
    commenturl = "http://2.cargotest.sinaapp.com/customercomment?recordId=%s&customer_id=%s" % (
        recordId, record[1])
    picurl = ShopPhotoManager.get_shop_photo_urls(record[2])[0]
    print picurl

    data_json = """{
    "touser":"******",
    "msgtype":"news",
    "news":{
        "articles": [
         {
             "title":"您已确认到店,请在完成服务后评价",
             "description":"点击进行评价",
             "url":"%s",
             "picurl":"%s"
         }
         ]
    }
    }""" % (record[1], commenturl, picurl)
    req = urllib2.Request(url)

    content_len = len(data_json) + 44  # when you use chinese in uft8

    res = urllib2.urlopen(req, data_json)
Exemplo n.º 15
0
def customer_comment_remind(recordId):
    """remind customer when customer arrived shop

    Args:
        recordId:
    """
    # get access_token
    url_request_token = ("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
                        "&appid=wx97b25a5e35916ef6&secret=eff7f6509ec87516cb0c442aec7dd7e9")
    urlfile = urllib2.urlopen(url_request_token)
    data_token = urlfile.read()
    data_token = json.loads(data_token)
    access_token = data_token["access_token"]

    # send remind message
    url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s" % access_token

    record = RecordManager.get_recordAllInfo(recordId)
    commenturl = "http://2.cargotest.sinaapp.com/customercomment?recordId=%s&customer_id=%s" % (recordId, record[1])
    picurl = ShopPhotoManager.get_shop_photo_urls(record[2])[0]
    print picurl

    data_json = """{
    "touser":"******",
    "msgtype":"news",
    "news":{
        "articles": [
         {
             "title":"您已确认到店,请在完成服务后评价",
             "description":"点击进行评价",
             "url":"%s",
             "picurl":"%s"
         }
         ]
    }
    }""" % (record[1], commenturl, picurl)
    req = urllib2.Request(url)

    content_len = len(data_json)+44 # when you use chinese in uft8

    res = urllib2.urlopen(req, data_json)
Exemplo n.º 16
0
    def post(self):
        """process with specific operation by arguments
        """
        # print 'class ShopMainHandler post() self.current_user: %s' % self.current_user

        # get shop id
        username = tornado.escape.xhtml_escape(self.current_user)
        shop_id = ShopInfoManager.get_shopId_by_account(username)

        # if request for records
        if 'record_id' in self.request.arguments:
            record_id = long(self.get_argument('record_id'))

            # if request for all unfinished records
            if record_id == -1:
                records = RecordManager.get_unfinished_records_by_shopid(
                    shop_id)

                # sort as reverse order by record id
                records.sort(key=lambda x: x[0], reverse=True)

                # convert to json
                dict_records = convert_records_array_to_dict(records)
                json_records = json.dumps(dict_records)
                self.write(json_records)
                return
            # else request for latest unfinished records
            else:
                records = RecordManager.get_unfinished_records_after(
                    shop_id, record_id)
                records.sort(key=lambda x: x[0], reverse=True)
                dict_records = convert_records_array_to_dict(records)
                json_records = json.dumps(dict_records)

                self.write(json_records)
                return

        # if request for records in interval time
        elif 'start_time' and 'end_time' in self.request.arguments:
            start_time = self.get_argument('start_time')
            end_time = self.get_argument('end_time')

            records = RecordManager.get_records_interval(
                shop_id, start_time, end_time)
            json_records = json.dumps(convert_records_array_to_dict(records))

            self.write(json_records)
            return

        # if a record has finished, save it
        elif 'finish_record_id' in self.request.arguments:
            finish_record_id = self.get_argument('finish_record_id')
            WechatMessageManager.customer_comment_remind(finish_record_id)
            RecordManager.set_finish(finish_record_id)
            self.write(SET_RECORD_FINISH_SUCCEEDED)
            return

        # set auto order number
        elif 'auto_order_num' in self.request.arguments:
            set_order_num = self.get_argument('auto_order_num')
            AutoOrderManager.set_order_num(shop_id, set_order_num)
            self.write(AUTO_ORDER_NUMBER_SET_SUCCEEDED)
            return

        # request for comment by record id
        elif 'comment_record_id' in self.request.arguments:
            comment_record_id = self.get_argument('comment_record_id')
            comment = CommentManager.get_comment_content('comment_record_id')
            if comment == None:
                comment = "尚未评价"
            self.write(comment)
            return

        # request to log out
        elif 'logout' in self.request.arguments:
            self.clear_current_user()
            print 'class ShopMainHandler post() log out!'
            self.write(LOGOUT_SUCCEEDED)
            return

        self.write(ERROR_POST_REQUEST)
Exemplo n.º 17
0
def insert(table_name, values):
    res = RecordManager.insert(table_name, values)
    if res == True:
        print('Query OK, 1 rows affected ({:.2f} sec)'.format(
            time.process_time() - start_time))
Exemplo n.º 18
0
def delete(table_name, conditions):
    res = RecordManager.delete(table_name, conditions)
    print('Query OK, {} rows affected ({:.2f} sec)'.format(
        res,
        time.process_time() - start_time))
Exemplo n.º 19
0
    def get(self):
        customer_id = OAuthManager.get_openid_base(self)
        now_date = datetime.datetime.now().date()

        record_list = []
        # get record this month
        this_month = datetime.datetime.now().date().month
        start_date = now_date.replace(day=01)
        end_date = now_date.replace(month=this_month + 1,
                                    day=01) - datetime.timedelta(days=1)
        record_list_this_month = RecordManager.get_records_interval_customer(
            customer_id, str(start_date), str(end_date))
        for record in record_list_this_month:
            record.append(CommentManager.has_comment(record[0]))
        if len(record_list_this_month) > 0:
            record_list.append(record_list_this_month)

        # get record one month before
        one_month_before = this_month - 1
        if one_month_before == 0:
            one_month_before = 12
            star_date_one_month_before = now_date.replace(
                year=datetime.datetime.now().date().year - 1,
                month=one_month_before,
                day=01)
            end_date_one_month_before = now_date.replace(
                day=01) - datetime.timedelta(days=1)
        else:
            star_date_one_month_before = now_date.replace(
                month=one_month_before, day=01)
            end_date_one_month_before = now_date.replace(
                month=this_month, day=01) - datetime.timedelta(days=1)
        record_list_one_month_before = RecordManager.get_records_interval_customer(
            customer_id, str(star_date_one_month_before),
            str(end_date_one_month_before))
        for record in record_list_one_month_before:
            record.append(CommentManager.has_comment(record[0]))
        if len(record_list_one_month_before) > 0:
            record_list.append(record_list_one_month_before)

        # get record two month before
        two_month_before = this_month - 2
        if two_month_before <= 0:
            two_month_before = two_month_before + 12
            star_date_two_month_before = now_date.replace(
                year=datetime.datetime.now().date().year - 1,
                month=two_month_before,
                day=01)
            end_date_two_month_before = now_date.replace(
                year=datetime.datetime.now().date().year - 1,
                month=one_month_before,
                day=01) - datetime.timedelta(days=1)
        else:
            star_date_two_month_before = now_date.replace(
                month=two_month_before, day=01)
            end_date_two_month_before = now_date.replace(
                month=one_month_before, day=01) - datetime.timedelta(days=1)
        record_list_two_month_before = RecordManager.get_records_interval_customer(
            customer_id, str(star_date_two_month_before),
            str(end_date_two_month_before))
        for record in record_list_two_month_before:
            record.append(CommentManager.has_comment(record[0]))
        if len(record_list_two_month_before) > 0:
            record_list.append(record_list_two_month_before)

        # record_list = [record_list_this_month, record_list_one_month_before, record_list_two_month_before]

        self.render("../static/template/CustomerServiceRecord.html",
                    customer_id=customer_id,
                    record_list=record_list)