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")

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

        ret = {}

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

            addr_idx = userdao.get_user_default_address_index(user_id)

            booking = MovingCleaningBooking(user_id=user_id,
                                            addr_idx=addr_idx,
                                            datetime=dt.datetime.now())
            session.add(booking)
            session.commit()

            # send sms
            sms_sender = SMS_Sender()
            name = str(userdao.get_user_name(user_id))
            phone = str(userdao.get_user_phone(user_id))
            address, size, kind = userdao.get_user_address_detail(user_id)
            address = str(address)
            if kind == 0:
                kind = '오피스텔'
            elif kind == 1:
                kind = '주택'
            elif kind == 2:
                kind = '아파트'

            text = '입주청소 예약 문의\n이름: %s\n번호: %s\n주소: %s\n종류: %s\n평수:%d' % (
                name, phone, address, kind, size)
            #print sms_sender.send_for_manager(sender = MAIN_CALL, mtype = 'lms', to = JAMES_CALL, text = str(text))

            # jandi notification
            send_jandi('MOVING_IN_CLEANING', "이사청소 문의", name + ' 고객님 이사청소 문의',
                       text)

            ret['response'] = Response.SUCCESS
            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'])
예제 #3
0
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        cleaning_id = self.get_argument('cleaning_id', '')
        payment = self.get_argument('payment', '')

        ret = {}

        mongo_logger = get_mongo_logger()

        try:
            addressdao = AddressDAO()
            doc = self.db.find_one_and_update({'cleaning_id' : cleaning_id},
                                            {'$set' : {'payment' : '후결제'}},
                                            return_document = ReturnDocument.AFTER)

            if payment == '현장결제':
                # jandi notification
                description = '{}({}) 고객님, 예약됨 {} {} - {}, {}'.format(doc['name'],
                            doc['phone'], doc['period'], doc['address'], doc['start_date'],
                            ','.join(doc['dates']))
                send_jandi('NEW_WEB', '[웹]신규예약', '후결제', description)

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

            mongo_logger.debug('web select payment',
                                            extra = {'cleaning_id' : cleaning_id,
                                                    'payment' : payment})

        except Exception, e:
            add_err_message_to_response(ret, err_dict['err_mysql'])
            self.set_status(Response.RESULT_SERVERERROR)
            print_err_detail(e)
            mongo_logger.error('failed to web select payment',
                                                  extra = {'cleaning_id' : cleaning_id,
                                                            'payment' : payment})
예제 #4
0
    def post(self):

        name = self.get_argument('name', '')
        birth = self.get_argument('birth', '')
        phone = self.get_argument('phone', '')
        address = self.get_argument('address', '')
        workingexp = self.get_argument('workingexp', '')

        ret = {}

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

        try:
            send_jandi(
                'APPLY_HOMEMASTER', "홈마스터 지원하기",
                '이름: {}, 번호: {}'.format(name, phone),
                '생년월일: {}, 사는곳: {}, 경력: {}'.format(birth, address, workingexp))

            # google docs
            row = []
            row.append(name)
            row.append(birth)
            row.append(phone)
            row.append(address)
            row.append(workingexp)
            row.append(dt.datetime.now())

            Google(row=row, key='1Rg5TYqJnNGGRwNc7pNwpoWUAbeN6_EP1kz2CtSv4EXY')

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

        except Exception, e:
            add_err_message_to_response(ret, err_dict['err_mysql'])
            self.set_status(Response.RESULT_SERVERERROR)
            print_err_detail(e)
예제 #5
0
    def notify_try_charge_unpaid(self):
        try:
            mongo_logger = get_mongo_logger()

            userdao = UserDAO()
            bookingdao = BookingDAO()

            current_time = dt.datetime.now()
            two_weeks_before = current_time - dt.timedelta(days=28)
            two_weeks_before = two_weeks_before.date()

            print '-' * 40
            print 'try charge unpaid notification via alimtalk'
            print 'cron_time :', current_time
            print '-' * 40

            session = Session()
            result = session.query(Booking, User) \
                            .join(User, Booking.user_id == User.id) \
                            .filter(func.Date(Booking.start_time) >= two_weeks_before) \
                            .filter(Booking.cleaning_status == BC.BOOKING_COMPLETED) \
                            .filter(Booking.payment_status != BC.BOOKING_PAID) \
                            .filter(User.is_b2b == 0) \
                            .filter(Booking.source == 'hm') \
                            .order_by(Booking.start_time) \
                            .all()

            for row in result:
                if 'b2b.com' in row.User.email:  # b2b 무시
                    continue

                if row.User.is_b2b == 1:  # b2b 무시
                    continue

                if row.Booking.source != 'hm':  # 11번가 무시
                    continue

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

                user_id = row.Booking.user_id
                user_name = crypto.decodeAES(row.User.name)
                phone = crypto.decodeAES(row.User.phone)

                booking_id = row.Booking.id
                appointment_type = row.Booking.appointment_type
                cleaning_time = convert_datetime_format2(
                    row.Booking.start_time)
                charge_price = row.Booking.price_with_task
                price = '{:,}원'.format(charge_price)

                print booking_id, user_id, user_name, cleaning_time, price

                status, try_charge, remain_days = bookingdao.is_next_booking_left_over_2days(
                    booking_id)
                print status, try_charge, remain_days

                if status == 'FAILURE':  # 다음 회차 예약 가져오기 실패. 건너 뜀
                    continue

                if try_charge:  # 결제를 시도해야함
                    ret, value = request_payment(user_id, user_name,
                                                 booking_id, charge_price,
                                                 appointment_type)

                    if ret:  # 결제 성공
                        row.Booking.payment_status = BC.BOOKING_PAID
                        session.commit()

                        print '*** success ***'

                        send_alimtalk(phone,
                                      'notify_try_charge_unpaid_success',
                                      cleaning_time, price)
                        mongo_logger.debug('user try charge success',
                                           extra={
                                               'dt': current_time,
                                               'user_id': user_id,
                                               'booking_id': booking_id,
                                               'price': price,
                                               'cleaning_time': cleaning_time
                                           })
                    else:  # 결제 실패
                        print '*** failed ***'
                        if remain_days == -1:
                            mongo_logger.debug('no booking remains',
                                               extra={
                                                   'dt': current_time,
                                                   'user_id': user_id,
                                                   'booking_id': booking_id,
                                                   'price': price,
                                                   'cleaning_time':
                                                   cleaning_time
                                               })

                        elif remain_days > 3:  # 3일 초과로 남았으면 실패 공지
                            send_alimtalk(phone, 'notify_charge_failure',
                                          cleaning_time, price)
                            mongo_logger.debug('user try charge fail',
                                               extra={
                                                   'dt': current_time,
                                                   'user_id': user_id,
                                                   'booking_id': booking_id,
                                                   'price': price,
                                                   'cleaning_time':
                                                   cleaning_time
                                               })

                        elif remain_days >= 0:  # 3일 이내면 전체 취소
                            print '*** cancel all ***'

                            bookingdao.cancel_all_upcomings(booking_id)

                            send_jandi(
                                'NEW_BOOKING', "미결제 전체 취소 알림",
                                user_name + ' 고객님 전체 취소됨',
                                '미결제 일시 : {}, 금액 : {}'.format(
                                    cleaning_time, price))

                            send_alimtalk(
                                phone, 'notify_try_charge_unpaid_cancel_all',
                                cleaning_time, price)
                            mongo_logger.debug('user try charge cancel all',
                                               extra={
                                                   'dt': current_time,
                                                   'user_id': user_id,
                                                   'booking_id': booking_id,
                                                   'price': price,
                                                   'cleaning_time':
                                                   cleaning_time
                                               })

        except Exception, e:
            print_err_detail(e)
            mongo_logger.error('failed to try charge failure',
                               extra={'err': str(e)})

if __name__ == '__main__':
    print dt.datetime.now()
    time_query = dt.datetime.now() - dt.timedelta(days = 3)
    query_date = time_query
    time_query = time_query.date()

    session = Session()
    records = session.query(OrderID11st.div_no) \
                    .filter(func.date(OrderID11st.datetime) >= time_query) \
                    .all()

    div_nos = [row[0] for row in records]

    now = dt.datetime.now()

    booking_checker = Booking11stChecker()
    orders, result_code, result_msg = booking_checker.check_11st_new_orders(query_date)

    # 예약 들어간 사항 필터링
    orders = [order for order in orders if order['dlvNo'] not in div_nos]
    for order in orders:
        user_name = order['rcvrNm']
        address = order['rcvrBaseAddr'] + ' ' + order['rcvrDtlsAddr']
        ord_date = order['ordDt']
        prd_name = order['prdNm']

        send_jandi('11ST_BOOKING', '11st 예약 알림', user_name + ' 고객님 예약됨',
                                '{}, {}, {}'.format(address, ord_date, prd_name))
예제 #7
0
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        ret = {}

        uid = self.get_argument('uid', '')
        search_keys = self.get_argument('search_keys', '')
        store_key = self.get_argument('store_key', '')

        price = self.get_argument('price', 0)
        price_with_task = self.get_argument('price_with_task', 0)

        wage_per_hour = self.get_argument('wage_per_hour', 0)
        address_index = self.get_argument('address_index', 0)

        discounted_price = self.get_argument('discounted_price', 0)
        promotion_code = self.get_argument('promotion_code', '')

        coupon_id = self.get_argument('coupon_id', '')
        coupon_discount_price = self.get_argument('coupon_discount_price', 0)

        laundry_apply_all = self.get_argument(
            'laundry_apply_all', 0)  # -1 - 없앰, 0 - one time, 1 - all time

        user_type = self.get_argument('user_type', 'unknown')

        # convert datetime

        # for ios fix
        if discounted_price != 0:
            discounted_price = discounted_price.replace('Optional(',
                                                        '').replace(')', '')

        price = int(price)
        price_with_task = int(price_with_task)
        discounted_price = int(discounted_price)
        coupon_discount_price = int(coupon_discount_price)
        laundry_apply_all = int(laundry_apply_all)
        wage_per_hour = int(wage_per_hour)

        print 'price_with_task', price_with_task
        print 'discounted_price', discounted_price

        search_keys = search_keys.split(',')

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        try:
            session = Session()
            userdao = UserDAO()
            masterdao = MasterDAO()
            promotiondao = PromotionDAO()
            addressdao = AddressDAO()
            coupondao = CouponDAO()

            holder = IntermediateValueHolder()

            # request id to group each individual bookings
            request_id = str(uuid.uuid4())

            obj = holder.retrieve(store_key)
            print obj
            if obj == None:
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_booking_timeout'])
                mix.track(uid, 'request timeout', {'time': dt.datetime.now()})
                mongo_logger.error('%s got timed out' % uid)
                return

            # retrieve all stored values
            uid = obj['user_id']
            mid = obj['master_id']
            dates = obj['dates']
            time = obj['time']
            appointment_type = obj['appointment_type']
            additional_task = obj['additional_task']
            org_additional_task = additional_task

            taking_time = obj['taking_time']
            first_added_time = obj['first_added_time']
            additional_time = obj['additional_time']
            total_time = obj['total_time']
            master_gender = obj['master_gender']
            have_pet = obj['have_pet']
            isdirty = obj['isdirty']

            is_b2b = userdao.is_b2b(uid)

            # hasids to generate unique booking id
            now = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d%H%M%S')
            hashids = Hashids(min_length=16, salt=now + uid)

            # set tool info
            havetools = 1
            if additional_task >= 64:
                havetools = 0

            card_idx = 0
            addr_idx = 0

            # get card and address idx
            if is_b2b:
                addr_idx = address_index
            else:
                addr_idx = userdao.get_user_default_address_index(uid)

            card_idx = userdao.get_user_default_card_index(uid)

            i = 1
            booking_ids = []
            start_time_list = []

            for date in dates:  #
                print date, time
                booking_id = hashids.encode(int(date + time.replace(':', '')))
                print 'key', booking_id
                master_id = mid

                date = dt.datetime.strptime(date, '%Y%m%d')
                dow = date.date().weekday()
                booking_time = dt.time(hour=int(time.split(':')[0]),
                                       minute=int(time.split(':')[1]))

                start_time = dt.datetime.combine(date, booking_time)
                estimated_end_time = start_time + dt.timedelta(
                    minutes=total_time)
                cleaning_duration = taking_time

                actual_price = 0
                if i == 1:  # 1 번째 클리닝
                    actual_price = price_with_task - (
                        discounted_price + coupon_discount_price
                    )  # 할인은 1회만 적용됨

                else:  # 나머지
                    actual_price = price
                    if havetools == 1:
                        additional_task = 0
                    else:
                        additional_task = 64

                    if laundry_apply_all == 1:
                        additional_task += 4  # 빨래

                    isdirty = 0  # 첫째 이후에는 is dirty는 0
                    estimated_end_time = estimated_end_time - dt.timedelta(
                        minutes=additional_time + first_added_time)

                booking = Booking(
                    id=booking_id,
                    request_id=request_id,
                    user_id=uid,
                    master_id=mid,
                    appointment_type=appointment_type,
                    appointment_index=i,
                    dow=dow,
                    booking_time=dt.datetime.now(),
                    org_start_time=start_time,
                    start_time=start_time,
                    estimated_end_time=estimated_end_time,
                    end_time=
                    estimated_end_time,  # update after homemaster finish their job
                    cleaning_duration=cleaning_duration,
                    additional_task=additional_task,
                    price=price,
                    price_with_task=actual_price,
                    charging_price=0,
                    card_idx=card_idx,
                    addr_idx=addr_idx,
                    havetools=havetools,
                    havepet=have_pet,
                    laundry_apply_all=laundry_apply_all,
                    is_dirty=isdirty,
                    master_gender=master_gender,
                    user_type=user_type,
                    wage_per_hour=wage_per_hour,
                    status=BC.BOOKING_UPCOMMING,
                    cleaning_status=BC.BOOKING_UPCOMMING,
                    payment_status=BC.BOOKING_UNPAID_YET)
                i += 1

                session.add(booking)
                booking_ids.append(booking_id)
                start_time_list.append(start_time)

                #print 'booking_id', booking_id, 'was added..'

            # charge for first appointment date
            user_name = userdao.get_user_name(uid)

            if is_b2b:
                session.commit()

                # remove store_key and related_keys
                holder.remove(store_key)
                for sk in search_keys:
                    holder.remove(sk)

                send_jandi('NEW_BOOKING', '[b2b]새 예약 알림', 'b2b 고객님 예약완료',
                           user_name)

                # b2b용 알림톡 추가 필요

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

                mongo_logger.debug('b2b confirm booking',
                                   extra={
                                       'user_id': uid,
                                       'master_id': mid,
                                       'booking_id': booking_ids[0]
                                   })

                return

            charge_price = price_with_task - (discounted_price +
                                              coupon_discount_price)

            # 1주 1회면서, 이벤트 기간인 경우에는 결제 하지 않음
            import redis
            try:
                from utils.secrets import REDIS_HOST, REDIS_PORT, REDIS_PWD
            except ImportError:
                REDIS_HOST = 'localhost'
                REDIS_PORT = 6379
                REDIS_PWD = ''

            r = redis.Redis(host=REDIS_HOST,
                            port=REDIS_PORT,
                            password=REDIS_PWD)
            event_on = r.get('free_event')

            print event_on
            if appointment_type == 4 and event_on:
                charge_price = price_with_task - price

                # 1회 이벤트 고객임을 명시해야함
                # table 필요
                free_event = UserFreeEvent(booking_request_id=request_id,
                                           user_id=uid,
                                           datetime=dt.datetime.now())
                session.add(free_event)

            if charge_price <= 0:
                ret_code = True
                msg = ''
            else:
                ret_code, msg = request_payment(uid, user_name, booking_ids[0],
                                                charge_price, appointment_type)

            # 결제 정보 출력
            print user_name, ret_code, msg

            if ret_code:
                session.commit()

                # remove store_key and related_keys
                holder.remove(store_key)
                for sk in search_keys:
                    holder.remove(sk)

                # promotion code 와 연결
                if promotion_code != '':
                    promotiondao.set_promotion_code_status(
                        promotion_code, 1, booking_ids[0], price_with_task)

                if coupon_id != '':
                    coupondao.set_coupon_status(coupon_id, 1, booking_ids[0],
                                                price_with_task)

                # change status to paid
                try:
                    first_booking = session.query(Booking, User, MasterPushKey) \
                                            .join(User, Booking.user_id == User.id) \
                                            .outerjoin(MasterPushKey, Booking.master_id == MasterPushKey.master_id) \
                                            .filter(Booking.id == booking_ids[0]) \
                                            .one()
                except NoResultFound, e:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    mongo_logger.debug('no first booking record',
                                       extra={
                                           'uid': uid,
                                           'mid': mid,
                                           'appointment_type':
                                           appointment_type,
                                           'have_pet': have_pet,
                                           'master_gender': master_gender,
                                           'isdirty': isdirty
                                       })
                    add_err_message_to_response(ret, err_dict['err_no_record'])
                    return

                except MultipleResultsFound, e:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    mongo_logger.debug('multiple first booking record',
                                       extra={
                                           'uid': uid,
                                           'mid': mid,
                                           'appointment_type':
                                           appointment_type,
                                           'have_pet': have_pet,
                                           'master_gender': master_gender,
                                           'isdirty': isdirty
                                       })
                    add_err_message_to_response(
                        ret, err_dict['err_multiple_record'])
                    return
예제 #8
0
class RequestConfirmScheduleHandler(tornado.web.RequestHandler):
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        ret = {}

        uid = self.get_argument('uid', '')
        search_keys = self.get_argument('search_keys', '')
        store_key = self.get_argument('store_key', '')

        price = self.get_argument('price', 0)
        price_with_task = self.get_argument('price_with_task', 0)

        wage_per_hour = self.get_argument('wage_per_hour', 0)
        address_index = self.get_argument('address_index', 0)

        discounted_price = self.get_argument('discounted_price', 0)
        promotion_code = self.get_argument('promotion_code', '')

        coupon_id = self.get_argument('coupon_id', '')
        coupon_discount_price = self.get_argument('coupon_discount_price', 0)

        laundry_apply_all = self.get_argument(
            'laundry_apply_all', 0)  # -1 - 없앰, 0 - one time, 1 - all time

        user_type = self.get_argument('user_type', 'unknown')

        # convert datetime

        # for ios fix
        if discounted_price != 0:
            discounted_price = discounted_price.replace('Optional(',
                                                        '').replace(')', '')

        price = int(price)
        price_with_task = int(price_with_task)
        discounted_price = int(discounted_price)
        coupon_discount_price = int(coupon_discount_price)
        laundry_apply_all = int(laundry_apply_all)
        wage_per_hour = int(wage_per_hour)

        print 'price_with_task', price_with_task
        print 'discounted_price', discounted_price

        search_keys = search_keys.split(',')

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        try:
            session = Session()
            userdao = UserDAO()
            masterdao = MasterDAO()
            promotiondao = PromotionDAO()
            addressdao = AddressDAO()
            coupondao = CouponDAO()

            holder = IntermediateValueHolder()

            # request id to group each individual bookings
            request_id = str(uuid.uuid4())

            obj = holder.retrieve(store_key)
            print obj
            if obj == None:
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_booking_timeout'])
                mix.track(uid, 'request timeout', {'time': dt.datetime.now()})
                mongo_logger.error('%s got timed out' % uid)
                return

            # retrieve all stored values
            uid = obj['user_id']
            mid = obj['master_id']
            dates = obj['dates']
            time = obj['time']
            appointment_type = obj['appointment_type']
            additional_task = obj['additional_task']
            org_additional_task = additional_task

            taking_time = obj['taking_time']
            first_added_time = obj['first_added_time']
            additional_time = obj['additional_time']
            total_time = obj['total_time']
            master_gender = obj['master_gender']
            have_pet = obj['have_pet']
            isdirty = obj['isdirty']

            is_b2b = userdao.is_b2b(uid)

            # hasids to generate unique booking id
            now = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d%H%M%S')
            hashids = Hashids(min_length=16, salt=now + uid)

            # set tool info
            havetools = 1
            if additional_task >= 64:
                havetools = 0

            card_idx = 0
            addr_idx = 0

            # get card and address idx
            if is_b2b:
                addr_idx = address_index
            else:
                addr_idx = userdao.get_user_default_address_index(uid)

            card_idx = userdao.get_user_default_card_index(uid)

            i = 1
            booking_ids = []
            start_time_list = []

            for date in dates:  #
                print date, time
                booking_id = hashids.encode(int(date + time.replace(':', '')))
                print 'key', booking_id
                master_id = mid

                date = dt.datetime.strptime(date, '%Y%m%d')
                dow = date.date().weekday()
                booking_time = dt.time(hour=int(time.split(':')[0]),
                                       minute=int(time.split(':')[1]))

                start_time = dt.datetime.combine(date, booking_time)
                estimated_end_time = start_time + dt.timedelta(
                    minutes=total_time)
                cleaning_duration = taking_time

                actual_price = 0
                if i == 1:  # 1 번째 클리닝
                    actual_price = price_with_task - (
                        discounted_price + coupon_discount_price
                    )  # 할인은 1회만 적용됨

                else:  # 나머지
                    actual_price = price
                    if havetools == 1:
                        additional_task = 0
                    else:
                        additional_task = 64

                    if laundry_apply_all == 1:
                        additional_task += 4  # 빨래

                    isdirty = 0  # 첫째 이후에는 is dirty는 0
                    estimated_end_time = estimated_end_time - dt.timedelta(
                        minutes=additional_time + first_added_time)

                booking = Booking(
                    id=booking_id,
                    request_id=request_id,
                    user_id=uid,
                    master_id=mid,
                    appointment_type=appointment_type,
                    appointment_index=i,
                    dow=dow,
                    booking_time=dt.datetime.now(),
                    org_start_time=start_time,
                    start_time=start_time,
                    estimated_end_time=estimated_end_time,
                    end_time=
                    estimated_end_time,  # update after homemaster finish their job
                    cleaning_duration=cleaning_duration,
                    additional_task=additional_task,
                    price=price,
                    price_with_task=actual_price,
                    charging_price=0,
                    card_idx=card_idx,
                    addr_idx=addr_idx,
                    havetools=havetools,
                    havepet=have_pet,
                    laundry_apply_all=laundry_apply_all,
                    is_dirty=isdirty,
                    master_gender=master_gender,
                    user_type=user_type,
                    wage_per_hour=wage_per_hour,
                    status=BC.BOOKING_UPCOMMING,
                    cleaning_status=BC.BOOKING_UPCOMMING,
                    payment_status=BC.BOOKING_UNPAID_YET)
                i += 1

                session.add(booking)
                booking_ids.append(booking_id)
                start_time_list.append(start_time)

                #print 'booking_id', booking_id, 'was added..'

            # charge for first appointment date
            user_name = userdao.get_user_name(uid)

            if is_b2b:
                session.commit()

                # remove store_key and related_keys
                holder.remove(store_key)
                for sk in search_keys:
                    holder.remove(sk)

                send_jandi('NEW_BOOKING', '[b2b]새 예약 알림', 'b2b 고객님 예약완료',
                           user_name)

                # b2b용 알림톡 추가 필요

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

                mongo_logger.debug('b2b confirm booking',
                                   extra={
                                       'user_id': uid,
                                       'master_id': mid,
                                       'booking_id': booking_ids[0]
                                   })

                return

            charge_price = price_with_task - (discounted_price +
                                              coupon_discount_price)

            # 1주 1회면서, 이벤트 기간인 경우에는 결제 하지 않음
            import redis
            try:
                from utils.secrets import REDIS_HOST, REDIS_PORT, REDIS_PWD
            except ImportError:
                REDIS_HOST = 'localhost'
                REDIS_PORT = 6379
                REDIS_PWD = ''

            r = redis.Redis(host=REDIS_HOST,
                            port=REDIS_PORT,
                            password=REDIS_PWD)
            event_on = r.get('free_event')

            print event_on
            if appointment_type == 4 and event_on:
                charge_price = price_with_task - price

                # 1회 이벤트 고객임을 명시해야함
                # table 필요
                free_event = UserFreeEvent(booking_request_id=request_id,
                                           user_id=uid,
                                           datetime=dt.datetime.now())
                session.add(free_event)

            if charge_price <= 0:
                ret_code = True
                msg = ''
            else:
                ret_code, msg = request_payment(uid, user_name, booking_ids[0],
                                                charge_price, appointment_type)

            # 결제 정보 출력
            print user_name, ret_code, msg

            if ret_code:
                session.commit()

                # remove store_key and related_keys
                holder.remove(store_key)
                for sk in search_keys:
                    holder.remove(sk)

                # promotion code 와 연결
                if promotion_code != '':
                    promotiondao.set_promotion_code_status(
                        promotion_code, 1, booking_ids[0], price_with_task)

                if coupon_id != '':
                    coupondao.set_coupon_status(coupon_id, 1, booking_ids[0],
                                                price_with_task)

                # change status to paid
                try:
                    first_booking = session.query(Booking, User, MasterPushKey) \
                                            .join(User, Booking.user_id == User.id) \
                                            .outerjoin(MasterPushKey, Booking.master_id == MasterPushKey.master_id) \
                                            .filter(Booking.id == booking_ids[0]) \
                                            .one()
                except NoResultFound, e:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    mongo_logger.debug('no first booking record',
                                       extra={
                                           'uid': uid,
                                           'mid': mid,
                                           'appointment_type':
                                           appointment_type,
                                           'have_pet': have_pet,
                                           'master_gender': master_gender,
                                           'isdirty': isdirty
                                       })
                    add_err_message_to_response(ret, err_dict['err_no_record'])
                    return

                except MultipleResultsFound, e:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    mongo_logger.debug('multiple first booking record',
                                       extra={
                                           'uid': uid,
                                           'mid': mid,
                                           'appointment_type':
                                           appointment_type,
                                           'have_pet': have_pet,
                                           'master_gender': master_gender,
                                           'isdirty': isdirty
                                       })
                    add_err_message_to_response(
                        ret, err_dict['err_multiple_record'])
                    return

                for bid in booking_ids:
                    print 'booking_id', bid, 'was added successfully...'

                tid = msg
                first_booking.Booking.tid = tid
                first_booking.Booking.status = BC.BOOKING_PAID
                first_booking.Booking.clearning_status = BC.BOOKING_UPCOMMING
                first_booking.Booking.payment_status = BC.BOOKING_PAID

                cleaning_time = convert_datetime_format2(
                    first_booking.Booking.start_time)
                devicetype = first_booking.User.devicetype
                master_pushkey = first_booking.MasterPushKey.pushkey if first_booking.MasterPushKey != None else ''

                session.commit()

                mix.track(
                    uid, 'confirm booking', {
                        'time': dt.datetime.now(),
                        'appointment_type': appointment_type,
                        'additional_task': additional_task
                    })
                mongo_logger.debug('confirm booking',
                                   extra={
                                       'log_time': dt.datetime.now(),
                                       'user_id': uid,
                                       'master_id': mid,
                                       'booking_id': booking_ids[0],
                                       'start_time': start_time_list[0]
                                   })

                #ret['response'] = {'booking_ids' : booking_ids} # victor 요청으로 첫번째
                ret['response'] = booking_ids[0]
                self.set_status(Response.RESULT_OK)

                # notification to iphone users
                #send_booking_iphone(booking_ids[0]) # ios released!! 03.23

                # alimtalk
                phone = userdao.get_user_phone(uid)
                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회'

                service = '기본 클리닝'
                if org_additional_task != 0:
                    service += ', {}'.format(
                        additional_task_string(org_additional_task))

                if len(phone) > 11:
                    phone = phone[:11]

                # jandi notification
                user_address, _, _ = userdao.get_user_address_by_index(
                    uid, addr_idx)
                district = addressdao.get_gu_name(
                    userdao.get_user_address(uid)[0])
                print district

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

                send_jandi(
                    'NEW_BOOKING', '[{}] 새 예약 알림'.format(user_type),
                    user_name + ' 고객님 예약됨',
                    '({}), {} 홈마스터, {}, {}'.format(district, master_name,
                                                   start_time_list[0],
                                                   appointment_type_text))

                send_alimtalk(phone, 'noti_reservation', user_name,
                              cleaning_time, appointment_type_text, service,
                              'http://goo.gl/j6PByf')
                send_alimtalk(phone, 'noti_caution', 'https://goo.gl/FxrJML',
                              'http://goo.gl/kuCVIh')

                # notification to homemaster
                send_new_booking_notification('android', [master_pushkey],
                                              booking_ids[0], cleaning_time)

                content = '''안녕하세요 {} 홈마스터님, 새로운 예약 정보를 알려드립니다.

                    날짜 : {}
                    주소 : {}
                    주기/서비스 : {} {}

                    자세한 내용은 마스터님 앱에서 확인 부탁 드립니다 ^^'''.format(
                    master_name, convert_datetime_format2(start_time_list[0]),
                    user_address, appointment_type_text, service)
                message_sender = MessageSender()
                print master_phone
                message_sender.send([master_phone], '새로운 예약 알림', content)
예제 #9
0
class RatingHandler(tornado.web.RequestHandler):
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        ret = {}

        booking_id = self.get_argument('booking_id', '')
        c_rate = self.get_argument('clean_rate', 0.0)
        c_review_msg = self.get_argument('clean_review', '')
        m_rate = self.get_argument('master_rate', 0.0)
        m_review_msg = self.get_argument('master_review', '')

        c_rate = float(c_rate)
        m_rate = float(m_rate)

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        try:
            session = Session()

            try:
                row = session.query(Booking).filter(
                    Booking.id == booking_id).one()

            except NoResultFound, e:
                session.close()
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret, err_dict['err_no_record'])
                return

            except MultipleResultsFound, e:
                session.close()
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_multiple_record'])
                return

            master_id = row.master_id
            user_id = row.user_id

            rating = Rating(booking_id=booking_id,
                            master_id=master_id,
                            rate_clean=c_rate,
                            review_clean=c_review_msg,
                            rate_master=m_rate,
                            review_master=m_review_msg,
                            review_time=dt.datetime.now())

            session.add(rating)

            row.havereview = 1  # review flag update

            if c_rate + m_rate == 10:
                master_id = row.master_id
                # 평점 5점 이상 1점 획득
                master_prize = MasterPrize(master_id=master_id,
                                           prize=3000,
                                           prize_description='평점 5점',
                                           earn_date=dt.datetime.now())
                session.add(master_prize)

            session.commit()

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

            mix.track(
                user_id, 'rated', {
                    'time': dt.datetime.now(),
                    'c_rate': c_rate,
                    'm_rate': m_rate,
                    'c_msg': c_review_msg,
                    'm_msg': m_review_msg
                })
            mongo_logger.debug('rated',
                               extra={
                                   'user_id': user_id,
                                   'c_rate': c_rate,
                                   'm_rate': m_rate,
                                   'c_msg': c_review_msg,
                                   'm_msg': m_review_msg
                               })

            #send_rating_granted(booking_id, c_rate, m_rate)

            userdao = UserDAO()
            masterdao = MasterDAO()

            user_name = userdao.get_user_name(user_id)
            master_name = masterdao.get_master_name(master_id)

            #for manager_phone in MANAGERS_CALL.split(','):
            #    send_alimtalk(manager_phone, 'noti_manager_rate', user_name, master_name, c_rate, m_rate)
            send_jandi(
                'NEW_BOOKING', "평가 알림",
                user_name + ' 고객님,' + master_name + '님 평가',
                '클리닝 평가 : {}, 마스터 평가 : {}\n클리닝 평가 내용 : {}\n\n, 마스터 평가 내용 : {}'.
                format(c_rate, m_rate, c_review_msg, m_review_msg))

            print booking_id, 'was successfully rated...'
예제 #10
0
class RequestConfirmScheduleWebHandler(tornado.web.RequestHandler):
    def post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        ret = {}

        uid = self.get_argument('uid', '')
        search_keys = self.get_argument('search_keys', '')
        store_key = self.get_argument('store_key', '')

        #price                   = self.get_argument('price', 0)
        #price_with_task         = self.get_argument('price_with_task', 0)
        #discounted_price        = self.get_argument('discounted_price', 0)
        promotion_code = self.get_argument('promotion_code', '')

        laundry_apply_all = self.get_argument(
            'laundry_apply_all', 0)  # -1 - 없앰, 0 - one time, 1 - all time

        has_card = self.get_argument('has_card', 0)
        # ---------- card paremeters ------------
        cno = self.get_argument('cno', '')
        expy = self.get_argument('expy', '')
        expm = self.get_argument('expm', '')
        ssnf = self.get_argument('ssnf', '')
        cpftd = self.get_argument('cpftd', '')
        calias = self.get_argument('calias', '')

        # register card
        request_url = '%s:%d/homemaster_payment/register_card' % (PAYMENT_HOST,
                                                                  PAYMENT_PORT)
        params = {}
        params['id'] = uid
        params['cno'] = cno
        params['expy'] = expy
        params['expm'] = expm
        params['ssnf'] = ssnf
        params['cpftd'] = cpftd
        params['calias'] = calias

        has_card = int(has_card)

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        # 카드가 없는 경우에만 카드 등록하고 진행, 있다면 바로 진행
        if has_card == 0:
            response = requests.post(request_url, data=params)
            result = json.loads(response.text)

            if response.status_code != 200 or result['response'] == "":
                print 'An error occurred while register card'
                print result['err_code'], result['err_msg']
                add_err_ko_message_to_response(ret, result['err_msg'])
                mongo_logger.error('register card failed', extra={'uid': uid})
                return

        laundry_apply_all = int(laundry_apply_all)

        search_keys = search_keys.split(',')

        try:
            session = Session()
            userdao = UserDAO()
            masterdao = MasterDAO()
            promotiondao = PromotionDAO()
            addressdao = AddressDAO()

            holder = IntermediateValueHolder()

            # request id to group each individual bookings
            request_id = str(uuid.uuid4())

            obj = holder.retrieve(store_key)
            print obj
            if obj == None:
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_booking_timeout'])
                mix.track(uid, 'request timeout', {'time': dt.datetime.now()})
                mongo_logger.error('%s got timed out' % uid)
                return

            # retrieve all stored values
            uid = obj['user_id']
            mid = obj['master_id']
            dates = obj['dates']
            time = obj['time']
            appointment_type = obj['appointment_type']
            additional_task = obj['additional_task']
            org_additional_task = additional_task

            taking_time = obj['taking_time']
            first_added_time = obj['first_added_time']
            additional_time = obj['additional_time']
            total_time = obj['total_time']
            master_gender = obj['master_gender']
            have_pet = obj['have_pet']
            isdirty = obj['isdirty']

            # price
            # price_with_task
            # discounted_price
            address, house_size, house_type = userdao.get_user_address_detail(
                uid)
            _, _, price, _ = get_time_price(appointment_type, house_type,
                                            house_size)
            _, additional_price = get_additional_task_time_price(
                additional_task, house_type, house_size)

            discounted_price = 0
            if promotion_code != '':
                discounted_price = promotiondao.get_discount_price(
                    promotion_code)

            price_with_task = price + additional_price
            if 0 < discounted_price <= 100:
                price_with_task *= (float(100 - discounted_price) / 100)
            else:
                price_with_task -= discounted_price

            price_with_task = int(price_with_task)

            print '-' * 30
            print price, additional_price
            print promotion_code, price_with_task
            print '##' * 20

            # hasids to generate unique booking id
            now = dt.datetime.strftime(dt.datetime.now(), '%Y%m%d%H%M%S')
            hashids = Hashids(min_length=16, salt=now + uid)

            # set tool info
            havetools = 1
            if additional_task >= 64:
                havetools = 0

            card_idx = 0
            addr_idx = 0

            # get card and address idx
            addr_idx = userdao.get_user_default_address_index(uid)
            card_idx = userdao.get_user_default_card_index(uid)

            i = 1
            booking_ids = []
            start_time_list = []

            for date in dates:  #
                print date, time
                booking_id = hashids.encode(int(date + time.replace(':', '')))
                print 'key', booking_id
                master_id = mid

                date = dt.datetime.strptime(date, '%Y%m%d')
                dow = date.date().weekday()
                booking_time = dt.time(hour=int(time.split(':')[0]),
                                       minute=int(time.split(':')[1]))

                start_time = dt.datetime.combine(date, booking_time)
                estimated_end_time = start_time + dt.timedelta(
                    minutes=total_time)
                cleaning_duration = taking_time

                actual_price = 0
                if i == 1:  # 1 번째 클리닝
                    actual_price = price_with_task  # 할인은 1회만 적용됨

                else:  # 나머지
                    actual_price = price
                    if havetools == 1:
                        additional_task = 0
                    else:
                        additional_task = 64

                    if laundry_apply_all == 1:
                        additional_task += 4  # 빨래

                    isdirty = 0  # 첫째 이후에는 is dirty는 0
                    estimated_end_time = estimated_end_time - dt.timedelta(
                        minutes=additional_time + first_added_time)

                booking = Booking(
                    id=booking_id,
                    request_id=request_id,
                    user_id=uid,
                    master_id=mid,
                    appointment_type=appointment_type,
                    appointment_index=i,
                    dow=dow,
                    booking_time=dt.datetime.now(),
                    org_start_time=start_time,
                    start_time=start_time,
                    estimated_end_time=estimated_end_time,
                    end_time=
                    estimated_end_time,  # update after homemaster finish their job
                    cleaning_duration=cleaning_duration,
                    additional_task=additional_task,
                    price=price,
                    price_with_task=actual_price,
                    charging_price=0,
                    card_idx=card_idx,
                    addr_idx=addr_idx,
                    havetools=havetools,
                    havepet=have_pet,
                    laundry_apply_all=laundry_apply_all,
                    is_dirty=isdirty,
                    master_gender=master_gender,
                    status=BC.BOOKING_UPCOMMING,
                    cleaning_status=BC.BOOKING_UPCOMMING,
                    payment_status=BC.BOOKING_UNPAID_YET)
                i += 1

                session.add(booking)
                booking_ids.append(booking_id)
                start_time_list.append(start_time)

                #print 'booking_id', booking_id, 'was added..'

            # charge for first appointment date
            user_name = userdao.get_user_name(uid)
            if price_with_task <= 0:
                ret_code = True
                msg = ''
            else:
                ret_code, msg = request_payment(uid, user_name, booking_ids[0],
                                                price_with_task,
                                                appointment_type)

            # 결제 정보 출력
            print user_name, ret_code, msg

            if ret_code:
                session.commit()

                # remove store_key and related_keys
                holder.remove(store_key)
                for sk in search_keys:
                    holder.remove(sk)

                # promotion code 와 연결
                if promotion_code != '':
                    promotiondao.set_promotion_code_status(
                        promotion_code, 1, booking_ids[0], price_with_task)

                # change status to paid
                try:
                    first_booking = session.query(Booking, User, MasterPushKey) \
                                            .join(User, Booking.user_id == User.id) \
                                            .outerjoin(MasterPushKey, Booking.master_id == MasterPushKey.master_id) \
                                            .filter(Booking.id == booking_ids[0]) \
                                            .one()
                except NoResultFound, e:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    mongo_logger.debug('no first booking record',
                                       extra={
                                           'uid': uid,
                                           'mid': mid,
                                           'appointment_type':
                                           appointment_type,
                                           'have_pet': have_pet,
                                           'master_gender': master_gender,
                                           'isdirty': isdirty
                                       })
                    add_err_message_to_response(ret, err_dict['err_no_record'])
                    return

                except MultipleResultsFound, e:
                    session.close()
                    self.set_status(Response.RESULT_OK)
                    mongo_logger.debug('multiple first booking record',
                                       extra={
                                           'uid': uid,
                                           'mid': mid,
                                           'appointment_type':
                                           appointment_type,
                                           'have_pet': have_pet,
                                           'master_gender': master_gender,
                                           'isdirty': isdirty
                                       })
                    add_err_message_to_response(
                        ret, err_dict['err_multiple_record'])
                    return

                for bid in booking_ids:
                    print 'booking_id', bid, 'was added successfully...'

                tid = msg
                first_booking.Booking.tid = tid
                first_booking.Booking.status = BC.BOOKING_PAID
                first_booking.Booking.clearning_status = BC.BOOKING_UPCOMMING
                first_booking.Booking.payment_status = BC.BOOKING_PAID

                cleaning_time = convert_datetime_format2(
                    first_booking.Booking.start_time)
                devicetype = first_booking.User.devicetype
                master_pushkey = first_booking.MasterPushKey.pushkey if first_booking.MasterPushKey != None else ''

                session.commit()

                mix.track(
                    uid, 'confirm booking', {
                        'time': dt.datetime.now(),
                        'appointment_type': appointment_type,
                        'additional_task': additional_task
                    })
                mongo_logger.debug('confirm booking',
                                   extra={
                                       'log_time': dt.datetime.now(),
                                       'user_id': uid,
                                       'master_id': mid,
                                       'booking_id': booking_ids[0],
                                       'start_time': start_time_list[0]
                                   })

                #ret['response'] = {'booking_ids' : booking_ids} # victor 요청으로 첫번째
                ret['response'] = {
                    'booking_id': booking_ids[0],
                    'price': price_with_task
                }
                self.set_status(Response.RESULT_OK)

                # notification to iphone users
                #send_booking_iphone(booking_ids[0]) # ios released!! 03.23

                # alimtalk
                phone = userdao.get_user_phone(uid)
                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회'

                service = '기본 클리닝'
                if org_additional_task != 0:
                    service += ', {}'.format(
                        additional_task_string(org_additional_task))

                if len(phone) > 11:
                    phone = phone[:11]

                # notification to managers
                #send_booking_requested(booking_ids[0])
                #for manager_phone in MANAGERS_CALL.split(','):
                #    send_alimtalk(manager_phone, 'noti_manager_new', user_name, appointment_type_text)

                # jandi notification
                district = addressdao.get_gu_name(
                    userdao.get_user_address(uid)[0])
                send_jandi('NEW_BOOKING', "[웹]새 예약 알림", user_name + ' 고객님 예약됨',
                           '({}), {}'.format(district, appointment_type_text))

                #master_phone = masterdao.get_master_phone(mid)
                #send_alimtalk(master_phone, 'noti_manager_new', user_name, appointment_type_text)

                web_noti = "예약 변경 및 취소는 오직 모바일 앱을 통해서만 가능합니다.\n스토어에서 ‘홈마스터' 앱을 다운받아 주세요.\n구글플레이스토어 :\nhttps://goo.gl/qJ2g7b\n앱스토어 :\nhttps://goo.gl/1OE5W6\n(고객센터 1800-0199)"

                send_alimtalk(phone, 'noti_reservation', user_name,
                              cleaning_time, appointment_type_text, service,
                              web_noti)
                send_alimtalk(phone, 'noti_caution', 'https://goo.gl/FxrJML',
                              'http://goo.gl/kuCVIh')

                # notification to homemaster
                send_new_booking_notification('android', [master_pushkey],
                                              booking_ids[0], cleaning_time)
class RegisterCardAndChargeHandler(tornado.web.RequestHandler):
    def initialize(self, mongo):

        self.mongo = mongo
        booking = mongo.booking
        booking.authenticate(MONGO_USER, MONGO_PWD, source='booking')

        self.db = booking.customer

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

        cleaning_id = self.get_argument('cleaning_id', '')
        cno = self.get_argument('cno', '')
        expy = self.get_argument('expy', '')
        expm = self.get_argument('expm', '')
        ssnf = self.get_argument('ssnf', '')
        cpftd = self.get_argument('cpftd', '')
        calias = self.get_argument('calias', '')

        ret = {}

        try:
            mongo_logger = get_mongo_logger()
            mix = get_mixpanel()

            userdao = UserDAO()

            doc = self.db.find_one_and_update(
                {'cleaning_id': cleaning_id}, {'$set': {
                    'payment': '선결제'
                }},
                return_document=ReturnDocument.AFTER)
            if doc == None:
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_no_cleaning_id'])
                return

            print cno

            try:
                uid = doc['user_id']
            except Exception, e:
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret, err_dict['err_no_user_id'])
                return

            try:
                amount = int(doc['total_price'])
            except Exception, e:
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_invalid_amount'])
                return

            address = doc['address']
            period = doc['period']
            dates = ','.join(doc['dates'])
            start_date = doc['start_date']

            request_url = '%s:%d/homemaster_payment/register_card' % (
                PAYMENT_HOST, PAYMENT_PORT)
            params = {}
            params['id'] = uid
            params['cno'] = cno
            params['expy'] = expy
            params['expm'] = expm
            params['ssnf'] = ssnf
            params['cpftd'] = cpftd
            params['calias'] = calias

            response = requests.post(request_url, data=params)
            result = json.loads(response.text)

            if response.status_code == 200 and result['response'] != "":
                mix.track(uid, 'register card', {
                    'time': dt.datetime.now(),
                    'calias': calias
                })
                mongo_logger.debug('%s registered card' % uid,
                                   extra={'user_id': uid})

                user_name = userdao.get_user_name(uid)
                user_phone = userdao.get_user_phone(uid)

                import redis
                try:
                    from utils.secrets import REDIS_HOST, REDIS_PORT, REDIS_PWD
                except ImportError:
                    REDIS_HOST = 'localhost'
                    REDIS_PORT = 6379
                    REDIS_PWD = ''

                r = redis.Redis(host=REDIS_HOST,
                                port=REDIS_PORT,
                                password=REDIS_PWD)
                event_on = r.get('free_event')

                if period in ['매주여러번', '매주한번'] and event_on:
                    result = True
                    msg = ''
                else:
                    result, msg = request_payment_web(uid, user_name, amount)

                if result:
                    ret['response'] = Response.SUCCESS

                    # jandi notification
                    description = '{}({}) 고객님, 예약됨 {} {} - {}, {}'.format(
                        user_name, user_phone, period, address, start_date,
                        dates)

                    send_jandi('NEW_WEB', '[웹]신규예약', '선결제', description)
                else:
                    ret['response'] = ''
                    ret['err_msg'] = msg

                self.set_status(Response.RESULT_OK)

                mongo_logger.debug('request payment web',
                                   extra={
                                       'user_id': uid,
                                       'amount': amount
                                   })
            else:
                print 'An error occurred while register card'
                print result['err_code'], result['err_msg']
                add_err_ko_message_to_response(ret, result['err_msg'])

                mix.track(uid, 'cannot register card',
                          {'time': dt.datetime.now()})
                mongo_logger.error('%s failed to register card' % uid,
                                   extra={'err': result['err_msg']})
    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 post(self):
        self.set_header("Content-Type", "application/json")
        self.set_header('Access-Control-Allow-Origin', '*')

        ret = {}

        uid                         = self.get_argument('uid', '')
        appointment_type            = self.get_argument('appointment_type', BC.ONE_TIME)
        taking_time                 = self.get_argument('taking_time', 25)
        first_added_time            = self.get_argument('first_added_time', 0)
        additional_time             = self.get_argument('additional_time', 0)
        have_pet                    = self.get_argument('have_pet', 0)
        master_gender               = self.get_argument('master_gender', 0)
        isdirty                     = self.get_argument('isdirty', 0)
        for_manager                 = self.get_argument('for_manager', '')

        # for b2b appointment
        user_address_idx            = self.get_argument('user_address_idx', -1)
        b2b                         = self.get_argument('b2b', '')

        # convert parameters
        appointment_type                = int(appointment_type)
        taking_time                     = int(taking_time)
        first_added_time                = int(first_added_time)
        additional_time                 = int(additional_time)

        taking_time_in_minutes          = taking_time * 6
        first_added_time_in_minutes     = first_added_time * 6
        additional_time_in_minutes      = additional_time * 6
        total_taking_time_in_minutes    = taking_time_in_minutes + first_added_time_in_minutes + additional_time_in_minutes

        have_pet                        = int(have_pet)
        master_gender                   = int(master_gender) # 0 dont care 1 women
        isdirty                         = int(isdirty)


        # logging part
        mix = get_mixpanel()
        mongo_logger = get_mongo_logger()

        try:
            if self.is_user_block(ret, uid) == True:
                return

            if appointment_type == BC.ONE_TIME_A_MONTH and b2b != 'b2b':
                self.set_status(Response.RESULT_OK)
                add_err_ko_message_to_response(ret, '4주 1회 서비스는 신규 예약을 지원하지 않습니다.')
                mongo_logger.debug('not booking one time a month', extra = { 'user_id' : uid })
                ret['err_code'] = '4038' # 임시 처리
                return


            if total_taking_time_in_minutes >= 600:
                self.set_status(Response.RESULT_OK)
                add_err_ko_message_to_response(ret, '클리닝 가능 시간을 초과하였습니다. (최대 10시간) 이전 화면으로 돌아가 추가사항을 2개이하로 줄여주세요.')
                ret['err_code'] = '4036' # 임시 처리
                return

            scheduler = HMScheduler()

            userdao = UserDAO()
            addrdao = AddressDAO()


            if user_address_idx == -1: # default_address
                address, geohash5, geohash6 = userdao.get_user_address(uid)
                _, size, kind = userdao.get_user_address_detail(uid)
            else: # address selection
                address, geohash5, geohash6 = userdao.get_user_address_by_index(uid, user_address_idx)
                _, size, kind = userdao.get_user_address_detail_by_index(uid, user_address_idx)

            gu_id = addrdao.get_gu_id(address)

            if gu_id == '':
                raise Exception('gu id is incorrect')

            available_schedules = scheduler.get_available_slots(gu_id = gu_id, geohash = geohash6, appointment_type = appointment_type, taking_time = total_taking_time_in_minutes,
                                                                prefer_women = True if master_gender == 1 else False,
                                                                have_pet = True if have_pet == 1 else False,
                                                                isdirty = True if isdirty == 1 else False,
                                                                user_id = uid)


            now = dt.datetime.now()
            if now.hour >= 17: # 7시 이후 라면 -> 5시로 변경 2016.06.03
                if for_manager == '': # 사용자 앱에서는 내일 예약 불가능
                    tomorrow = now + dt.timedelta(days=1)
                    tomorrow = dt.datetime.strftime(tomorrow, '%Y%m%d')
                    if tomorrow in available_schedules:
                        del available_schedules[tomorrow]

            for day in available_schedules:
                print '[', day, ']'
                print available_schedules[day]['by_time']
            # log to mixpanel
            mix.track(uid, 'request available schedule', {'time' : dt.datetime.now(), 'taking_time' : taking_time, 'additional_time' : additional_time, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender,'isdirty' : isdirty})

            # log to mongo
            mongo_logger.debug('request available schedule', extra = {'log_time' : dt.datetime.now(),  'user_id' : uid, 'taking_time' : taking_time, 'additional_time' : additional_time, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender,'isdirty' : isdirty})

            if len(available_schedules) > 0: # 가능한 날짜가 있다면
                ret['response'] = {'schedule' : available_schedules, 'first_date' : available_schedules.keys()[0] }
            else:
                add_err_message_to_response(ret, err_dict['err_not_available'])

                mongo_logger.debug('no masters', extra = {'log_time' : dt.datetime.now(), 'user_id' : uid, 'taking_time' : total_taking_time_in_minutes, 'gu_id' : gu_id, 'address' : address})
                user_name = userdao.get_user_name(uid)
                user_phone = userdao.get_user_phone(uid)
                send_jandi('BOOKING_NOT_AVAILABE', '예약 불가능 알림', '고객 : {} 전번 : {}'.format(user_name, user_phone),
                            '주기 : {}, 주소 : {}'.format(appointment_type, address))

            self.set_status(Response.RESULT_OK)
        except Exception, e:
            add_err_message_to_response(ret, err_dict['err_mysql'])
            self.set_status(Response.RESULT_SERVERERROR)
            print_err_detail(e)
            mongo_logger.error('error request available schedules', extra = {'user_id' : uid, 'err' : str(e)})
예제 #14
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', '*')

        ret = {}

        uid                         = self.get_argument('uid', '')
        appointment_type            = self.get_argument('appointment_type', BC.ONE_TIME)
        taking_time                 = self.get_argument('taking_time', 25)
        first_added_time            = self.get_argument('first_added_time', 0)
        additional_time             = self.get_argument('additional_time', 10)
        have_pet                    = self.get_argument('have_pet', 0)
        master_gender               = self.get_argument('master_gender', 0)
        isdirty                     = self.get_argument('isdirty', 0)
        for_manager                 = self.get_argument('for_manager', '')

        # for address parameter
        address = self.get_argument('address', '')
        size    = self.get_argument('size', 25)
        kind    = self.get_argument('kind', 0)

        size = int(size)
        kind = int(kind)

        # convert parameters
        appointment_type                = int(appointment_type)
        taking_time                     = int(taking_time)
        first_added_time                = int(first_added_time)
        additional_time                 = int(additional_time)

        taking_time_in_minutes          = taking_time * 6
        first_added_time_in_minutes     = first_added_time * 6
        additional_time_in_minutes      = additional_time * 6
        total_taking_time_in_minutes    = taking_time_in_minutes + first_added_time_in_minutes + additional_time_in_minutes

        have_pet                        = int(have_pet)
        master_gender                   = int(master_gender) # 0 dont care 1 women
        isdirty                         = int(isdirty)


        # logging part
        mix = get_mixpanel()
        mongo_logger = get_mongo_logger()

        try:
            print uid
            if self.is_user_block(ret, uid) == True:
                return

            if appointment_type == BC.ONE_TIME_A_MONTH:
                self.set_status(Response.RESULT_OK)
                add_err_ko_message_to_response(ret, '4주 1회 서비스는 신규 예약을 지원하지 않습니다.')
                mongo_logger.debug('not booking one time a month', extra = { 'user_id' : uid })
                ret['err_code'] = '4038' # 임시 처리
                return

            if total_taking_time_in_minutes <= 0 or taking_time_in_minutes <= 0:
                self.set_status(Response.RESULT_OK)
                add_err_ko_message_to_response(ret, '클리닝 시간이 잘못 설정되었습니다.')
                ret['err_code'] = '9999' # 임시 처리
                return


            if total_taking_time_in_minutes >= 600:
                self.set_status(Response.RESULT_OK)
                add_err_ko_message_to_response(ret, '클리닝 가능 시간을 초과하였습니다. (최대 10시간) 이전 화면으로 돌아가 추가사항을 2개이하로 줄여주세요.')
                ret['err_code'] = '4036' # 임시 처리
                return

            scheduler = HMScheduler()

            session = Session()
            userdao = UserDAO()
            addrdao = AddressDAO()

            # add user address
            latlng = get_latlng_from_address(address)
            if len(latlng) > 1:
                latitude = latlng[0]
                longitude = latlng[1]

                geohash5 = get_geohash(latitude, longitude, 5)
                geohash6 = get_geohash(latitude, longitude, 6)
            else:
                latitude = 0.0
                longitude = 0.0
                geohash5 = ''
                geohash6 = ''

            key = userdao.get_user_salt_by_id(uid)[:16]
            crypto = aes.MyCrypto(key)

            encrypted_address = crypto.encodeAES(str(address))

            count = session.query(UserAddress).filter(UserAddress.user_id == uid).count()
            last_index = session.query(UserAddress).filter(UserAddress.user_id == uid).order_by(desc(UserAddress.user_addr_index)).first()

            index = 0
            if last_index != None:
                index = last_index.user_addr_index + 1

            new_address = UserAddress(user_id = uid, address = encrypted_address, size = size, kind = kind,
                                        user_addr_index = index, latitude = latitude, longitude = longitude,
                                        geohash5 = geohash5, geohash6 = geohash6)
            session.add(new_address)
            session.commit()

            # set default address index
            if count == 0:
                new_default_address = UserDefaultAddress(user_id=uid, address_idx=index)
                session.add(new_default_address)
            else:
                record = session.query(UserDefaultAddress).filter(UserDefaultAddress.user_id == uid).one()
                record.address_idx = index

            session.commit()

            address, geohash5, geohash6 = userdao.get_user_address(uid)
            _, size, kind = userdao.get_user_address_detail(uid)

            gu_id = addrdao.get_gu_id(address)

            if gu_id == '':
                raise Exception('gu id is incorrect')
                return

            available_schedules = scheduler.get_available_slots(gu_id = gu_id, geohash = geohash6, appointment_type = appointment_type, taking_time = total_taking_time_in_minutes,
                                                                prefer_women = True if master_gender == 1 else False,
                                                                have_pet = True if have_pet == 1 else False,
                                                                isdirty = True if isdirty == 1 else False,
                                                                user_id = uid)


            now = dt.datetime.now()
            if now.hour >= 17: # 7시 이후 라면 -> 5시로 변경 2016.06.03
                if for_manager == '': # 사용자 앱에서는 내일 예약 불가능
                    tomorrow = now + dt.timedelta(days=1)
                    tomorrow = dt.datetime.strftime(tomorrow, '%Y%m%d')
                    if tomorrow in available_schedules:
                        del available_schedules[tomorrow]

            for day in available_schedules:
                print '[', day, ']'
                print available_schedules[day]['by_time']
            # log to mixpanel
            mix.track(uid, 'request available schedule', {'time' : dt.datetime.now(), 'taking_time' : taking_time, 'additional_time' : additional_time, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender,'isdirty' : isdirty})

            # log to mongo
            mongo_logger.debug('request available schedule', extra = {'log_time' : dt.datetime.now(),  'user_id' : uid, 'taking_time' : taking_time, 'additional_time' : additional_time, 'appointment_type' : appointment_type, 'have_pet' : have_pet, 'master_gender' : master_gender,'isdirty' : isdirty})

            if len(available_schedules) > 0: # 가능한 날짜가 있다면
                ret['response'] = {'schedule' : available_schedules, 'first_date' : available_schedules.keys()[0] }
            else:
                add_err_message_to_response(ret, err_dict['err_not_available'])

                mongo_logger.debug('no masters', extra = {'log_time' : dt.datetime.now(), 'user_id' : uid, 'taking_time' : total_taking_time_in_minutes, 'gu_id' : gu_id, 'address' : address})
                user_name = userdao.get_user_name(uid)
                user_phone = userdao.get_user_phone(uid)
                send_jandi('BOOKING_NOT_AVAILABE', '예약 불가능 알림', '고객 : {} 전번 : {}'.format(user_name, user_phone),
                            '주기 : {}, 주소 : {}'.format(appointment_type, address))

            self.set_status(Response.RESULT_OK)
        except Exception, e:
            add_err_message_to_response(ret, err_dict['err_mysql'])
            self.set_status(Response.RESULT_SERVERERROR)
            print_err_detail(e)
            mongo_logger.error('error request available schedules', extra = {'user_id' : uid, 'err' : str(e)})
    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', '')
        no_fee = self.get_argument('no_fee', 0)

        reason_id = int(reason_id)

        print "reason_id : ", reason_id

        no_fee = int(no_fee)

        ret = {}

        mongo_logger = get_mongo_logger()
        mix = get_mixpanel()

        try:
            session = Session()

            try:
                row = 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.id == booking_id) \
                             .filter(Booking.cleaning_status == BC.BOOKING_UPCOMMING) \
                             .one()

            except NoResultFound, e:
                session.close()
                self.set_status(Response.RESULT_OK)
                add_err_message_to_response(ret,
                                            err_dict['err_no_entry_to_cancel'])
                return

            user_id = row.Booking.user_id

            masterdao = MasterDAO()
            userdao = UserDAO()
            key = userdao.get_user_salt_by_id(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))

            charge = 0
            new_status = BC.BOOKING_CANCELED_CHARGE

            request_id = row.Booking.request_id

            appointment_index = row.Booking.appointment_index
            appointment_time = row.Booking.start_time
            appointment_type = row.Booking.appointment_type
            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
            device_type = row.Booking.user_type
            now = dt.datetime.now()
            cancel_amount = 0

            diff_in_hours = (appointment_time - now).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

            if current_payment_status == BC.BOOKING_PAID:
                if no_fee == 1:  # 관리자가 선택하여 fee를 지불 할 수 있게 하기 위해서
                    charge = 0

                new_status = BC.BOOKING_CANCELED_REFUND

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

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

                is_event = True if is_event != None else False

                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, booking_id,
                                                       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
                    else:
                        # 결제 필요
                        # 취소에 대한 결제 필요
                        partial = '0'
                        cancel_amount = row.Booking.price_with_task - row.Booking.price
                        if cancel_amount > 0:
                            cancel_payment(user_id, booking_id, cancel_amount,
                                           partial)

                        complete_count = session.query(Booking) \
                                .filter(Booking.request_id == request_id) \
                                .filter(Booking.cleaning_status == 2) \
                                .count()

                        print complete_count, row.Booking.cleaning_status
                        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

            else:  # cancel charge price
                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,
                                                    booking_id, charging_price,
                                                    appointment_type)
                    if ret_code == False:
                        new_status = BC.BOOKING_PAYMENT_FAILED

            #row.Booking.modified_date   = now
            row.Booking.charging_price = int(charge)
            row.Booking.status = new_status
            row.Booking.cleaning_status = BC.BOOKING_CANCELED
            row.Booking.payment_status = new_status

            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_TEXT % (username, userphone, master_name, date)
            #print 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', username, date, appointment_type_text)

            cancel_reasons = []
            cancel_reasons.append('지금은 서비스가 필요하지 않아요')
            cancel_reasons.append('집에 없어서 문을 열어드릴 수가 없어요')
            cancel_reasons.append('시간이 마음에 들지 않아요')
            cancel_reasons.append('클리닝을 잊고 있었네요')
            cancel_reasons.append('원하는 홈마스터가 아니에요')
            cancel_reasons.append('기타')
            cancel_reasons.append('이사가요')
            cancel_reasons.append('기타')
            cancel_reasons.append('관리자가 취소 했습니다')

            cancel_reason = cancel_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...'

            master_pushkey = masterdao.get_master_pushkey(master_id)
            #master_name = masterdao.get_master_name(master_id)
            #master_phone   = masterdao.get_master_phone(master_id)

            send_booking_canceled('android', [master_pushkey], booking_id,
                                  date, username)

            content = '''{} 홈마스터님
예약이 1회 취소 되었습니다.

고객 : {}
주기 : {}
날짜 : {}'''.format(master_name, username, appointment_type_text, date)

            message_sender = MessageSender()
            message_sender.send([master_phone], '예약 1회 취소 알림', content)

            print 'master_pushkey', master_pushkey
            print booking_id, date

            #send_alimtalk(master_phone, 'noti_manager_cancel', username, date, appointment_type_text)
            # adjust appointment index
            index_result = session.query(Booking).filter(
                Booking.request_id == request_id).filter(
                    Booking.appointment_index > appointment_index).all()
            for index_row in index_result:
                index_row.appointment_index -= 1

            coupondao = CouponDAO()
            coupondao.cancel_coupon_usage(booking_id)

            CANCEL = 0
            cancel_reason = CancelReason(booking_id=booking_id,
                                         user_id=user_id,
                                         reason_id=reason_id,
                                         etc_reason=etc_reason,
                                         kind=CANCEL,
                                         cancel_time=dt.datetime.now())
            session.add(cancel_reason)

            session.commit()

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

            ret['response'] = Response.SUCCESS

            self.set_status(Response.RESULT_OK)
    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