def update_note_by_service_id_or_user_id(user_connected_model, user_connected_schema):
    """

    @return:
    """
    data, error = validate_data(user_stars_schema, request)
    if error:
        return custom_response(data, 400)

    if data.get('service_id'):
        stars_to_add_note = Stars.get_stars_by_service_id(data.get('service_id'))
        if not stars_to_add_note:
            custom_response("Service rate not found", 400)
        stars_ = user_stars_schema.dump(stars_to_add_note)
        update_note(stars_to_add_note, stars_, data, user_connected_model)
        return custom_response("success", 200)

    if data.get('user_id'):
        artist_to_note = User.get_one_user(data['user_id'])
        user_who_set_note = User.get_one_user(auth.user.get('id'))
        if not artist_to_note.user_type == user_who_set_note.user_type == USER_AUDITOR_PRO:
            stars_to_add_note = Stars.get_stars_by_user_id(data.get('user_id'))
            if not stars_to_add_note:
                custom_response("Service rate not found", 400)
            stars_ = user_stars_schema.dump(stars_to_add_note)
            update_note(stars_to_add_note, stars_, data, user_connected_model)
            return custom_response("success", 200)
        return custom_response("Unauthorized", 400)

    return custom_response("I need user_id or service_id", 400)
def send_prestige_email(user_connected_model,
                        user_connected_schema,
                        prestige,
                        beat_id=None,
                        service_id=None):
    """

    Args:
        prestige:
        beat_id:
        service_id:
        user_connected_model:
        user_connected_schema:
    """

    if prestige not in list(PRESTIGE_ALLOWED_TYPE):
        return custom_response("prestige type not found", 400)

    prestige = PRESTIGE_ALLOWED_TYPE[prestige]
    mail_data = dict(template="prestige.html")

    if beat_id:
        beat = Media.get_song_by_id(beat_id)
        if not beat:
            return custom_response("beat not found", 400)

        recipient = User.get_one_user(beat.user_id)
        mail_data.update(dict(beat_title=beat.title))

    else:
        service = Services.get_by_service_id(service_id)
        if not service:
            return custom_response("service not found", 400)

        recipient = User.get_one_user(service.user_id)
        mail_data.update(dict(service_title=service.title))

    if user_connected_model.email == recipient.email:
        return custom_response('Unauthorized', 400)

    data = prestige_data(
        sender_id=user_connected_model.id,
        recipient_id=recipient.id,
        service_id=service_id,
        prestige=prestige,
        beat_id=beat_id,
    )
    mail_data.update(
        dict(reference=data['key_share'],
             sender_name=user_connected_model.name,
             sender_email=user_connected_model.email,
             recipient_email=recipient.email,
             prestige=prestige))
    Prestige(data).save()
    send_prestige(**mail_data)

    return custom_response("success", 200)
 def decorated_auth(*args, **kwargs):
     """ auth required decoration """
     try:
         socket.create_connection(
             (socket.gethostbyname("www.google.com"), 80), 2)
     except OSError:
         return custom_response("Connection error", 404)
     if RevokedTokenModel.is_jti_blacklisted(
             request.headers.get('Isl-Token')):
         return custom_response('You Are logout, reconnect you please',
                                400)
     if 'Isl_Token' not in request.headers:
         return custom_response(
             'Authentication token is not available, please login to get one',
             400)
     token = request.headers.get('Isl-Token')
     data = Auth.decode_token(token)
     try:
         if data.status_code == 400:
             return custom_response('token invalid', 400)
     except AttributeError:
         user_id = data['data']['user_id']
         check_user = User.get_one_user(user_id)
         if not check_user:
             return custom_response('token invalid', 400)
         auth.user = {'id': user_id}
         kwargs['user_connected_model'] = check_user
         kwargs['user_connected_schema'] = UserSchema().dump(check_user)
         return func(*args, **kwargs)
def check_artist_condition_global(user_id):

    user = User.get_one_user(user_id)
    if user and user.condition_globals:
        return custom_response(
            condition_globals_schema.dump(user.condition_globals[0]), 200)
    return custom_response("user or user condition global not found", 400)
Beispiel #5
0
def create_a_new_reservation(user_connected_model, user_connected_schema):
    """ """

    data, error = validate_data(reservation_schema, request)
    if error:
        return custom_response(data, 400)

    payment_reference = random_string(20)
    stripe.api_key = "sk_test_SnQS9gn3p2TRP7lrkjkpM5LN007eNS7Izg"
    artist_amount, total_tva, isl_amount = check_price_details(ht_price=data["total_amount"])
    total_amount = float(isl_amount + total_tva + artist_amount)

    payment_history_obj = {
        "paid": False,
        "tva": total_tva,
        "name": data["name"],
        "email": data["email"],
        "city": data["city"],
        "postal_code": data["postal_code"],
        "phone": data["phone"],
        'address': data["address"],
        'type': KANTOBIZ,
        'buyer_id': user_connected_model.id,
        'artist_id': data["artist_owner_id"],
        'reference': payment_reference,
        'isl_amount': isl_amount,
        'artist_amount': artist_amount,
        'ip_address': None,
        'total_amount': total_amount
    }

    payment_history_to_save = PaymentHistory(payment_history_obj)
    payment_history_to_save.save()

    artist = User.get_one_user(data["artist_owner_id"])
    data["artist_email"] = artist.email

    # payment = payment_stripe(total_amount, data['stripe_token']['id'], "Purchase Service KantoBiz")

    if data["email"] != user_connected_schema["email"]:
        data["auditor_email"] = user_connected_schema["email"]

    # if payment.paid:
    new_reservation = Reservations({
        "event": data["event"],
        "status": PENDING,
        "address": data["address"],
        "total_amount": total_amount,
        "event_date": data["event_date"],
        "services_id": data["services_id"],
        "artist_owner_id": data["artist_owner_id"],
        "options_id_list": data["options_id_list"],
        "payment_history_id": payment_history_to_save.id,
        "auditor_who_reserve_id": user_connected_model.id,
        "refund_policy": artist.condition_globals[0].refund_policy
    })
    new_reservation.save()
    payment_success_send_email({"user_data": data}, payment_reference, total_amount, total_tva)
    return custom_response(reservation_basic_schema.dump(new_reservation), 200)
def show_profile(user_connected_model, user_connected_schema):
    """ Get my Profile """

    profile = user_connected_model.profile or Profiles.get_profile(
        social_id=user_connected_model.social_id)

    user_condition_globals, reservation_booking_list, reservation_list, notes = {}, [], [], 0.00
    if user_connected_model.user_type != USER_AUDITOR_PRO:
        user_condition_globals = condition_globals_schema.dump(
            user_connected_model.condition_globals[0])
        user_reservation_list = user_connected_model.reservation_list.all()
        if user_reservation_list:
            reservation_list = [
                check_reservation_info_with_service_info(
                    reservation_basic_schema, Services, User, r)
                for r in user_reservation_list
            ]
    else:
        notes = mean(
            User.get_one_user(user_connected_model.id).stars[0].note or [0])

    user_booking_list = user_connected_model.booking_list.all()
    if user_booking_list:
        reservation_booking_list = [
            check_reservation_info_with_service_info(reservation_basic_schema,
                                                     Services, User, r)
            for r in user_booking_list
        ]

    user_banking = user_connected_model.banking
    if user_banking:
        user_banking = banking_schema.dump(user_banking[0])

    return custom_response(
        {
            "notes":
            notes,
            "role":
            user_connected_model.user_type,
            "my_followings":
            user_connected_model.all_admires.count(),
            "my_followers":
            user_connected_model.my_admirers.count(),
            "my_profile":
            profile_schema.dump(profile),
            "conditions":
            user_condition_globals,
            "banking":
            user_banking or {},
            "reservations_list":
            reservation_list,
            "reservations_booking_list":
            reservation_booking_list,
            "payment_history":
            check_all_user_payment_history(user_connected_model,
                                           payment_history_schema, User,
                                           Reservations),
        }, 200)
Beispiel #7
0
def auditor_decline_reservation(reservation_id, user_connected_model, user_connected_schema):
    """

    Args:
        reservation_id:
        user_connected_model:
        user_connected_schema:

    Returns:

    """

    user_reservation = user_connected_model.booking_list.filter_by(id=reservation_id).first()

    if user_reservation:
        reservation_s = reservation_basic_schema.dump(user_reservation)

        if reservation_s["status"] == DECLINED:
            return custom_response("already declined", 400)

        if reservation_s["status"] == ACCEPTED:
            service_s = service_schema.dump(user_reservation.service)
            artist = User.get_one_user(service_s["user_id"])
            payment_history_0bj = payment_history_schema.dump(user_reservation.payment_history)
            reference = payment_history_0bj["reference"]

            data = {
                "service": service_s,
                "refunded": 0.00,
                "date": month + " " + day + ", " + year,
                "auditor": user_connected_schema,
                "reservation": reservation_s,
                "artist_name": artist.name,
                "artist_email": artist.email,
                "invoicing_address": payment_history_0bj
            }

            # do not forget refund
            reservation_s["invoice"] = canceled_by_auditor_after_accept(
                "CanceledByAuditorAfterAccept.html", data=data, reference=reference,
                user_type="customer", email=payment_history_0bj["email"], user_connected=user_connected_schema)

            canceled_by_auditor_after_accept(
                "CanceledByAuditorAfterAccept.html", data=data, reference=reference,
                user_type="artist", email=artist.email)

            reservation_s["status"] = DECLINED
            payment_history_0bj["refund"] = True
            user_reservation.payment_history.update(payment_history_0bj)
            user_reservation.update(reservation_s)
            return custom_response_after_update(user_connected_model, user_reservation)

        reservation_s["status"] = DECLINED
        user_reservation.update(reservation_s)
        return custom_response_after_update(user_connected_model, user_reservation)

    return custom_response("reservation not found", 404)
Beispiel #8
0
def artist_decline_reservation(reservation_id, user_connected_model, user_connected_schema):
    """

    Args:
        reservation_id:
        user_connected_model:
        user_connected_schema:

    Returns:

    """

    user_reservation = user_connected_model.reservation_list.filter_by(id=reservation_id).first()
    if user_reservation:
        reservation_s = reservation_basic_schema.dump(user_reservation)

        if reservation_s["status"] == DECLINED:
            return custom_response("already declined", 400)

        if reservation_s["status"] == ACCEPTED:
            # refund
            service_s = service_schema.dump(user_reservation.service)
            payment_history_0bj = payment_history_schema.dump(user_reservation.payment_history)
            reference = payment_history_0bj["reference"]

            data = {
                "service": service_s,
                "date": month + " " + day + ", " + year,
                "auditor": user_schema.dump(User.get_one_user(reservation_s["auditor_who_reserve_id"])),
                "reservation": reservation_s,
                "artist_name": user_connected_model.name,
                "artist_email": user_connected_model.email,
                "invoicing_address": payment_history_0bj
            }

            invoice = canceled_reservation_by_artist(
                "PaymentRefundByArtistRefused.html", data=data, reference=reference,
                user_type="customer", email=payment_history_0bj["email"], user_connected=user_connected_schema)

            canceled_reservation_by_artist(
                "PaymentRefundByArtistRefused.html", data=data, reference=reference,
                user_type="artist", email=user_connected_model.email)

            reservation_s["status"] = DECLINED
            reservation_s["invoice"] = invoice
            user_reservation.update(reservation_s)
            payment_history_0bj["refund"] = True
            user_reservation.payment_history.update(payment_history_0bj)
            return custom_response_after_update(user_connected_model, user_reservation)

        reservation_s["status"] = DECLINED
        user_reservation.update(reservation_s)
        return custom_response(
            check_reservation_info_with_service_info(reservation_basic_schema, Services, User, user_reservation, True
                                                     ), 200)
    return custom_response("reservation not found", 404)
Beispiel #9
0
def search_user_service_by_id(service_id):
    service_checked = Services.get_by_service_id(service_id)

    if not service_checked:
        return custom_response("service not found", 400)

    service_checked = service_schema.dump(service_checked)
    material_id = service_checked["materials_id"]
    service_checked["materials"] = material_schema.dump(
        Materials.get_by_materials_id(material_id))
    service_checked["artist_name"] = User.get_one_user(
        service_checked["user_id"]).name
    service_checked["notes"] = check_service_stars(service_checked["id"])
    _options = User.get_one_user(service_checked["user_id"]).options.all()
    service_checked["options"] = []
    for option in _options:
        if service_checked["id"] in option.services_id_list:
            service_checked["options"].append(option_schema.dump(option))

    return custom_response({"service": service_checked}, 200)
def all_user_admiration(user_id):
    """ get all user admiration """

    user = User.get_one_user(user_id)
    if not user:
        return custom_response("user do not exist", 400)

    all_users = {"all_admire": [], "my_admirers": []}
    all_admiration = user.all_admires.all()
    all_admirers = user.my_admirers.all()

    for admire in all_admiration:
        u_pr = profile_schema.dump(User.get_one_user(admire.admire_id).profile)
        all_users['all_admire'].append(
            check_dict_keys(u_pr, _keys=profile_keys_to_remove, inverse=True))

    for admire in all_admirers:
        u_pr = profile_schema.dump(User.get_one_user(admire.admire_id).profile)
        all_users['my_admirers'].append(
            check_dict_keys(u_pr, _keys=profile_keys_to_remove, inverse=True))

    return custom_response(all_users, 200)
def all_beats_admiration(user_id):
    """ get all beats user admiration """

    user = User.get_one_user(user_id)
    if not user:
        return custom_response("user do not exist", 400)

    all_beats = []
    all_admiration = user.all_admires.filter_by(admire_id=None).all()

    for admire in all_admiration:
        _beat = media_schema.dump(admire.beat)
        all_beats.append(_beat)

    return custom_response(all_beats, 200)
def add_others_information_to_list_of_service(all_indexed_data):
    new_list_of_all_indexed_data = []
    for service in all_indexed_data:
        material = es.search(
            index="materials",
            body={
                "query": {
                    "bool": {
                        "must": [{
                            "match": {
                                "id": service["materials_id"]
                            }
                        }]
                    }
                }}
        )
        option = es.search(
            index="options",
            body={
                "query": {
                    "bool": {
                        "must": [{
                            "match": {
                                "user_id": service["user_id"]
                            }
                        }],
                        "filter": {
                            "query_string": {
                                "fields": ["services_id_list"],
                                "query": service["id"]
                            }
                        }}
                }
            }
        )

        service["materials"] = material['hits']['hits'][0]["_source"]
        service["artist_name"] = User.get_one_user(service["user_id"]).name
        service["notes"] = check_service_stars(service["id"])
        service["options"] = [d["_source"] for d in option['hits']['hits']]
        new_list_of_all_indexed_data.append(service)

    return sorted(new_list_of_all_indexed_data, key=itemgetter('price'))
def add_new_admiration_user(artist_to_admire_id, user_connected_model,
                            user_connected_schema):
    """ User add new admiration """

    if not User.get_one_user(artist_to_admire_id):
        return custom_response("User not found", 400)

    if artist_to_admire_id is not user_connected_model.id:
        admire_info = user_connected_model.all_admires.filter_by(
            admire_id=artist_to_admire_id).first()

        if admire_info:
            return custom_response("exist", 400)

        Admiration(
            dict(user_id=user_connected_model.id,
                 admire_id=artist_to_admire_id)).save()
        return custom_response("Added", 200)

    return custom_response("Unauthorized", 400)
    def validator():
        """ check if user data is in request """

        data = request.get_json()
        if not data.get("stripe_token"):
            return custom_response("no token stripe", 400)
        if not data.get("MyCarts"):
            return custom_response("send me the carts with key 'MyCarts'", 400)
        if not data.get("user_data"):
            return custom_response(
                "send me the user information with key 'user_data'", 400)
        if not data["user_data"].get("name"):
            return custom_response("i need name in user information", 400)
        if not data["user_data"].get("email"):
            return custom_response("i need email in user information", 400)
        if not data["user_data"].get("address"):
            return custom_response("i need address in user information", 400)
        if not data["user_data"].get("city"):
            return custom_response("i need city in user information", 400)
        if not data["user_data"].get("postal_code"):
            return custom_response("i need postal_code in user information",
                                   400)

        if data['user_data'].get('phone'):
            data['user_data']['phone'] = int(data['user_data'].get('phone'))
        else:
            data['user_data']['phone'] = None

        token = request.headers.get('Isl-Token')
        if token:
            data_ = Auth.decode_token(token)
            try:
                if data_.status_code == 400:
                    data["user_data"]["user_id"] = None
            except AttributeError:
                user_id = data_['data']['user_id']
                check_user = User.get_one_user(user_id)
                if not check_user:
                    data["user_data"]["user_id"] = None

        return func(data)
def get_top_beat_maker(listed=False):
    """ get top beatmakers """

    top_beats = get_top_beats(listed=True)
    top_beat_maker = []

    for beat in top_beats:
        user = User.get_one_user(beat['user_id'])
        beat_maker_profile = profile_schema.dump(user.profile)
        beat_maker_profile = check_dict_keys(beat_maker_profile,
                                             _keys=profile_keys_to_remove,
                                             inverse=True)
        beat_maker_profile['number_of_beats'] = user.medias.count()

        if beat_maker_profile not in top_beat_maker:
            top_beat_maker.append(beat_maker_profile)

    if listed:
        return top_beat_maker

    return custom_response({"top_beatmaker": top_beat_maker}, 200)
def search_beats_and_artist(string_to_search):
    """ search matching with text_ in table medias """

    beats_and_artist = es.search(
        index="beats",
        doc_type="songs",
        body={
            "from": 0,
            "size": 10,
            "query": {
                "query_string": {
                    "fields":
                    ["title", "artist", "genre", "artist_tag", "description"],
                    "query":
                    "*" + string_to_search + "*"
                }
            },
            # "sort": [{"listened": {"order": "asc", "mode": "min"}}]
        })

    data = {'beats': [], 'artists': []}
    for r in beats_and_artist['hits']['hits']:
        data['beats'].append(r['_source'])

        artist_profile = profile_schema.dump(
            User.get_one_user(r['_source']['user_id']).profile)
        keys_to_remove = [
            'address', 'age', 'city', 'region', 'social_id', 'photo', 'email',
            'cover_photo', 'photo'
        ]
        artist_profile = check_dict_keys(artist_profile,
                                         _keys=keys_to_remove,
                                         inverse=True)
        if artist_profile not in data['artists']:
            data['artists'].append(artist_profile)

    return custom_response(data, 200)
 def get_user_data_by_token(self, token):
     data = Auth.decode_token(token)
     self.assertEqual(type(data), dict)
     with self._app.app_context():
         user = User.get_one_user(data['data']["user_id"])
     return user