Пример #1
0
    def __init__(self):
        # self.sockfd = sockfd
        # 界面的创建以及动作执行
        app = QtWidgets.QApplication(sys.argv)
        self.form = QtWidgets.QWidget()
        self.cur_dialog = QtWidgets.QDialog()
        self.reg_dialog = QtWidgets.QDialog()
        self.num_dialog = QtWidgets.QDialog()
        self.sel_dialog = QtWidgets.QDialog()
        self.usr_dialog = QtWidgets.QDialog()
        self.usr1_dialog = QtWidgets.QDialog()
        self.cur1_dialog = QtWidgets.QDialog()
        # 创建所有页面的对象
        self.mf = MainInterface()  # 主界面
        self.cur = Courier()  # 快递员登录界面
        self.reg = Registered()  # 快递员注册界面
        self.num = Number()  # 快递员输入用户信息界面
        self.sel = SelectSize()  # 快递员选择柜子大小界面
        self.usr = User()  # 用户输入验证码界面
        self.usr1 = UsrSelect()  # 用户选择寄件和取件界面
        self.cur1 = CurSelect()  # 快递员选择派件和取件界面

        self.mf.main_inter(self.form)
        self.form.show()
        self.cur.c_interface(self.cur_dialog)
        self.reg.register_interface(self.reg_dialog)
        self.usr.user_interface(self.usr_dialog)
        self.num.number_inteface(self.num_dialog)
        self.sel.select_interface(self.sel_dialog)
        self.usr1.us_interface(self.usr1_dialog)
        self.cur1.cs_interface(self.cur1_dialog)
        # 调用动作函数
        self.action()
        sys.exit(app.exec_())
Пример #2
0
    def run(self):
        '''This is the method that drives the entire program.'''
        # Ask the user what mode they want to run the bot in.
        self.currentMode = self.modeSelect()

        # Last output before loop
        print(f'Starting bot in: {self.currentMode}')

        # While loop.
        while (1):
            print('-------------')

            # Let the scraper scrape for new cases.
            self.scraper.scrape()

            # Check if there is a new case from that scrape.
            if self.validator.checkForNewCase():
                print('Sherlock has found a new case.')

                # Logic to decide who gets emails when there is a new case.
                if self.currentMode == Environment.TEST:
                    Courier.sendEmailsToAdminOnly(
                        'Covid Case sent to admin emails.')

                if self.currentMode == Environment.PROD:
                    # Courier.sendEmailsToEveryoneInMailingList('New covid-19 case confirmed on campus.')
                    pass

            self.cleanUp()
            print('-------------')

            # Sleep for as long as indicated in self.loopInterval.
            time.sleep(self.loopInterval)
Пример #3
0
    def get_couriers(self) -> dict:
        couriers = {}
        for courier in self.data['couriers']:
            new_courier = Courier()
            new_courier.courier_id = courier.get('courier_id')
            new_courier.location_x = courier.get('location_x')
            new_courier.location_y = courier.get('location_y')
            couriers[new_courier.courier_id] = new_courier

        return couriers
Пример #4
0
    def cleanLists(self):
        '''The goal of this function is to make all of the data uniform.'''
        # Check to make sure length is the same for both lists
        if len(self.cases) != len(self.dates):
            msg = f'ERROR. Cases list length: {len(self.cases)}. Dates list length: {len(self.dates)}'
            Courier.sendEmailsToAdminOnly(msg)
            sys.exit('Bot stopped due to length issues.')

        # Look for all \xa0 characters and remove them
        for i in range(0, len(self.cases) - 1):
            self.cases[i] = self.cases[i].replace(u'\xa0', ' ').strip()
            self.dates[i] = self.dates[i].replace(u'\xa0', ' ').strip()
Пример #5
0
 def __init__(self):
     '''Initializes bot class.'''
     self.scraper = Scraper()
     self.validator = Validator()
     self.courier = Courier()
     self.loopInterval = 300  # In seconds
     self.currentMode = Environment.TEST  # This is set in self.ModeSelect() method in the run method. I have it set to Environment.TEST default incase someone removes self.modeSelect().
Пример #6
0
 def delCourier(self):
     index = self.tableWidget.row(self.tableWidget.currentItem())
     if index == -1:
         return
     #Courier(index).removeCourier()
     Courier(index).removeCourier()
     self.fillTableCouriers()
Пример #7
0
def get_courier_by_id(connection, courier_id):
    with connection:
        element = connection.execute(GET_COURIER_BY_ID,
                                     courier_id).fetchall()[0]
        courier = Courier(element[0], element[1], json.loads(element[2]),
                          json.loads(element[3]), json.loads(element[4]))
        return courier
Пример #8
0
 def fillFields(self):
     k = 0
     self.items = []
     while (True):
         try:
             courier = Courier(k)
             print(type(courier.name))
             self.items.append(
                 str(courier.name) + " " + str(courier.surename))
             k = k + 1
         except KeyError:
             break
     self.Courier.addItems(self.items)
     dfn = pd.read_csv('data/products.csv', encoding='utf-8')
     del dfn['Unnamed: 0']
     self.items = []
     for i in range(len(dfn)):
         self.items.append(dfn.iloc[i, 0])
     self.Product.addItems(self.items)
     k = 0
     self.items = []
     self.itemsAddress = []
     while (True):
         try:
             client = Client(k)
             self.items.append(
                 str(client.name) + " " + str(client.phone_number))
             self.itemsAddress.append(
                 str(client.street) + " " + str(client.house))
             k = k + 1
         except KeyError:
             break
     self.Client.addItems(self.items)
     self.Address.addItems(self.itemsAddress)
Пример #9
0
async def update_couriers(request):
    json = await request.json()
    id = request.match_info.get('id')
    incorrect = False
    courier = Courier(id, None, None, None, 0)
    for key, val in json.items():
        if key == "courier_type" and type(val) is str and val in ('foot',
                                                                  'bike',
                                                                  'car'):
            courier.type = val
        elif key == "regions" and type(val) is list and all(
                type(x) is int and x > 0 for x in val):
            courier.regions = val
        elif key == "working_hours" and type(val) is list and all(
                type(x) is str for x in val) and len(val) <= 3:
            courier.working_hours = val
        else:
            incorrect = True
    if incorrect:
        return web.Response(status=400)
    courier = courier.update(request.app['db'])
    orders = courier.get_incompatible_orders(request.app['db'])
    for order in orders:
        order.remove_courier(request.app['db'])
    return web.json_response(status=200,
                             data={
                                 "courier_id": courier.id,
                                 "courier_type": courier.type,
                                 "regions": courier.regions,
                                 "working_hours": courier.working_hours
                             })
Пример #10
0
 async def test_deliver_order_success(self):
     ordinary_shelf = self.od.shelf_mapping['frozen']
     overflow_shelf = self.od.shelf_mapping['overflow']
     order, order_info = await self.setup_order_info([], ordinary_shelf,
                                                     overflow_shelf)
     courier = Courier(delay_time=2, order_info=order_info)
     msg = await courier.deliver_order([])
     print(msg)
     assert 'delivered: \x1b[32mTrue\x1b[0m' in msg
Пример #11
0
def get_couriers(connection):
    with connection:
        data = connection.execute(GET_COURIERS_TABLE).fetchall()
        couriers = []
        for element in data:
            courier = Courier(element[0], element[1], json.loads(element[2]),
                              json.loads(element[3]), json.loads(element[4]))

            couriers.append(courier)
        return couriers
Пример #12
0
 async def test_deliver_order_fail(self):
     ordinary_shelf = self.od.shelf_mapping['frozen']
     overflow_shelf = self.od.shelf_mapping['overflow']
     order, order_info = await self.setup_order_info([], ordinary_shelf,
                                                     overflow_shelf)
     order_info.is_on_shelf = False
     courier = Courier(delay_time=2, order_info=order_info)
     msg = await courier.deliver_order(wasted_orders=[])
     print(msg)
     assert 'not in shelf' in msg
Пример #13
0
class Testing(unittest.TestCase):
    def setUp(self):
        self.o = Order({u'id' : u'a8cfcb76-7f24-4420-a5ba-d46dd77bdffd' , u'prepTime' : 4 , u'name' : u'Banana Split'})
        cooking = MTList()
        cooking.put(self.o)
        self.c = Cook(MTList() , cooking)
        self.courier=Courier(self.o)


    def test_arrival_time(self):
        self.assertEqual(self.courier.get_order_details(self.o)[0],self.o.order_wait_time)
Пример #14
0
 def getHTMLFromURL(self, url):
     '''Makes a server request for the given url, ensures the response is ok, then returns a formatted html object.'''
     try:
         response = requests.get(
             url
         )  # Attempt to make a request to the server and wait for the response.
         if response.status_code != 200:  # If the response is not 200 (OK), wait and try again (recursively).
             print(
                 f'Could not connect to {url}. Retrying in {self._timeout_duration} seconds...'
             )
             time.sleep(self._timeout_duration)
             Courier.sendEmailsToAdminOnly(
                 'Could not connect to SPU website.'
             )  # TODO Take this out at some point.
             self.getHTMLFromURL(
                 url
             )  # TODO Make sure we don't overflow the call stack (TIMEOUT_DURATION must be reasonable)
         else:
             return html.fromstring(
                 response.content
             )  # Pull the content out of the response and format it as an HTML object
     except ConnectionError:
         Courier.sendEmailsToAdminOnly('Connection Error!')
Пример #15
0
    async def consumer(self):
        """
        consume order from queue, terminated the program if all orders in queue have been processed,
        :return:
        """
        try:
            while True:
                order_info = await self.order_queue.get()
                if not order_info:
                    continue

                if order_info == 'finished':
                    self.order_queue.task_done()
                    break

                print('\n########## consume order queue #############')
                courier_delay_time = random.randint(self.deliver_time_range[0],
                                                    self.deliver_time_range[1])
                print(
                    colored(
                        'consumer get {0} ,start dispatching to courier in: {1} seconds'
                        .format(order_info.order['id'],
                                courier_delay_time), 'green'))

                await asyncio.sleep(courier_delay_time)
                try:
                    courier = Courier(delay_time=courier_delay_time,
                                      order_info=order_info)
                    deliver_msg = await courier.deliver_order(
                        wasted_orders=self.wasted_orders)
                    print('\n&&&&&&&&&&&& deliver info &&&&&&&&&&&&')
                    print(deliver_msg)
                    self.delivered_orders.append(order_info)
                except Exception as e:
                    print(colored("Catch Exception {0}".format(e)), 'red')
                    raise
                finally:
                    self.order_queue.task_done()
        except asyncio.CancelledError:
            print("worker is being cancelled")
            raise
        finally:
            print(
                '\n########## all orders have been processed,system terminated #############'
            )
Пример #16
0
async def couriers(request):
    json = await request.json()
    objects = []
    incorrect_objects = []
    for k, v in json.items():
        if k == "data":
            for obj in v:
                courier = Courier(obj.get("courier_id"),
                                  obj.get("courier_type"), obj.get("regions"),
                                  obj.get("working_hours"), 0)
                incorrect = False
                for key, val in obj.items():
                    if key == "courier_id" and type(val) is int and val > 0:
                        courier.id = val
                    elif key == "courier_type" and type(
                            val) is str and val in ('foot', 'bike', 'car'):
                        courier.type = val
                    elif key == "regions" and type(val) is list and all(
                            type(x) is int and x > 0 for x in val):
                        courier.regions = val
                    elif key == "working_hours" and type(val) is list and all(
                            type(x) is str for x in val) and len(val) <= 3:
                        courier.working_hours = val
                    else:
                        incorrect = True
                if incorrect or courier.regions is None or courier.working_hours is None or courier.type is None:
                    incorrect_objects.append({"id": courier.id})
                else:
                    objects.append({"id": courier.id})
                    courier.save(request.app['db'])
        else:
            return web.Response(status=400)

    if len(incorrect_objects) > 0:
        return web.json_response(
            status=400,
            data={"validation_error": {
                "couriers": incorrect_objects
            }})
    else:
        return web.json_response(status=201, data={"couriers": objects})
Пример #17
0
def add_couriers():
    elements, errors, conn = [], [], db.connect()
    ids = db.get_couriers_id(conn)
    for element in request.json['data']:
        try:
            if element['courier_id'] in ids:
                raise (ValueError, 'Такой id уже существует в базе данных')
            c = Courier(element['courier_id'], element['courier_type'], element['regions'],
                        element['working_hours'])
            elements.append(c)
        except Exception:
            errors.append({'id': element['courier_id']})

    # если в процессе добавления возникли ошибки
    if errors:
        return jsonify({'validation_error': {'couriers': errors}}), 400

    db.insert_couriers(conn, elements)
    return jsonify({'couriers': [{'id': elem.courier_id} for elem in elements]}), 201
Пример #18
0
 def setUp(self):
     self.o = Order({u'id' : u'a8cfcb76-7f24-4420-a5ba-d46dd77bdffd' , u'prepTime' : 4 , u'name' : u'Banana Split'})
     cooking = MTList()
     cooking.put(self.o)
     self.c = Cook(MTList() , cooking)
     self.courier=Courier(self.o)
Пример #19
0
    def main_logic(self, action=None):
        if action:
            new_actions = self.new_action(action)

        work_duration = 0

        action_done = False
        for courier_id in self.couriers:
            if self.couriers[courier_id].order_info:
                courier_order = self.couriers[courier_id].order_info[0][0]
                courier_action = self.couriers[courier_id].order_info[0][1]
                print(courier_id, courier_order, courier_action,
                      self.couriers[courier_id].order_info)

                if courier_action == 'pickup':
                    distance = Courier.get_travel_duration_minutes([
                        self.couriers[courier_id].location_x,
                        self.couriers[courier_id].location_y
                    ], [
                        self.orders[courier_order].pickup_location_x,
                        self.orders[courier_order].pickup_location_y
                    ])
                    print('pick dist')
                    self.couriers[courier_id].destination_distance = distance
                    #print(courier_id,distance)
                elif courier_action == 'dropoff':
                    distance = Courier.get_travel_duration_minutes([
                        self.couriers[courier_id].location_x,
                        self.couriers[courier_id].location_y
                    ], [
                        self.orders[courier_order].dropoff_location_x,
                        self.orders[courier_order].dropoff_location_y
                    ])
                    self.couriers[courier_id].destination_distance = distance
        # итерируюсь по минутам рабочего времени курьеров
        for minute in range(self.time, self.END_MINUTES + 1):
            #self.time +=1
            #print(minute)
            if action_done:
                self.time = minute
                break
            for courier_id in self.couriers:
                if self.couriers[courier_id].destination_distance == 0:
                    action_done = True
                    continue
                if not self.couriers[courier_id].order_info:
                    continue
                courier_action = self.couriers[courier_id].order_info[0][1]
                courier_order = self.couriers[courier_id].order_info[0][0]

                self.couriers[courier_id].time += 1
                if self.couriers[courier_id].destination_distance is not None:
                    self.couriers[courier_id].destination_distance -= 1
                if courier_action == 'pickup':
                    work_duration = Courier.get_travel_duration_minutes([
                        self.couriers[courier_id].location_x,
                        self.couriers[courier_id].location_y
                    ], [
                        self.orders[courier_order].pickup_location_x,
                        self.orders[courier_order].pickup_location_y
                    ])
                    self.couriers[courier_id].location_x = self.orders[
                        self.couriers[courier_id].order_info[0]
                        [0]].pickup_location_x
                    self.couriers[courier_id].location_y = self.orders[
                        self.couriers[courier_id].order_info[0]
                        [0]].pickup_location_y
                    if self.orders[
                            courier_order].pickup_from < minute < self.orders[
                                courier_order].pickup_to:
                        action = self.couriers[courier_id].order_info.pop()
                        self.couriers[courier_id].has_order = True
                    work_payment = work_duration * 2
                    self.profit -= work_payment

                elif courier_action == 'dropoff':
                    work_duration = Courier.get_travel_duration_minutes([
                        self.couriers[courier_id].location_x,
                        self.couriers[courier_id].location_y
                    ], [
                        self.orders[courier_order].dropoff_location_x,
                        self.orders[courier_order].dropoff_location_y
                    ])
                    self.couriers[courier_id].location_x = self.orders[
                        self.couriers[courier_id].order_info[0]
                        [0]].dropoff_location_x
                    self.couriers[courier_id].location_y = self.orders[
                        self.couriers[courier_id].order_info[0]
                        [0]].dropoff_location_y
                    if self.orders[
                            courier_order].dropoff_from < minute < self.orders[
                                courier_order].dropoff_to:
                        self.orders_payment = self.orders[
                            courier_order].payment
                        self.orders[self.couriers[courier_id].order_info[0]
                                    [0]].delivered = True
                        action = self.couriers[courier_id].order_info.pop()
                        self.couriers[courier_id].has_order = False

                        if not self.couriers[courier_id].order_info:
                            self.couriers[courier_id].is_active = False
                    work_payment = work_duration * 2
                    self.profit += self.orders_payment - work_payment

        #work_duration = sum([x.time - 360 for x in self.couriers.values()])
        return self.couriers, self.orders, self.profit
Пример #20
0
class Action():
    def __init__(self):
        # self.sockfd = sockfd
        # 界面的创建以及动作执行
        app = QtWidgets.QApplication(sys.argv)
        self.form = QtWidgets.QWidget()
        self.cur_dialog = QtWidgets.QDialog()
        self.reg_dialog = QtWidgets.QDialog()
        self.num_dialog = QtWidgets.QDialog()
        self.sel_dialog = QtWidgets.QDialog()
        self.usr_dialog = QtWidgets.QDialog()
        self.usr1_dialog = QtWidgets.QDialog()
        self.cur1_dialog = QtWidgets.QDialog()
        # 创建所有页面的对象
        self.mf = MainInterface()  # 主界面
        self.cur = Courier()  # 快递员登录界面
        self.reg = Registered()  # 快递员注册界面
        self.num = Number()  # 快递员输入用户信息界面
        self.sel = SelectSize()  # 快递员选择柜子大小界面
        self.usr = User()  # 用户输入验证码界面
        self.usr1 = UsrSelect()  # 用户选择寄件和取件界面
        self.cur1 = CurSelect()  # 快递员选择派件和取件界面

        self.mf.main_inter(self.form)
        self.form.show()
        self.cur.c_interface(self.cur_dialog)
        self.reg.register_interface(self.reg_dialog)
        self.usr.user_interface(self.usr_dialog)
        self.num.number_inteface(self.num_dialog)
        self.sel.select_interface(self.sel_dialog)
        self.usr1.us_interface(self.usr1_dialog)
        self.cur1.cs_interface(self.cur1_dialog)
        # 调用动作函数
        self.action()
        sys.exit(app.exec_())

    def action(self):
        # 主界面操作
        self.mf.send_button.clicked.connect(
            lambda: self.create_sock(self.cur_dialog))  # 快递员寄快递
        self.mf.pickup_button.clicked.connect(
            lambda: self.create_sock(self.usr1_dialog))  # 用户取快递
        # 快递员登录界面操作
        self.cur.register_button.clicked.connect(
            self.cur_dialog.hide)  # 进入注册页面
        self.cur.register_button.clicked.connect(self.reg_dialog.show)
        self.cur.back_pushButton.clicked.connect(self.cur_back)  # 返回主页面
        self.cur.login_button.clicked.connect(self.login_action)  # 登录操作
        # 快递员注册界面操作
        self.reg.back_pushButton.clicked.connect(self.reg_back)  # 返回登录页面
        self.reg.register_button2.clicked.connect(self.register_action)  # 注册操作
        # 快递员选择操作 派件&取件
        self.cur1.back_button.clicked.connect(self.cur1_dialog.hide)  # 返回登录页面
        self.cur1.back_button.clicked.connect(self.cur_dialog.show)
        self.cur1.send_button.clicked.connect(self.cur1_dialog.hide)  # 选择派件操作
        self.cur1.send_button.clicked.connect(self.sel_dialog.show)
        # 快递员选择柜子规格
        self.sel.back_pushButton.clicked.connect(self.sel_dialog.hide)
        self.sel.back_pushButton.clicked.connect(self.cur1_dialog.show)
        self.sel.ok_button.clicked.connect(self.select_action)
        # 快递员输入用户信息操作
        self.num.ok_button.clicked.connect(
            self.input_num)  # 确认用户信息(用户电话号码和快递单号)
        self.num.back_pushButton.clicked.connect(
            self.num_dialog.close)  # 返回上一级界面(用户登录界面)
        self.num.back_pushButton.clicked.connect(self.sel_dialog.show)
        # 用户选择寄件 取件操作
        self.usr1.back_button.clicked.connect(self.usr1_dialog.hide)  # 返回主界面
        self.usr1.back_button.clicked.connect(self.close_sock)
        self.usr1.pickup_button.clicked.connect(
            self.usr1_dialog.hide)  # 选择取件操作
        self.usr1.pickup_button.clicked.connect(self.usr_dialog.show)
        # 用户输入验证码操作
        self.usr.back_pushButton.clicked.connect(
            self.usr_dialog.hide)  # 返回到用户选择界面
        self.usr.back_pushButton.clicked.connect(self.usr1_dialog.show)
        self.usr.ok_pushButton.clicked.connect(self.code_sure_action)  # 确认验证码

    # 当点击快递员和用户的时候创建套接字
    def create_sock(self, dialog):
        self.sockfd = socket()
        try:
            self.sockfd.connect(ADDR)
        except:
            QtWidgets.QMessageBox.warning(self.cur_dialog, '警告',
                                          '服务器未连接\n请稍后再试!',
                                          QtWidgets.QMessageBox.Yes)
            self.sockfd.close()
            return
        self.form.hide()
        dialog.show()

    # 当返回到主界面的时候关闭套接字
    def close_sock(self):
        self.sockfd.send(b"Q")
        self.sockfd.close()
        self.form.show()

    # 快递员注册页面返回登录页面清空所有内容
    def reg_back(self):
        self.reg_dialog.close()
        self.cur_dialog.show()
        self.reg.username_edit2.setText("")
        self.reg.password_edit2.setText("")
        self.reg.password2_edit2.setText("")

    # 快递员登录页面返回主页面清空所有内容
    def cur_back(self):
        self.cur_dialog.close()
        self.form.show()
        self.cur.username_edit.setText("")
        self.cur.password_edit.setText("")

    # 快递员登录操作,判断快递员输入的用户名和密码是否争取
    def login_action(self):
        username = self.cur.username_edit.text()
        password = self.cur.password_edit.text()
        # 验证用户
        if username == "" or password == "":
            QtWidgets.QMessageBox.warning(self.cur_dialog, '警告',
                                          '用户名或密码不能为空!\n请重新输入!',
                                          QtWidgets.QMessageBox.Yes)
        else:
            # 发送给服务端的消息
            msg = "L {} {}".format(username, password)
            self.sockfd.send(msg.encode())
            data = self.sockfd.recv(128).decode()
            # 若收到OK则表示登陆成功,否则给出提示
            if data == "OK":
                print("登陆成功")
                self.cur_dialog.hide()
                self.cur1_dialog.show()
            else:
                QtWidgets.QMessageBox.warning(self.cur_dialog, '警告',
                                              '用户名或密码错误\n请重新输入!',
                                              QtWidgets.QMessageBox.Yes)
        self.cur.username_edit.setText('')
        self.cur.password_edit.setText('')

    # 快递员注册操作,判断快递员输入的用户名和密码是否合法
    def register_action(self):
        username = self.reg.username_edit2.text()
        password = self.reg.password_edit2.text()
        password1 = self.reg.password2_edit2.text()
        print(username)
        print(password)
        print(password1)
        res = re.findall("\d{6,12}", password)

        # 将密码输入框清空
        def clear():
            self.reg.password_edit2.setText("")
            self.reg.password2_edit2.setText("")

        # 判断密码的合法性
        # 用户名和密码不能为空
        if username == '' or password == '':
            QtWidgets.QMessageBox.warning(self.reg_dialog, '警告',
                                          '用户名或密码不能为空\n请重新输入!',
                                          QtWidgets.QMessageBox.Yes)
        # 两次密码必须一致
        elif password != password1:
            QtWidgets.QMessageBox.warning(self.reg_dialog, '警告',
                                          '两次密码不一致\n请重新输入!',
                                          QtWidgets.QMessageBox.Yes)
        elif res == []:
            QtWidgets.QMessageBox.warning(self.reg_dialog, '警告',
                                          '密码由字母和数字组成,\n至少6位\n请重新输入!',
                                          QtWidgets.QMessageBox.Yes)
        else:
            # 若密码合法则发送给服务端
            msg = 'R {} {}'.format(username, password)
            self.sockfd.send(msg.encode())
            data = self.sockfd.recv(128).decode()
            # 接收到OK表示注册成功,否则注册失败
            if data == "OK":
                replay = QtWidgets.QMessageBox.information(
                    self.reg_dialog, '消息', '注册成功!', QtWidgets.QMessageBox.Yes)
                if replay == QtWidgets.QMessageBox.Yes:

                    self.reg_dialog.close()
                    self.cur_dialog.show()
            else:
                QtWidgets.QMessageBox.warning(self.reg_dialog, '警告',
                                              '用户名已存在\n请重新输入!',
                                              QtWidgets.QMessageBox.Yes)
        clear()

    # 快递员输入用户信息操作
    def input_num(self):
        phone_num = self.num.number_edit.text()
        express_num = self.num.number2_edit.text()
        print(phone_num)
        print(express_num)
        # 使用正则匹配电话号码和快递单号,判断其合法性
        res = re.findall("^1\d{10}$", phone_num)
        res1 = re.findall("^\d+$", express_num)
        # 判断输入的电话号和快递码的合法性
        if res == []:
            QtWidgets.QMessageBox.warning(self.num_dialog, '警告', '请输入正确的手机号!',
                                          QtWidgets.QMessageBox.Yes)
            self.num.number_edit.setText("")
            return
        elif res1 == []:
            QtWidgets.QMessageBox.warning(self.num_dialog, '警告', '请输入正确的快递单号!',
                                          QtWidgets.QMessageBox.Yes)
            self.num.number2_edit.setText("")
            return
        else:
            # 若输入合法,发送给服务端消息
            msg = "N {} {} {}".format(phone_num, express_num, ADDR_G)
            self.sockfd.send(msg.encode())
            data = self.sockfd.recv(128).decode()
            # 若收到OK表示成功,否则失败
            if data == "OK":
                replay = QtWidgets.QMessageBox.information(
                    self.num_dialog, '消息', '柜子已打开!\n请放入快递!\n然后关闭快递柜!',
                    QtWidgets.QMessageBox.Yes)
                if replay == QtWidgets.QMessageBox.Yes:
                    self.form.show()
                    self.num_dialog.hide()

            else:
                QtWidgets.QMessageBox.warning(self.num_dialog, '警告',
                                              '快递柜打开失败!\n请重新输入!',
                                              QtWidgets.QMessageBox.Yes)
        self.num.number_edit.setText("")
        self.num.number2_edit.setText("")

    # 用户输入验证码取件操作
    def code_sure_action(self):
        code = self.usr.code_lineEdit.text()
        print(code)
        # 发送给服务端消息
        msg = "C {}".format(code)
        self.sockfd.send(msg.encode())
        data = self.sockfd.recv(128).decode()
        # 若收到OK则表示验证码正确,柜子打开,否则不正确
        if data == "OK":
            replay = QtWidgets.QMessageBox.information(
                self.usr_dialog, '消息', '柜子已打开!\n请取出您的快递!\n然后关闭快递柜!',
                QtWidgets.QMessageBox.Yes)
            if replay == QtWidgets.QMessageBox.Yes:
                self.form.show()
                self.usr_dialog.hide()
        else:
            QtWidgets.QMessageBox.warning(self.usr_dialog, '警告',
                                          '验证码输入失败!\n请重新输入!',
                                          QtWidgets.QMessageBox.Yes)
        self.usr.code_lineEdit.setText("")

    # 用户选择柜子规格
    def select_action(self):
        def trans():
            self.sel_dialog.hide()
            self.num_dialog.show()

        # 选择小柜子
        if self.sel.small_button.isChecked():
            print("小柜子")
            msg = "G S"
            self.sockfd.send(msg.encode())
        # 选择大柜子
        elif self.sel.big_button.isChecked():
            print("大柜子")
            msg = "G B"
            self.sockfd.send(msg.encode())
        # 选择中柜子
        elif self.sel.middle_button.isChecked():
            print("中柜子")
            msg = "G M"
            self.sockfd.send(msg.encode())
        else:
            print("请选择柜子")
            return

        data = self.sockfd.recv(128).decode()
        # 收到OK表示此类型的柜子还有,否则表示没有了,给出提示
        if data == "OK":
            trans()
        else:
            QtWidgets.QMessageBox.warning(self.sel_dialog, '警告',
                                          '没有此类型的柜子\n请重新选择!',
                                          QtWidgets.QMessageBox.Yes)
Пример #21
0
 def addCourierButtonClicked(self):
     n = self.work.textName.toPlainText()
     s = self.work.textSurname.toPlainText()
     p = self.work.textPatr.toPlainText()
     c = self.work.carriageSize.toPlainText()
     Courier(self.i).changeCourier(n, s, p, c)