def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        master_id = self.get_argument('master_id', '')
        off_date = self.get_argument('off_date', '')  # 20160603

        master_date_key = '{0}_{1}'.format(master_id, off_date)

        off_date = dt.datetime.strptime(off_date, '%Y%m%d')

        ret = {}

        try:
            session = Session()
            masterdao = MasterDAO()

            # add request logs
            # type : 1 - request, 0 - cancel
            day_off_request = MasterDayoffRequest(
                master_id=master_id,
                date=off_date,
                type=0,
                request_time=dt.datetime.now())
            session.add(day_off_request)

            # master schedules by date active -> 0
            row = session.query(MasterScheduleByDate) \
                    .filter(MasterScheduleByDate.master_id == master_id) \
                    .filter(MasterScheduleByDate.date == off_date) \
                    .one()

            row.active = 1

            # commit
            session.commit()

            master_name = masterdao.get_master_name(master_id)
            send_jandi('HOMEMASTER_REST', "휴무 신청 취소",
                       master_name + ' 홈마스터님 휴무 신청 취소',
                       '휴무 취소 날짜 : {}'.format(off_date))

            ret['response'] = Response.SUCCESS
            self.set_status(Response.RESULT_OK)

            print 'master_id', master_id, 'cancel dayoff request', off_date

        except NoResultFound, e:
            self.set_status(Response.RESULT_OK)
            add_err_ko_message_to_response(ret, '휴무 신청 취소 가능 날짜가 아닙니다.')
            return
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        master_ids = self.get_argument('master_ids', '')
        ret = {}

        try:
            master_name_dict = {}

            masterdao = MasterDAO()
            master_ids = master_ids.split(',')
            for mid in master_ids:
                master_name = masterdao.get_master_name(mid)
                master_name_dict[mid] = master_name

            ret['response'] = master_name_dict

            self.set_status(Response.RESULT_OK)

        except Exception, e:
            print_err_detail(e)
            self.set_status(Response.RESULT_SERVERERROR)
            add_err_message_to_response(ret, err_dict['err_mysql'])
示例#3
0
    def get(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        date = self.get_argument('date', '')
        sigungu = self.get_argument('sigungu', '')
        customer_sigungu = self.get_argument('customer_sigungu', '')

        if date == None or date == '':
            date = dt.datetime.now()

        date = dt.datetime.strptime(date, '%Y%m%d')

        ret = {}

        try:
            session = Session()
            userdao = UserDAO()
            masterdao = MasterDAO()

            if sigungu == '':
                master_ids = masterdao.get_all_master_ids()
            else:
                master_ids = masterdao.get_master_ids_where_regions_available(
                    sigungu)

            master_times = []

            day_of_week = date.weekday()

            for mid in master_ids:
                master_schedules = []
                '''start_times, end_times = masterdao.get_master_working_time(mid)

              start_times = start_times.split(',')
              end_times = end_times.split(',')

              st = start_times[day_of_week] if start_times[day_of_week] != '' else 8
              et = end_times[day_of_week] if end_times[day_of_week] != '' else 8

              st = int(st)
              et = int(et)'''

                st, et = masterdao.get_master_working_time_for_day(
                    mid, date.date())
                current_cleaning_counts = masterdao.get_master_completed_cleaning_count_at_date(
                    mid, date)
                is_unassigned = masterdao.is_unassigned(mid)

                master_dict = {}
                master_dict['master_name'] = masterdao.get_master_name(mid)
                master_dict['master_id'] = mid
                master_dict['is_unassigned'] = is_unassigned
                master_dict[
                    'is_beginner'] = True if current_cleaning_counts <= 10 else False
                master_dict[
                    'current_cleaning_counts'] = current_cleaning_counts
                master_dict[
                    'master_available_from'] = '0%s:00' % st if st < 10 else '%s:00' % st
                master_dict[
                    'master_available_to'] = '0%s:00' % et if et < 10 else '%s:00' % et

                # for day off
                master_dict['is_day_off'] = masterdao.is_day_off(
                    mid, date.date())

                for row in session.query(Master, Booking, User, UserAddress, UserDefaultCard, Promotion, EventPromotionBooking) \
                                  .outerjoin(Booking, Master.id == Booking.master_id) \
                                  .join(User, User.id == Booking.user_id) \
                                  .join(UserAddress, and_(Booking.user_id == UserAddress.user_id, Booking.addr_idx == UserAddress.user_addr_index)) \
                                  .outerjoin(UserDefaultCard, User.id == UserDefaultCard.user_id) \
                                  .outerjoin(Promotion, Booking.id == Promotion.booking_id) \
                                  .outerjoin(EventPromotionBooking, Booking.id == EventPromotionBooking.booking_id) \
                                  .filter(func.DATE(Booking.start_time) == date) \
                                  .filter(Master.id == mid) \
                                  .filter(or_(Booking.cleaning_status == BC.BOOKING_UPCOMMING, Booking.cleaning_status == BC.BOOKING_STARTED, Booking.cleaning_status == BC.BOOKING_COMPLETED)) \
                                  .order_by(Master.name, Booking.start_time) \
                                  .all():

                    key = userdao.get_user_salt_by_id(row.User.id)[:16]
                    crypto = aes.MyCrypto(key)

                    discount_price = 0
                    if row.Promotion != None:
                        discount_price += row.Promotion.discount_price
                    if row.EventPromotionBooking != None:
                        discount_price += row.EventPromotionBooking.discount_price

                    kind = row.UserAddress.kind
                    if kind == 0:
                        kind = '오피스텔'
                    elif kind == 1:
                        kind = '주택'
                    else:
                        kind = '아파트'

                    address = crypto.decodeAES(row.UserAddress.address)
                    if customer_sigungu in address:
                        master_schedules.append(
                            self.make_schedule_dict(
                                row.Booking.id, row.User.devicetype,
                                row.Booking.appointment_type,
                                row.Booking.appointment_index,
                                dt.datetime.strftime(row.Booking.start_time,
                                                     '%H:%M'),
                                dt.datetime.strftime(
                                    row.Booking.estimated_end_time, '%H:%M'),
                                row.Booking.havereview, row.Booking.user_id,
                                crypto.decodeAES(row.User.name),
                                crypto.decodeAES(row.User.phone),
                                crypto.decodeAES(row.UserAddress.address),
                                row.UserAddress.size, kind,
                                row.Booking.is_dirty, row.Booking.status,
                                row.Booking.cleaning_status,
                                row.Booking.payment_status,
                                row.Booking.price_with_task, discount_price,
                                row.Booking.routing_method, row.User.is_b2b,
                                row.UserDefaultCard))

                master_dict['time_list'] = master_schedules
                master_times.append(master_dict)

            ret['response'] = master_times
            self.set_status(Response.RESULT_OK)

        except Exception, e:
            session.rollback()

            print_err_detail(e)
            self.set_status(Response.RESULT_SERVERERROR)
            add_err_message_to_response(ret, err_dict['err_mysql'])
示例#4
0
    def get(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        booking_id = self.get_argument('booking_id', '')

        ret = {}

        try:
            # retrieve update logs from mongo
            '''{ "_id" : ObjectId("574436f28a34832173d79a74"),
            "timestamp" : Timestamp(1464088306, 392),
            "module" : "update_schedule_handler",
            "fileName" : "/home/dev/webapps/src/rest/booking/update_schedule_handler.py",
            "apply_to_all_behind" : 0,
             "lineNumber" : 181,
             "message" : "update logs",
             "user_id" : "cef0e0ef-b6b9-44c1-bd99-f59a844e51e1",
             "org_time" : "2016년 06월 17일 금요일 오전 11시",
             "thread" : NumberLong("140546989348672"),
             "level" : "DEBUG",
             "threadName" : "MainThread",
             "loggerName" : "hm_logger",
             "org_master_id" : "bd1bae4b-3b1b-41e1-8c23-703226457a19",
             "booking_id" : "GdB6wdQJ37m8LgkD",
             "changed_master_id" : "d0060b43-d1e4-4b48-aa53-b6817913275d",
             "changed_time" : "2016년 06월 19일 일요일 오전 11시",
             "method" : "post" }'''
            masterdao = MasterDAO()

            update_records = []
            cursor = self.db.find({
                'message': 'update logs',
                'booking_id': booking_id
            }).sort('timestamp', 1)

            for item in cursor:
                org_master_id = item['org_master_id']
                changed_master_id = item['changed_master_id']

                org_master_name = masterdao.get_master_name(org_master_id)
                changed_master_name = masterdao.get_master_name(
                    changed_master_id)

                locale_time = item['timestamp'].as_datetime() + dt.timedelta(
                    hours=9)

                logging_time = convert_datetime_format2(locale_time)

                by_whom = '없음'
                if 'by_manager' in item:
                    if item['by_manager'] == 1:
                        by_whom = '매니저'
                    else:
                        by_whom = '고객'

                org_time = item['org_time'] if 'org_time' in item else ''
                changed_time = item[
                    'changed_time'] if 'changed_time' in item else ''

                update_records.append({
                    'org_time': org_time,
                    'changed_time': changed_time,
                    'org_master_name': org_master_name,
                    'changed_master_name': changed_master_name,
                    'logging_time': logging_time,
                    'by_whom': by_whom
                })

            ret['response'] = {'update_records': update_records}
            self.set_status(Response.RESULT_OK)

        except Exception, e:
            print_err_detail(e)
            self.set_status(Response.RESULT_SERVERERROR)
            add_err_message_to_response(ret, err_dict['err_mysql'])
    def post(self):
        self.set_header("Content-Type", "application/json")

        master_id = self.get_argument('master_id', '')
        date = self.get_argument('date', '')

        ret = {}

        date = dt.datetime.strptime(date, '%Y%m%d')

        try:
            session = Session()
            userdao = UserDAO()
            masterdao = MasterDAO()

            content = ''
            result = session.query(Booking, Master, User, UserAddress) \
                            .join(Master, Booking.master_id == Master.id) \
                            .join(User, Booking.user_id == User.id) \
                            .join(UserAddress, and_(Booking.user_id == UserAddress.user_id, Booking.addr_idx == UserAddress.user_addr_index)) \
                            .filter(Booking.master_id == master_id) \
                            .filter(func.date(Booking.start_time) == date) \
                            .filter(or_(Booking.cleaning_status == BC.BOOKING_UPCOMMING, Booking.cleaning_status == BC.BOOKING_COMPLETED)) \
                            .order_by(Booking.start_time) \
                            .all()

            word_idx = 1

            master_name = masterdao.get_master_name(master_id)
            master_phone = masterdao.get_master_phone(master_id)

            for row in result:
                key = userdao.get_user_salt_by_id(row.User.id)[:16]
                crypto = aes.MyCrypto(key)
                master_phone = str(row.Master.phone)
                master_name = str(row.Master.name)
                user_name = str(crypto.decodeAES(row.User.name))
                appointment_index = str(row.Booking.appointment_index)
                enterbuilding = str(
                    crypto.decodeAES(row.Booking.enterbuilding)
                ) if row.Booking.enterbuilding != None else str('')
                enterhome = str(crypto.decodeAES(row.Booking.enterhome)
                                ) if row.Booking.enterhome != None else str('')
                date_str = str(convert_datetime_format2(
                    row.Booking.start_time))
                address = str(crypto.decodeAES(row.UserAddress.address))
                appointment_type    = str(4 / row.Booking.appointment_type) + '주' \
                                      if row.Booking.appointment_type != BC.ONE_TIME \
                                      and row.Booking.appointment_type != BC.ONE_TIME_BUT_CONSIDERING \
                                      else '1회'
                additional_task = additional_task_string(
                    row.Booking.additional_task)
                take_time = timedelta_to_time(row.Booking.estimated_end_time -
                                              row.Booking.start_time)
                take_time_str = '%d시간 %d분' % (take_time.hour, take_time.minute)
                message = str(row.Booking.message)
                trash_location = str(row.Booking.trash_location)

                text = CONFIRM_UPDATE_BODY % (
                    user_name, appointment_index, date_str, address,
                    appointment_type, additional_task, take_time_str,
                    enterbuilding, enterhome, message, trash_location)

                content += str(word_idx) + '. ' + str(text) + '\n\n'
                word_idx += 1

            booking_date = dt.datetime.strftime(date, '%m월%d일')
            title = '%s 홈마스터님, %s 일정입니다.' % (master_name, booking_date)

            if word_idx == 1:
                content = '홈마스터님 내일 일정은 없습니다.'
                title = '홈마스터님 내일 일정은 없습니다.'

            ret['response'] = {
                'content': content,
                'phone': master_phone,
                'subject': title
            }
            self.set_status(Response.RESULT_OK)

        except Exception, e:
            session.rollback()

            print_err_detail(e)
            self.set_status(Response.RESULT_SERVERERROR)
            add_err_message_to_response(ret, err_dict['err_mysql'])
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        booking_id = self.get_argument('booking_id', '')
        reason_id = self.get_argument('reason_id', CANCEL_ADMIN)
        etc_reason = self.get_argument('etc_reason', '')
        charge_amount = self.get_argument('charge_amount', 0)
        no_fee = self.get_argument('no_fee', 0)

        regular_cancel_charge = self.get_argument('regular_cancel_charge', 0)

        charge_amount = int(charge_amount)
        reason_id = int(reason_id)
        no_fee = int(no_fee)

        regular_cancel_charge = int(regular_cancel_charge)

        print 'cancel all charge amount : ', charge_amount
        print 'reason_id : ', reason_id
        print 'etc_reason : ', etc_reason

        ret = {}

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        try:
            session = Session()
            userdao = UserDAO()
            masterdao = MasterDAO()

            stmt = session.query(Booking.request_id).filter(
                Booking.id == booking_id).subquery()
            first_startime = session.query(Booking.start_time).filter(
                Booking.request_id == stmt).order_by(
                    Booking.start_time).first()[0]

            result = session.query(Booking, Master, User, UserAddress) \
                         .join(Master, Booking.master_id == Master.id) \
                         .join(User, Booking.user_id == User.id) \
                         .join(UserDefaultAddress, User.id == UserDefaultAddress.user_id) \
                         .join(UserAddress, and_(UserAddress.user_id == UserDefaultAddress.user_id, UserAddress.user_addr_index == UserDefaultAddress.address_idx)) \
                         .filter(Booking.request_id == stmt) \
                         .filter(or_(Booking.cleaning_status == BC.BOOKING_UPCOMMING, Booking.cleaning_status == BC.BOOKING_STARTED, Booking.cleaning_status == BC.BOOKING_COMPLETED)) \
                         .all()

            # 서비스를 처음 이용한지 2달이 넘었는지 아닌지 조사,
            # 넘지 않았다면 이미 부과된 금액에 대해서도 1회 서비스 금액 과의 차액만큼 부과됨
            current_time = dt.datetime.now()

            completed_charge = 1
            if current_time >= first_startime + dt.timedelta(days=57):
                completed_charge = 0

            cancel_all_charge = 0
            # 그동안의 모든 예약에 대해서 처리함
            for row in result:
                charge = 0

                new_status = BC.BOOKING_CANCELED_CHARGE

                key = userdao.get_user_salt_by_id(row.User.id)[:16]
                crypto = aes.MyCrypto(key)

                username = str(crypto.decodeAES(row.User.name))

                request_id = row.Booking.request_id
                appointment_index = row.Booking.appointment_index

                bid = row.Booking.id
                user_id = row.Booking.user_id
                appointment_time = row.Booking.start_time
                current_status = row.Booking.status
                current_cleaning_status = row.Booking.cleaning_status
                current_payment_status = row.Booking.payment_status
                price = row.Booking.price_with_task
                source = row.Booking.source
                appointment_type = row.Booking.appointment_type

                diff_in_hours = (appointment_time -
                                 current_time).total_seconds() / 3600

                if diff_in_hours >= 24:
                    charge = price * BC.BOOKING_CHARGE_RATE_NO
                elif 4 <= diff_in_hours < 24:
                    charge = price * BC.BOOKING_CHARGE_RATE_30
                else:
                    charge = price * BC.BOOKING_CHARGE_RATE_50

                # 이미 지불한 금액에 대해 1회 비용의 차액만큼 계산
                if completed_charge == 1:
                    if current_cleaning_status == BC.BOOKING_COMPLETED:
                        # 차액만큼 계속 더함
                        _, house_size, house_type = userdao.get_user_address_detail_by_index(
                            user_id, row.Booking.addr_idx)
                        time_prices = get_basic_time_price(
                            house_type, house_size)
                        try:
                            print time_prices[0]['price']
                            print time_prices[appointment_type]['price']
                            charge_amount = int(
                                time_prices[0]['price'] -
                                time_prices[appointment_type]['price'])
                        except Exception:
                            charge_amount = 3000
                        cancel_all_charge += charge_amount

                # event
                is_event = session.query(UserFreeEvent) \
                                .filter(UserFreeEvent.booking_request_id == request_id) \
                                .first()

                is_event = True if is_event != None else False

                if is_event == True and appointment_index == 1:
                    partial = '0'
                    cancel_amount = row.Booking.price_with_task - row.Booking.price
                    cancel_payment(user_id, bid, cancel_amount, partial)

                    # 취소에 대한 결제 필요
                    # 8회 이상 썼다면(완료카운트 9회 미만일 경우 결제)
                    complete_count = session.query(Booking) \
                            .filter(Booking.request_id == request_id) \
                            .filter(Booking.cleaning_status == 2) \
                            .count()

                    if complete_count < 9 and row.Booking.cleaning_status == 2:
                        ret_code, msg = request_payment(
                            user_id, username, booking_id, price,
                            appointment_type)
                        if ret_code == False:
                            row.Booking.payment_status = BC.BOOKING_PAYMENT_FAILED

                if current_payment_status == BC.BOOKING_PAID and current_cleaning_status == BC.BOOKING_UPCOMMING:
                    if no_fee == 1:
                        charge = 0

                    new_status = BC.BOOKING_CANCELED_REFUND

                    partial = '1'
                    if charge == 0:
                        partial = '0'

                    cancel_amount = int(price - charge)
                    if cancel_amount > 0 and source == 'hm' and userdao.get_user_default_card_index(
                            user_id) != -1:
                        if not (is_event and appointment_index == 1):
                            ret_code, msg = cancel_payment(
                                user_id, bid, cancel_amount, partial)
                            if ret_code == False:
                                session.close()
                                self.set_status(Response.RESULT_OK)
                                add_err_ko_message_to_response(ret, msg)
                                #self.write(json.dumps(ret))
                                return

                elif current_payment_status == BC.BOOKING_UNPAID_YET and current_cleaning_status == BC.BOOKING_UPCOMMING:
                    print 'cancel charge'
                    charging_price = int(charge)
                    if charging_price > 0 and source == 'hm' and userdao.get_user_default_card_index(
                            user_id) != -1 and no_fee == 0:
                        print user_id, username, booking_id, charging_price, appointment_type
                        ret_code, msg = request_payment(
                            user_id, username, bid, charging_price,
                            appointment_type)
                        if ret_code == False:
                            new_status = BC.BOOKING_PAYMENT_FAILED

                #row.Booking.modified_date   = current_time
                if current_cleaning_status == BC.BOOKING_UPCOMMING:
                    row.Booking.charging_price = int(charge)
                    row.Booking.status = new_status
                    row.Booking.cleaning_status = BC.BOOKING_CANCELED
                    row.Booking.payment_status = new_status

                # add cancel reason
                CANCEL_ALL = 1
                reason = session.query(CancelReason).filter(
                    CancelReason.booking_id == bid)
                if reason.count() == 0:
                    cancel_reason = CancelReason(booking_id=bid,
                                                 user_id=user_id,
                                                 reason_id=reason_id,
                                                 etc_reason=etc_reason,
                                                 kind=CANCEL_ALL,
                                                 cancel_time=dt.datetime.now())
                    session.add(cancel_reason)
                else:
                    try:
                        reason_row = reason.one()
                        reason_row.kind = 1
                    except Exception, e:
                        print e

            # 수수료 임시 처리 막기
            #cancel_all_charge = 0
            if cancel_all_charge > 0 and source == 'hm' and regular_cancel_charge == 0:
                user_name = userdao.get_user_name(user_id)
                ret_code, msg = request_charge(user_id, user_name,
                                               cancel_all_charge)
                if ret_code == False:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    add_err_ko_message_to_response(ret, msg)
                    self.write(json.dumps(ret))
                    return

            if row != None:
                key = userdao.get_user_salt_by_id(row.User.id)[:16]
                crypto = aes.MyCrypto(key)

                # push to homemaster via sms
                master_id = row.Master.id
                master_phone = str(row.Master.phone)
                master_name = str(row.Master.name)
                username = str(crypto.decodeAES(row.User.name))
                userphone = str(crypto.decodeAES(row.User.phone))
                date = str(convert_datetime_format(row.Booking.start_time))
                addr = str(crypto.decodeAES(row.UserAddress.address))
                appointment_type = str(row.Booking.appointment_type)

                print 'app _type'
                print appointment_type

                appointment_type_text = ''
                if appointment_type == BC.ONE_TIME or appointment_type == BC.ONE_TIME_BUT_CONSIDERING:
                    appointment_type_text = '1회'
                elif appointment_type == BC.FOUR_TIME_A_MONTH:
                    appointment_type_text = '매주'
                elif appointment_type == BC.TWO_TIME_A_MONTH:
                    appointment_type_text = '2주 1회'
                elif appointment_type == BC.ONE_TIME_A_MONTH:
                    appointment_type_text = '4주 1회'

                #sms_sender = SMS_Sender()
                #text = BOOKING_CANCEL_ALL_TEXT % (appointment_type, username, userphone, master_name, date)
                #send_result = sms_sender.send_for_manager(sender = MAIN_CALL, mtype = 'sms', to = MANAGERS_CALL, subject = BOOKING_TEXT_SUBJECT, text = text)

                #for manager_phone in MANAGERS_CALL.split(','):
                #    send_alimtalk(manager_phone, 'noti_manager_cancel_all', username, date, appointment_type_text)

                cancel_all_reasons = []
                cancel_all_reasons.append('너무 비싸요')
                cancel_all_reasons.append('제가 여행을 가요')
                cancel_all_reasons.append('청소품질이 마음에 들지 않아요')
                cancel_all_reasons.append('필요할 때에만 서비스를 이용하고 싶어요')
                cancel_all_reasons.append('다른 업체로 바꿀래요')
                cancel_all_reasons.append('원하던 홈마스터가 오질 않아요')
                cancel_all_reasons.append('저 이사가요')
                cancel_all_reasons.append('기타')
                cancel_all_reasons.append('관리자가 취소 했습니다')

                cancel_reason = cancel_all_reasons[reason_id]
                if cancel_reason == '기타':
                    cancel_reason += ' ' + etc_reason
                elif reason_id == CANCEL_ADMIN:
                    cancel_reason += ', 관리자 메모 : ' + etc_reason

                send_jandi(
                    'NEW_BOOKING', "전체 취소 알림", username + ' 고객님 전체 취소함',
                    '{}, {} 사유 : {}'.format(date, appointment_type_text,
                                            cancel_reason))

                print 'jandi notification for cancel all...'

                master_pushkey = masterdao.get_master_pushkey(master_id)
                send_all_bookings_canceled('android', [master_pushkey],
                                           booking_id, date, username)

                master_phone = masterdao.get_master_phone(master_id)
                master_name = masterdao.get_master_name(master_id)

                user_name = userdao.get_user_name(user_id)

                content = '''{} 홈마스터님
정기 고객의 예약이 전체 취소 되었습니다.

고객 : {}
주기 : {}'''.format(master_name, user_name, appointment_type_text)

                print 'text'
                print appointment_type_text
                message_sender = MessageSender()
                message_sender.send([master_phone], '예약 전체 취소 알림', content)

                #send_alimtalk(master_phone, 'noti_manager_cancel_all', username, date, appointment_type_text)

            coupondao = CouponDAO()
            coupondao.cancelall_coupon_usage(booking_id)

            session.commit()

            mix.track(
                user_id, 'cancel all', {
                    'time': dt.datetime.now(),
                    'reason_id': reason_id,
                    'etc_reason': etc_reason
                })
            mongo_logger.debug('%s was all canceled' % booking_id,
                               extra={
                                   'user_id': user_id,
                                   'booking_id': booking_id
                               })

            ret['response'] = Response.SUCCESS
            self.set_status(Response.RESULT_OK)
    def get(self):
        self.set_header("Content-Type", "application/json")

        master_id = self.get_argument('master_id', '')
        only_5 = self.get_argument('only_5', 1)
        only_5 = int(only_5)

        ret = {}

        try:
            session = Session()

            ratings = []

            userdao = UserDAO()
            masterdao = MasterDAO()

            result = session.query(Rating, Booking, User, Master) \
                            .join(Booking, Rating.booking_id == Booking.id) \
                            .join(Master, Rating.master_id == Master.id) \
                            .join(User, Booking.user_id == User.id) \
                            .filter(Master.id == master_id)

            if only_5 == 1:
                result = result.filter(and_(Rating.rate_clean == 5.0, Rating.rate_master == 5.0)) \

            result = result.order_by(desc(Booking.start_time)).all()

            for row in result:
                key = userdao.get_user_salt(row.User.email)[:16]
                crypto = aes.MyCrypto(key)

                rating = {}

                rating['user_name'] = crypto.decodeAES(row.User.name)
                rating['start_date'] = dt.datetime.strftime(
                    row.Booking.start_time, '%Y-%m-%d')
                rating['rating_date'] = dt.datetime.strftime(
                    row.Rating.review_time, '%Y-%m-%d %H:%M')
                rating['start_time'] = convert_time_format(
                    row.Booking.start_time.time())
                rating['booking_id'] = row.Booking.id
                rating['clean_rating'] = float(row.Rating.rate_clean)
                rating['clean_review'] = row.Rating.review_clean
                rating['master_rating'] = float(row.Rating.rate_master)
                rating['master_review'] = row.Rating.review_master

                ratings.append(rating)

            cleaning_avg_rating, master_avg_rating = masterdao.get_master_rating(
                master_id)
            master_name = masterdao.get_master_name(master_id)

            ret['response'] = {
                'cleaning_avg_rating': cleaning_avg_rating,
                'master_avg_rating': master_avg_rating,
                'ratings': ratings,
                'master_id': master_id,
                'master_name': master_name
            }

            self.set_status(Response.RESULT_OK)

        except Exception, e:
            session.rollback()

            print_err_detail(e)
            self.set_status(Response.RESULT_SERVERERROR)
            add_err_message_to_response(ret, err_dict['err_mysql'])
示例#8
0
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        booking_id = self.get_argument('booking_id', '')
        reason = self.get_argument('reason', '')
        print booking_id, reason

        ret = {}

        try:
            session = Session()

            userdao = UserDAO()
            masterdao = MasterDAO()
            addressdao = AddressDAO()

            now = dt.datetime.now().date() + dt.timedelta(days=2)

            row = session.query(Booking) \
                        .filter(Booking.id == booking_id) \
                        .filter(Booking.cleaning_status == 0) \
                        .filter(func.date(Booking.start_time) >= now) \
                        .one()

            master_id = row.master_id
            start_time = row.start_time

            request = MasterBookingModifyRequest(
                master_id=master_id,
                booking_id=booking_id,
                reason=reason,
                org_time=start_time,
                request_time=dt.datetime.now())
            session.add(request)
            session.commit()

            row = session.query(Booking, UserAddress) \
                    .join(UserAddress, and_(Booking.user_id == UserAddress.user_id, Booking.addr_idx == UserAddress.user_addr_index)) \
                    .filter(Booking.id == booking_id) \
                    .one()

            master_name = masterdao.get_master_name(row.Booking.master_id)
            user_name = userdao.get_user_name(row.Booking.user_id)
            district = addressdao.get_gu_name(
                userdao.get_user_address(row.Booking.user_id)[0])
            appointment_time = convert_datetime_format2(row.Booking.start_time)

            for manager_phone in MANAGERS_CALL.split(','):
                send_alimtalk(manager_phone, 'noti_manager_modify_schedule',
                              master_name, user_name, district,
                              appointment_time)

            send_jandi(
                'HOMEMASTER_REST', "휴무 신청", master_name + ' 홈마스터님 일정변경 신청',
                '고객 : {}\n지역 : {}\n일정 : {}'.format(user_name, district,
                                                   appointment_time))

            ret['response'] = Response.SUCCESS
            self.set_status(Response.RESULT_OK)

            print 'booking_id', booking_id, 'was requested to modify'

        except NoResultFound, e:
            session.close()
            self.set_status(Response.RESULT_OK)
            add_err_ko_message_to_response(
                ret, '해당일은 일정 변경이 불가능 합니다. 일정 변경은 최소 이틀전에 가능합니다.')
            return
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        master_id = self.get_argument('master_id', '')
        off_date = self.get_argument('off_date', '')  # 20160603
        debug = self.get_argument('debug', 0)  # debug = 1: true 0: false

        master_date_key = '{0}_{1}'.format(master_id, off_date)

        off_date = dt.datetime.strptime(off_date, '%Y%m%d')

        ret = {}
        mongo_logger = get_mongo_logger()

        try:
            print "day off request ------------------------------------------- start"
            holder = IntermediateValueHolder()
            session = Session()
            masterdao = MasterDAO()

            # check redis that the master is not held
            is_held = holder.exists(master_date_key)
            print is_held
            if is_held:
                self.set_status(Response.RESULT_OK)
                mongo_logger.debug('doing booking',
                                   extra={
                                       'master_id': master_id,
                                       'off_date': off_date
                                   })
                add_err_ko_message_to_response(
                    ret, '현재 예약이 진행 중 이라 휴무 신청이 불가능 합니다.')
                return

            # add request logs
            # type : 1 - request, 0 - cancel
            day_off_request = MasterDayoffRequest(
                master_id=master_id,
                date=off_date,
                type=1,
                request_time=dt.datetime.now())
            session.add(day_off_request)

            # master schedules by date active -> 0
            row = session.query(MasterScheduleByDate) \
                    .filter(MasterScheduleByDate.master_id == master_id) \
                    .filter(MasterScheduleByDate.date == off_date) \
                    .one()

            row.active = 0

            mongo_logger.debug('set row.active = 0',
                               extra={
                                   'master_id': master_id,
                                   'off_date': off_date
                               })

            # commit
            session.commit()

            mongo_logger.debug('session.commit()',
                               extra={
                                   'master_id': master_id,
                                   'off_date': off_date
                               })

            if debug == 0:
                master_name = masterdao.get_master_name(master_id)
                send_jandi('HOMEMASTER_REST', "휴무 신청",
                           master_name + ' 홈마스터님 휴무 신청',
                           '휴무날짜 : {}'.format(off_date))

            ret['response'] = Response.SUCCESS
            self.set_status(Response.RESULT_OK)

            print 'master_id', master_id, 'request dayoff request', off_date
            print "day off request ------------------------------------------- end"

        except NoResultFound, e:
            self.set_status(Response.RESULT_OK)
            mongo_logger.debug('no result',
                               extra={
                                   'master_id': master_id,
                                   'off_date': off_date
                               })
            add_err_ko_message_to_response(ret, '휴무 신청 가능 날짜가 아닙니다.')
            return