def find_message_for_id_or_raise(message_id): try: return WorkshopMessage.objects.get(id=message_id) except WorkshopMessage.DoesNotExist as e: logger.error('No workshop message found for ID: {}, err: {}'.format( message_id, str(e))) raise WorkshopMessageNotFoundException(message_id)
def find_workshop_for_id_or_raise(workshop_id): try: return Workshop.objects.get(id=workshop_id) except Workshop.DoesNotExist as e: logger.error('No workshops found for ID: {}, err: {}'.format( workshop_id, str(e))) raise WorkshopNotFoundException(workshop_id)
def _check_if_user_is_author_of_message_or_workshop_mentor(message, user): author = message.author mentors = message.workshop.mentors.all() if (user != author) and (user not in mentors): logger.error('User with ID: {} tried to delete message with ID: {}'.format(user.id, message.id)) raise WorkshopIllegalAccessException('Only mentor or author can delete workshop message')
def __find_reset_password_attempt(token): try: return ResetPassword.objects.get(token=token, active=True) except ResetPassword.DoesNotExist: logger.error( 'Failed to find reset password record for token: {}'.format(token)) raise ResetPasswordNotFoundException()
def _find_user_for_email(email): try: return User.objects.get(username=email) except User.DoesNotExist as e: logger.error('No user found for email: {}, err: {}.'.format( email, str(e))) raise LoginFailedException()
def _find_promo_code_for_id_or_raise(promo_code_id): try: return PromoCode.objects.get(code=promo_code_id) except PromoCode.DoesNotExist as e: logger.error('Promo code for ID: {} not found, err: {}'.format( promo_code_id, str(e))) raise PromoCodeNotFoundException(promo_code_id)
def _check_if_user_has_purchase(user): try: p = Purchase.objects.get(user=user) logger.error('User: {} already has purchase: {}'.format(user.id, p.id)) raise UserAlreadyHasPurchaseException(user.id, p.id) except Purchase.DoesNotExist: pass
def _check_if_product_is_active(product): price_tier = product.price_tier now = timezone.now() date_from = price_tier.date_from date_to = price_tier.date_to if not (date_from < now < date_to): logger.error('Product for ID: {} is not active, from: {}, to: {}'.format(product.id, date_from, date_to)) raise ProductInactiveException(product.id)
def check_if_user_is_workshop_mentor_or_attendee(workshop, user): if (user not in workshop.attendees.all()) and ( user not in workshop.mentors.all()): logger.error( 'User with ID: {} tried to access workshop with ID: {} illegally.'. format(user.id, workshop.id)) raise WorkshopIllegalAccessException( 'Only mentors and attendees are allowed to access workshop data')
def rebuild_workshops_full_text_search(): logger.info('Updating workshop full-text search index.') try: rebuild_index.Command().handle(using=['default'], verbosity=2, remove=True, noinput=True) except Exception as e: logger.error('Caught exception while updating workshop index: %s' % e) return None
def __is_100_discount_promo_code(code): if code is None: return False try: promo_code = PromoCode.objects.get(code=code) return promo_code.discount == 100 except PromoCode.DoesNotExist as e: logger.error('Promo code for code: {} not found, err: {}'.format(code, e)) return False
def validate_payload_with_schema(payload, schema): """ Needed because of: https://github.com/tomchristie/django-rest-framework/issues/2556 When empty request comes it's not parsed. """ try: jsonschema.validate(payload, schema) return payload except ValidationError as e: logger.error('Caught JSON schema validation error: {}.'.format(str(e))) raise ParseException(str(e), 400)
def __check_if_user_already_signed_for_workshop_in_current_slot_tier(user, workshop): user_timeslots = __get_user_timeslots(user) user_tiers = __get_timeslot_tiers(user_timeslots) workshop_timeslots = __get_workshop_timeslots(workshop) workshop_tiers = __get_timeslot_tiers(workshop_timeslots) intersection = user_tiers.intersection(workshop_tiers) if intersection: msg = 'User with ID: {}, is already registered for workshop in tier(s): {}.'.format(user.id, intersection) logger.error(msg) raise UserAlreadySignedForWorkshopInTierException(msg)
def custom_exception_handler(exc): logger.error('Exception caught: {}, error: {}.'.format(type(exc).__name__, exc)) status_code = _find_code_for_exception(exc) response = Response(status=status_code, data={ 'detail': (hasattr(exc, 'detail') and exc.detail) or (hasattr(exc, 'message') and exc.message) or 'No detail', 'code': (hasattr(exc, 'code')) and exc.code or 0 }) return response
def custom_exception_handler(exc): logger.error('Exception caught: {}, error: {}.'.format( type(exc).__name__, exc)) status_code = _find_code_for_exception(exc) response = Response(status=status_code, data={ 'detail': (hasattr(exc, 'detail') and exc.detail) or (hasattr(exc, 'message') and exc.message) or 'No detail', 'code': (hasattr(exc, 'code')) and exc.code or 0 }) return response
def __check_if_user_has_successful_purchase(user, workshop_id): try: return Purchase.objects.get(user=user, payment_status=PaymentStatusName.SUCCESS.value) except Purchase.DoesNotExist as e: logger.error( 'No purchase found for user with ID: {} when signing for workshop with ID: {}, err: {}'.format( user.id, workshop_id, str(e)) ) try: purchase = Purchase.objects.get(user=user) logger.info('User with ID: {} has purchase with ID: {}, status: {}, payment type: {}'.format( user.id, purchase.id, purchase.payment_status, purchase.payment_type) ) except Purchase.DoesNotExist: pass raise WorkshopWithoutPurchaseSignAttemptException(user.id)
def __raise_mutually_exclusive_tiers_exceptions(user, workshop, user_tiers_ids, workshop_tiers_ids): logger.error( 'User with ID: {} cannot sign for workshop with ID: {}. Mutually exclusive tiers, users: {}, workshops :{}.' .format(user.id, workshop.id, user_tiers_ids, workshop_tiers_ids) ) raise MutuallyExclusiveTiersException()
def __find_reset_password_attempt(token): try: return ResetPassword.objects.get(token=token, active=True) except ResetPassword.DoesNotExist: logger.error('Failed to find reset password record for token: {}'.format(token)) raise ResetPasswordNotFoundException()
def find_message_for_id_or_raise(message_id): try: return WorkshopMessage.objects.get(id=message_id) except WorkshopMessage.DoesNotExist as e: logger.error('No workshop message found for ID: {}, err: {}'.format(message_id, str(e))) raise WorkshopMessageNotFoundException(message_id)
def _check_password(email, query_password, db_password): if not check_password(query_password, db_password): logger.error( 'Password verification failed for user with email: {}.'.format( email)) raise LoginFailedException()
def __find_user_auth_for_email(email): try: return User.objects.get(email=email.lower()) except User.DoesNotExist: logger.error('No user found for email: {}'.format(email)) return None
def _check_if_user_is_workshop_mentor(workshop, user): if user not in workshop.mentors.all(): logger.error( 'User with ID: {} tried to access attendees list for workshop with ID: {}'.format(user.id, workshop.id)) raise WorkshopIllegalAccessException('Only mentors are allowed to access workshop attendees list')
def _compare_ids_and_raise_exception_if_different(endpoint_id, user_id): if str(endpoint_id) != str(user_id): logger.error('Id does not match: %s and: %s' % (endpoint_id, user_id)) raise InvalidUserIdException()
def e(msg): logger.error(msg)
def _find_promo_code_for_id_or_raise(promo_code_id): try: return PromoCode.objects.get(code=promo_code_id) except PromoCode.DoesNotExist as e: logger.error('Promo code for ID: {} not found, err: {}'.format(promo_code_id, str(e))) raise PromoCodeNotFoundException(promo_code_id)
def e(msg): logger.error(msg)
def check_if_user_is_workshop_mentor_or_attendee(workshop, user): if (user not in workshop.attendees.all()) and (user not in workshop.mentors.all()): logger.error('User with ID: {} tried to access workshop with ID: {} illegally.'.format(user.id, workshop.id)) raise WorkshopIllegalAccessException('Only mentors and attendees are allowed to access workshop data')
def _find_user_for_email(email): try: return User.objects.get(username=email) except User.DoesNotExist as e: logger.error('No user found for email: {}, err: {}.'.format(email, str(e))) raise LoginFailedException()
def _check_password(email, query_password, db_password): if not check_password(query_password, db_password): logger.error('Password verification failed for user with email: {}.'.format(email)) raise LoginFailedException()
def __find_user_auth_for_email(email): try: return User.objects.get(email=email.lower()) except User.DoesNotExist: logger.error('No user found for email: {}'.format(email)) return None
def _find_promo_code_or_raise(code): try: return PromoCode.objects.get(code=code) except PromoCode.DoesNotExist as e: logger.error('Promo code for code: {} not found, err: {}'.format(code, e)) raise PromoCodeForPurchaseNotFoundException(code)
def _check_if_promo_code_is_active(promo_code): if not promo_code.active: logger.error('Promo code: {} is not active'.format(promo_code.code)) raise PromoCodeForPurchaseNotActiveException(promo_code.code)
def __find_user_for_email(email): try: return User.objects.get(email=email.lower()) except User.DoesNotExist: logger.error('No auth found for email: {}'.format(email, )) raise UserNotFoundForPasswordResetException()
def _check_if_promo_code_has_valid_usage_limit(promo_code): if not promo_code.usage_limit > 0: logger.error('Promo code: {} has exceeded usage limit'.format(promo_code.code)) raise PromoCodeForPurchaseHasExceededUsageLimit(promo_code.code)
def generate_and_send_invoice(): logger.info('Generating and sending invoices.') unsent_invoices = PurchaseInvoice.objects.filter( sent=False, purchase__payment_status=PaymentStatusName.SUCCESS.value, purchase__confirmation_sent=True ) logger.info('Found: {} unsent invoices.'.format(unsent_invoices.count())) for invoice in unsent_invoices: with transaction.atomic(): try: purchase = invoice.purchase logger.info('Generating invoice for purchase: {}'.format(purchase.id)) client = iFirmaClient( invoice.name, invoice.tax_id, iFirmaAddress( invoice.city, invoice.zip_code, invoice.street, invoice.country, ) ) position = iFirmaItem( VAT.VAT_23, 1, float("{0:.2f}".format(purchase.price_total / 100.0)), u"Bilet wstępu na warsztaty codepot.pl: {}".format(purchase.id), "szt." ) ifirma_invoice = iFirmaInvoiceParams(client, [position]) (ifirma_invoice_id, ifirma_invoice_no) = _ifirma_client.generate_invoice(ifirma_invoice) ifirma_invoice_pdf = _ifirma_client.get_invoice_pdf(ifirma_invoice_id) invoice.ifirma_id = ifirma_invoice_id send_mail( [purchase.user.email], 'Payment completed [{}]'.format(purchase.id), get_rendered_template( 'mail/purchase/invoice.txt', {'name': purchase.user.first_name, 'purchase_id': purchase.id} ), get_rendered_template( 'mail/purchase/invoice.html', {'name': purchase.user.first_name, 'purchase_id': purchase.id} ), ['*****@*****.**'], ('{}.pdf'.format(ifirma_invoice_no), ifirma_invoice_pdf.getvalue(), 'application/pdf') ) invoice.no = ifirma_invoice_no invoice.sent = True invoice.save() except Exception as e: logger.error('Error while generating invoice for purchase: {}, err: {}.'.format(purchase.id, str(e))) continue
def __find_user_for_email(email): try: return User.objects.get(email=email.lower()) except User.DoesNotExist: logger.error('No auth found for email: {}'.format(email, )) raise UserNotFoundForPasswordResetException()
def log_and_raise(message, exc_class): logger.error(message) raise exc_class(message)
def find_workshop_for_id_or_raise(workshop_id): try: return Workshop.objects.get(id=workshop_id) except Workshop.DoesNotExist as e: logger.error('No workshops found for ID: {}, err: {}'.format(workshop_id, str(e))) raise WorkshopNotFoundException(workshop_id)
def _find_purchase_for_user_or_raise(user): try: return Purchase.objects.get(user=user) except Purchase.DoesNotExist as e: logger.error('No purchase found for user with ID: {}, err: {}'.format(user.id, str(e))) raise UserPurchaseNotFoundException(user.id)
def _find_product_or_raise(product_id): try: return Product.objects.get(id=product_id) except Product.DoesNotExist as e: logger.error('Product for ID: {} not found, err: {}'.format(product_id, e)) raise ProductNotFoundException(product_id)