Exemple #1
0
 def sync_request(cls, req_obj, raise_error=True):
     resp = sync_cli.fetch(req_obj, raise_error=raise_error)
     if not http_code.is_success(resp.code):
         logging.error(">>> sync request returned with non-2xx code <<<")
         logging.error("request: ")
         logging.error(repr(req_obj.__dict__))
         logging.error("response: ")
         logging.error(repr(resp.__dict__))
         return  # java接口访问失败
     return resp
Exemple #2
0
def account_query(**kwargs):
    """
    根据账户查询
    :param account: 见account.req_query
    :return:
    """
    resp = normal_cli.fetch(account.req_query(**kwargs), raise_error=False)
    if not is_success(resp.code):
        return False
    return json.loads(resp.body)
Exemple #3
0
def tornado_account_query(**kwargs):
    """
    根据账户查询
    :param account: 见account.req_query
    :return:
    """
    resp = yield async_cli.fetch(account.req_query(**kwargs),
                                 raise_error=False)
    if not is_success(resp.code):
        raise gen.Return(False)
    raise gen.Return(json.loads(resp.body))
Exemple #4
0
    def patch(self, number):
        """
        @api {PATCH} /express/ps/single/{number}/assignee_qj 配送端 - 扫码取件
        @apiName ps_express_single_assignee_qj
        @apiGroup app_ps

        @apiParam (url param) {string} number 运单号

        @apiParam (body param) {object} operating_loc 操作地理信息
        @apiParam (body param) {float} operating_loc.lat 经度
        @apiParam (body param) {float} operating_loc.lng 纬度
        @apiParam (body param) {string} operating_loc.addr 地址信息


        @apiParamExample {json} 请求示例
        patch http://api.gomrwind.com:5000/express/ps/single/000001000333/assignee_qj
        {}
        @apiUse bad_response
        """
        try:
            data = Schema({
                Optional("operating_loc", default={}):
                schema_loc  # 操作当时的地理位置信息
            }).validate(self.get_body_args())
        except SchemaError as e:
            logging.error(e.message)
            self.resp_args_error()
            return
        operator = self.man_info
        operator["operating_loc"] = data["operating_loc"]

        # 1. 执行扫码取件
        resp_obj = yield self.async_fetch(
            express.redirect_perform_expr_event(number=number,
                                                operation=ExprState.EVENT_QJ,
                                                operator=operator))

        # 2. 数据组log: 扫码取件(人->人)
        if http_code.is_success(resp_obj.code):
            try:
                yield java_windlog.log_create(
                    type=21005,
                    creatorId=self.man_info["id"],
                    createTime=arrow.utcnow().isoformat(),
                    orderId=number)
            except Exception as e:
                logging.warn(e.message)

        # 3. 不管收件结果如何, 原样返回
        self.resp(content=resp_obj.content, status_code=resp_obj.code)
Exemple #5
0
 def cmd_send_message(self, command_id, content):
     """
     前端发来消息
     """
     if not self.status["authenticated"]:
         self.send(REQ_SEND_MESSAGE, command_id, "not permitted.")
         return
     try:
         content = Schema({
             "message": object
         }).validate(content)
     except SchemaError:
         self.send(REQ_SEND_MESSAGE, command_id, "bad content structure.")
         return
     if not self.status["client_id"]:
         self.send(REQ_SEND_MESSAGE, command_id, "No client_id figured.")
         return
     resp = yield self.rtm.send_message(
         from_peer=conf.SYSTEM_ANSWERER_CLIENT_ID,
         to_peers=[self.status["client_id"]],
         message=json.dumps(content["message"], ensure_ascii=False),
         conv_id=self.status["cli"],
     )
     if is_success(resp.code):
         self.send(REQ_SEND_MESSAGE, command_id, {
             "status": True
         })
         channel_utils.CP_unread_increase(
             self.status["cli"],
             f=self.status["answerer_info"]["client_id"],
             t=self.status["client_id"],
             last_message=message_utils.pack_message_summary(content["message"])
         )
         redisc.publish(conf.TREDIS_CHANNEL_CURRENT, {
             "cli": self.status["cli"],
             "message": content["message"],
             "from": self.status["answerer_info"]["client_id"]
         })
     else:
         self.send(REQ_SEND_MESSAGE, command_id, {
             "status": False
         })
Exemple #6
0
 def get(self):
     """
     判断点是否落入任何一个围栏(外加一些逻辑条件)
     """
     resp_obj = yield self.async_fetch(
         node.redirect_get_fence(**self.get_query_args()))
     if not http_code.is_success(resp_obj.code):
         logging.error(
             "fence query with error status code, message: {content}, code: {code}"
             .format(content=repr(resp_obj.content), code=resp_obj.code))
         self.resp(*resp_obj.parse_response())
         return
     if resp_obj.content == []:
         # 不在任何围栏内
         self.resp({"within": False, "message": "该地址不在配送范围内"})
         return
     for f in resp_obj.content:
         if f.get("mans", []):
             # 在任一个有人的围栏内即
             self.resp({"within": True, "has_man": True})
             return
     self.resp({"within": True, "has_man": False, "message": "该地址不在配送范围内"})
Exemple #7
0
    def patch(self):
        """
        抢呼叫
        :param :
        :return:
        """
        try:
            kw = Schema({
                'call_id': schema_unicode,
            }).validate(self.get_body_args())
        except SchemaError as e:
            logging.warn(e)
            self.resp_args_error(e.message)
            return
        operator = self.man_info

        # 1. 执行抢呼叫
        resp_obj = yield self.async_fetch(
            express.redirect_perform_call_event(
                call_id=kw['call_id'],
                operation=CallState.EVENT_ASSIGN_TO_ME,
                operator=operator,
                assignee=operator))

        # 2. 数据组log: 抢呼叫
        if http_code.is_success(resp_obj.code):
            try:
                call = resp_obj.content
                yield java_windlog.log_create(type=21002,
                                              creatorId=call["assignee"]["id"],
                                              createTime=call["create_time"],
                                              locationLat=call["loc"]["lat"],
                                              locationLng=call["loc"]["lng"],
                                              caseId=call["id"])
            except Exception as e:
                logging.warn(e.message)

        # 3. 不管收件结果如何, 原样返回
        self.resp(content=resp_obj.content, status_code=resp_obj.code)
Exemple #8
0
    def cmd_subscriber_message_history(self, command_id, content):
        """
        某个订阅者的聊天历史
        """
        if not self.status["authenticated"]:
            self.send(REQ_SUBSCRIBER_MESSAGE_HISTORY, command_id, "not permitted.")
            raise gen.Return()
        try:
            content = Schema({
                Optional("client_id", default=None): schema_utf8,
                Optional("limit", default=20): schema_int,
                Optional("msgid"): schema_utf8,
                Optional("max_ts"): schema_int
            }).validate(content)
        except SchemaError:
            self.send(REQ_SUBSCRIBER_MESSAGE_HISTORY, command_id, "bad content structure.")
            raise gen.Return()
        if not self.status["client_id"] and not content["client_id"]:
            self.send(REQ_SUBSCRIBER_MESSAGE_HISTORY, command_id, "Currently no client_id, please offer a client_id.")
            raise gen.Return()
        self.status["client_id"] = content.pop("client_id")
        resp = yield self.rtm.conversation_history_sys(self.status["cli"], self.status["client_id"], **content)
        if is_success(resp.code):
            channel_utils.CP_mark_read(
                self.status["cli"],
                f=self.status["client_id"],
                t=conf.CHANNEL_PRESENCE_ANY_CLIENT_ID
            )
            ret = yield answerer_utils.pack_leancloud_chat_history(json.loads(resp.body), self.status["cli"])
            self.send(
                REQ_SUBSCRIBER_MESSAGE_HISTORY,
                command_id,
                ret
            )

        else:
            self.send(REQ_SUBSCRIBER_MESSAGE_HISTORY, command_id, json.loads(resp.body))
Exemple #9
0
 def patch(self):
     """
     加单
     :param :
     :return:
     """
     try:
         kw = Schema({
             'call_id': schema_unicode,
             'name': schema_unicode_empty,
             'tel': schema_unicode,
             'address': schema_unicode_empty,
             'lat': schema_float,
             'lng': schema_float,
             Optional('category', default=DEFAULT_CATEGORY): schema_unicode,
             'remark': schema_unicode_empty
         }).validate(self.get_body_args())
     except SchemaError as e:
         logging.warn(e)
         self.resp_args_error(e.message)
         return
     # 0. 解包出call_id
     call_id = kw.pop('call_id')
     # 1. 解析送达地址, 获取对应的围栏
     fence_n = yield node.query_fence_point_within([kw['lng'], kw['lat']],
                                                   need_mans=True)
     # 1.1 没围栏, 拒绝加单
     if fence_n['id'] == 'x':
         msg = '找不到客户送达地址[%s][%s]%s 所在的送达围栏.' % (kw['name'], kw['address'],
                                                 (kw['lat'], kw['lng']))
         logging.info(msg)
         self.resp_error('加单失败,送达地址超出服务范围')
         return
     # 1.2 有围栏, 但是围栏下没有人
     elif not fence_n['mans']:
         logging.info('找到客户送达地址[%s][%s]%s 所在送达围栏[%s], 但围栏内没人.' %
                      (kw['name'], kw['address'],
                       (kw['lat'], kw['lng']), fence_n['name']))
         self.resp_error('抱歉!该地址所在区域无人可供上门收件')
         return
     # 1.3 有围栏, 执行加单
     else:
         # 注意把mans去掉
         fence_n.pop('mans', None)
         kw['fence'] = fence_n
         operator = self.man_info
         resp_obj = yield self.async_fetch(
             express.redirect_perform_call_event(
                 call_id=call_id,
                 operation=CallState.EVENT_ADD,
                 operator=operator,
                 **kw))
         # 2. 加单成功: 记数据组log
         if http_code.is_success(resp_obj.code):
             try:
                 call = resp_obj.content
                 yield java_windlog.log_create(
                     type=21003,
                     creatorId=self.man_info["id"],
                     createTime=arrow.utcnow().isoformat(),
                     locationLat=call["loc"]["lat"],
                     locationLng=call["loc"]["lng"],
                     shopId=call["shop_id"],
                     orderAddress=kw["address"],
                     orderLat=kw["lat"],
                     orderLng=kw["lng"],
                     caseId=call["id"])
             except Exception as e:
                 logging.warn(e.message)
         # 3. 不管加单结果如何, 原样返回
         self.resp(resp_obj.content, resp_obj.code)
         return
Exemple #10
0
    def post(self, fh_or_h5):
        """
            @api {post} /express/{fh|h5}/call 发货端 - 一键呼叫
            @apiName common_express_one_key_call
            @apiGroup common_express
            @apiVersion 0.0.1

            @apiParam (body param) {int} count 运单个数
            @apiParam (body param) {json} sender 寄方信息
            @apiParam (body param) {string} sender.tel 寄方手机号
            @apiParam (body param) {string} sender.name 寄方名称
            @apiParam (body param) {string} sender.addr 寄方地址
            @apiParam (body param) {float} sender.lat 寄方地址纬度
            @apiParam (body param) {float} sender.lng 寄方地址经度

            @apiSuccessExample 成功返回示例
            HTTP/1.1 200 OK
            {express}
            @apiUse default_express

            @apiUse bad_response
        """
        try:
            kw = Schema({
                Optional("sender",
                         default={
                             'addr': '未知地段',
                             'name': '收方名称',
                             'tel': '00000000000',
                             'lat': 0.0,
                             'lng': 0.0
                         }): {
                    "addr": schema_unicode,
                    "name": schema_unicode,
                    "tel": schema_unicode,
                    Optional('lat'): schema_float,
                    Optional('lng'): schema_float,
                },
                "count": schema_int
            }).validate(self.get_body_args())
        except SchemaError:
            self.resp_error("请将信息填写完整.")
            return

        sender = kw['sender']
        if 'lat' in sender and 'lng' in sender:
            lat_0 = sender['lat']
            lng_0 = sender['lng']
        else:
            # 解析发货人当前位置地址
            lng_0, lat_0 = yield baidumap_api.async_get_coordinates(
                "", "", sender["addr"])
        shop = {
            'id': self.shop_info['id'],
            'name': sender['name'],
            'tel': sender['tel'],
            'm_type': fh_or_h5,
            'lat': lat_0,
            'lng': lng_0,
            'address': sender['addr'],
        }
        # 1. 执行一键呼叫
        resp_obj = yield self.async_fetch(
            express.redirect_one_key_call(shop=shop, count=kw['count']))
        # 2. 数据组log: 一键呼叫
        if http_code.is_success(resp_obj.code):
            try:
                yield java_windlog.log_create(
                    type=21001,
                    shopId=shop["id"],
                    createTime=arrow.utcnow().isoformat(),
                    amount=kw["count"],
                    locationLat=shop["lat"],
                    locationLng=shop["lng"],
                    caseId=str(resp_obj.parse_response()[0]["id"]))
            except Exception as e:
                logging.warn(e.message)
        # 3. 不管收件结果如何, 原样返回
        self.resp(content=resp_obj.content, status_code=resp_obj.code)
Exemple #11
0
def log_create(isVal=None, type="",
               # 日志创建者
               creatorId="", creatorName="", creatorTel="", creatorRole="", createTime="",
               # 影响者
               effectorId="", effectorName="", effectorTel="", effectorRole="",
               # 运单信息
               orderId="", orderSum="", orderState=0, orderType="", orderAddress="", orderCreator="", orderLat=0.0,
               orderLng=0.0,
               # 客户信息
               shopAddress="", shopLat=0.0, shopLng=0.0, shopId="", shopName="", shopTel="",
               # 资金
               fondSum=0.0, fondType="",
               # 交通工具
               vehicleId="", vehicleMile="",
               # 软件版本
               softwareVersion="",
               # 地理信息
               locationAddress="", locationLat=0.0, locationLng=0.0,
               # 其他
               remark="", caseId="", caseType="", caseDetail="", amount=0,
               **kwargs):
    """新增参数请加到上面并归类, 未加入的参数会被忽略(warning提示)"""
    if kwargs:
        logging.warn("Got unprocessed params: " + repr(kwargs))
    url = JAVA_DATA_PREFIX + "/WindCloud/log/create"

    d = dict(
        isVal=isVal,  # 是否有效
        type=type,  # 日志类型

        # 日志创建者
        creatorId=creatorId,
        creatorName=creatorName,
        creatorTel=creatorTel,
        creatorRole=creatorRole,
        createTime=createTime,  # 日志创建时间

        # 影响者
        effectorId=effectorId,
        effectorName=effectorName,
        effectorTel=effectorTel,
        effectorRole=effectorRole,

        # 运单信息
        orderId=orderId,
        orderSum=orderSum,
        orderState=orderState,  # 运单状态
        orderType=orderType,
        orderAddress=orderAddress,
        orderCreator=orderCreator,
        orderLat=orderLat,
        orderLng=orderLng,

        # 客户信息
        shopAddress=shopAddress,
        shopLat=shopLat,
        shopLng=shopLng,
        shopId=shopId,
        shopName=shopName,
        shopTel=shopTel,

        # 资金
        fondSum=fondSum,  # 资金总数
        fondType=fondType,  # 资金类型

        # 交通工具
        vehicleId=vehicleId,  # 车辆牌号
        vehicleMile=vehicleMile,  # 里程数

        # 软件版本
        softwareVersion=softwareVersion,

        # 地理信息
        locationAddress=locationAddress,
        locationLat=locationLat,
        locationLng=locationLng,

        # 其他
        remark=remark,
        caseId=caseId,  # 事件 id
        caseType=caseType,  # 事件类型
        caseDetail=caseDetail,  # 事件详情
        amount=amount  # 数量
    )
    d = {i: d[i] for i in d if d[i]}
    logging.info("windlog.log_create: " + repr(d))
    resp = yield async_requests.post(url, json=d)
    if not resp:
        logging.warn("Got empty windlog resp")
    if not http_code.is_success(resp.code):
        logging.warn("Windlog failed with code %s" % resp.code)