def get_verification_token(self): if get_current_time( ).minute > self.verification_token_time.minute + VERIFICATION_TOKEN_EXPIRATION_TIME: self.verification_token = uuid.uuid4() self.verification_token_time = get_current_time() self.save() return self.verification_token
def is_unexpired(self): if get_current_time( ).minute <= self.connected_date.minute + SESSION_EXPIRATION_TIME: return True self.is_expired = True self.disconnected_date = get_current_time() self.save() return False
def get_verification_token(self): exp_day, exp_hour, exp_min, exp_sec = VERIFICATION_TOKEN_EXPIRATION_TIME if get_current_time() > self.verification_token_time + timedelta(days=exp_day, hours=exp_hour, minutes=exp_min, seconds=exp_sec): self.verification_token = uuid.uuid4() self.verification_token_time = get_current_time() self.save() return self.verification_token
def is_unexpired(self): exp_day, exp_hour, exp_min, exp_sec = SESSION_EXPIRATION_TIME if self.is_expired: return False if get_current_time() <= self.connected_date + timedelta(days=exp_day, hours=exp_hour, minutes=exp_min, seconds=exp_sec): return True self.is_expired = True self.disconnected_date = get_current_time() self.save() return False
def post(self, request, public_id=None): data = TicketCreateSerializer(data=request.data) if data.is_valid(): payment = Payment.objects.filter( public_id=data.validated_data.get("payment_id")).first() if payment: if payment.user != request.user: raise UserDoesNotHavePayment() if not data.validated_data.get("is_ok"): payment.delete() payment.event.available_places = payment.event.available_places + payment.quantity payment.event.save() return response() event = payment.event if payment.is_expired: raise PaymentExpired() payment.end_time = get_current_time() payment.is_expired = True payment.refund_id = data.validated_data.get("refund_id") payment.save() else: raise PaymentNotFound result = [] email_result = [] for i in range(0, payment.quantity): ticket = Ticket.objects.create(user=request.user, event=event, is_vip=payment.is_vip) result.append(ticket.public_id) email_result.append(ticket) send_celery_email('Bought Tickets', request.user.email, settings.TICKET_TEMPLATE, email_result) return response(data=result) raise ValidationError( error_list=error_many_list_serializer(data.errors))
def delete(self, request): user = request.user if user.is_company: events = Event.objects.filter(host=user, is_responsible=False, end_date__lt=get_current_time()) if events and Ticket.objects.filter(event__in=events): raise CannotDeleteUserHavingEvents() events = Event.objects.filter(host=user, is_responsible=True, all_user_payments_refunded=False) if events and Ticket.objects.filter(event__in=events): for i in events: try: refund_all_event_users(i) except NoPaymentIsMade as e: pass except StripeError() as e: raise e i.all_user_payments_refunded = True events = Event.objects.filter(host=user) for i in events: i.delete() Session.expire_all_sessions(user=request.user) user.is_active = False user.save() return response()
def post(self, request, public_id=None): data = EventCreateSerializer(data=request.data) if data.is_valid(): if data.validated_data.get('ticket_fee') == 0: try: charge = stripe.Charge.create( amount=settings.FREE_EVENT_CHARGE, currency="amd", source=request.user.stripe_id) except Exception as e: raise StripeError() event = data.create(data.validated_data) event.host = request.user event.available_places = event.ticket_amount event.save() if event.ticket_fee == 0: Payment.objects.create(end_time=get_current_time(), amount=settings.FREE_EVENT_CHARGE, event=event, user=request.user, reason=1, refund_id=charge['id']) return response(data=event.serialize(extra_info=True)) # errors.update(data.errors) raise ValidationError( error_list=error_many_list_serializer(data.errors))
def send_subscription_emails(): exp_day, exp_hour, exp_min, exp_sec = settings.CELERY_TASK_INTERVAL subscribers = Subscriber.objects.all() amount_of_events = 100 events_array = [] j=1 user = None for i in subscribers: try: user = CustomUser.objects.get(email=i.email) except CustomUser.DoesNotExist or CustomUser.MultipleObjectsReturned: user = None print(i) # print(i.last_subscription_email_date) # print(get_current_time()) # print(timedelta(days=exp_day, hours=exp_hour, minutes=exp_min, seconds=exp_sec)) # print(bool(i.last_subscription_email_date > get_current_time() + timedelta(days=exp_day, # hours=exp_hour, # minutes=exp_min, # seconds=exp_sec))) if i.last_subscription_email_date < get_current_time() + timedelta(days=exp_day, hours=exp_hour, minutes=exp_min, seconds=exp_sec): # print("Get into first if") if user: if user.categories: event_data = Event.objects.filter(categories__in = user.categories.all()) if user.address: events_data = events_data.filter(address__city__in =user.address.city, address__state__in = user.address.state) elif not user or not events_data or events_data.count()<4: events_data = Event.objects.all() amount_of_events = events_data.count() if events_data.count()<100 else 100 events_data = events_data.order_by('-creation_date') if j*4 > amount_of_events/4: j = 1 events_array = [m.serialize() for m in events_data[(j-1)*4: j*4]] # print(events_array) # print(j) # print(amount_of_events) send_email('Updates', i.email, settings.SUBSCRIBE_TEMPLATE, events_array) i.last_subscription_email_date = get_current_time() i.amount_of_subscription_emails = i.amount_of_subscription_emails + 1 i.save() j += 1 return True
def get_ot_token(self): exp_day, exp_hour, exp_min, exp_sec = OT_TOKEN_EXPIRATION_TIME if get_current_time() > self.ot_token_date + timedelta(days=exp_day, hours=exp_hour, minutes=exp_min, seconds=exp_sec): self.generate_ot_token() return self.ot_token
def generate_ot_token(self): self.ot_token = generate_int_token() self.ot_token_date = get_current_time() try: self.save() except IntegrityError: self.generate_ot_token() return self.ot_token
def post(self, request): data = PaymentSerializer(data=request.data) if data.is_valid(): event = Event.objects.filter( public_id=data.validated_data.get("public_id")).first() if not event: raise EventNotFound if event.ticket_fee == 0: raise UserPermission if event.available_places < data.validated_data.get('quant'): raise NoAvailablePlaces() if event.end_date < get_current_time(): raise CannotPayForPassedEvent() event.available_places = event.available_places - data.validated_data.get( 'quant') event.save() amount = data.validated_data.get('quant')*event.ticket_fee if not data.validated_data.get('is_vip') \ else data.validated_data.get('quant')*event.vip_ticket_fee if not event.is_responsible: try: payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=amount * 100, currency='amd', application_fee_amount=100 * amount * settings.CHARGE_PERCENTAGE / 100, stripe_account=event.host.stripe_id, receipt_email=settings.EMAIL_HOST_USER) except Exception as e: raise StripeError() else: try: payment_intent = stripe.PaymentIntent.create( payment_method_types=['card'], amount=amount * 100, currency='amd', receipt_email=settings.EMAIL_HOST_USER) except Exception as e: raise StripeError() payment = Payment.objects.create( amount=amount, quantity=data.validated_data.get('quant'), is_vip=data.validated_data.get('is_vip'), user=request.user, event=event) return response( data={ "client_secret": payment_intent.client_secret, "payment_id": payment.public_id, "public_id": data.validated_data.get("public_id") }) raise ValidationError( error_list=error_many_list_serializer(data.errors))
def put(self, request, public_id=None): data = TicketUpdateSerializer(data=request.data) if data.is_valid(): try: ticket = Ticket.objects.get( public_id=data.validated_data.get('public_id')) except Ticket.DoesNotExist or Ticket.MultipleObjectsReturned: raise TicketNotFound if ticket.is_used or ticket.event.end_date < get_current_time(): raise TicketIsExpired() if request.user != ticket.event.host: raise UserPermission ticket.is_used = True ticket.save() return response() raise ValidationError( error_list=error_many_list_serializer(data.errors))
def re_update_verification_token(self): self.verification_token = uuid.uuid4() self.verification_token_time = get_current_time() self.save() return self.verification_token
def is_valid(self, *args, **kwargs): super(EventCreateSerializer, self).is_valid(*args, **kwargs) exp_day, exp_hour, exp_min, exp_sec = EVENT_DAY_INTERVAL exp_day_se, exp_hour_se, exp_min_se, exp_sec_se = EVENT_START_END_INTERVAL if not self._errors: self._errors = {} if not self.initial_data.get('start_date'): self._errors['start_date'] = [ ErrorDetail(string="This field may not be blank.", code='invalid') ] if not self.initial_data.get('end_date'): self._errors['end_date'] = [ ErrorDetail(string="This field may not be blank.", code='invalid') ] if not self._errors.get('start_date'): start_date = self.to_internal_value_one_value( self.initial_data.get('start_date'), 'start_date') if start_date: if start_date <= get_current_time(): self._errors['start_date'] = [ ErrorDetail( string="Start date should be bigger than now.", code='invalid') ] if not self._errors.get( 'start_date') and start_date < get_current_time( ) + timedelta(days=exp_day, hours=exp_hour, minutes=exp_min, seconds=exp_sec): self._errors['start_date'] = [ ErrorDetail( string= "We require at least: {}, hours: {}, minutes: {}, " "seconds: {} for promotion of the event.".format( exp_day, exp_hour, exp_min, exp_sec), code='invalid') ] end_date = self.to_internal_value_one_value( self.initial_data.get('end_date'), 'end_date') if end_date: if start_date > end_date: self._errors['end_date'] = [ ErrorDetail( string= 'End date cannot be lower than start date.', code='invalid') ] if not self._errors.get('end_date') and end_date < start_date + \ timedelta(days=exp_day_se, hours=exp_hour_se, minutes=exp_min_se, seconds=exp_sec_se): self._errors['end_date'] = [ ErrorDetail( string= "End date should have a least days: {}, hours: {}, minutes: {}, " "seconds: {} interval compared to start date.". format(exp_day_se, exp_hour_se, exp_min_se, exp_sec_se), code='invalid') ] return bool(not self._errors)
def jwt_payload_handler(user): payload = {'user_id': user.pk, 'date': str(get_current_time())} if isinstance(user.pk, uuid.UUID): payload['user_id'] = str(user.pk) return payload
def expire_session(self): self.is_expired = True self.disconnected_date = get_current_time() self.save()
class Event(models.Model): public_id = models.UUIDField(unique=True, blank=False, default=uuid.uuid4) title = models.CharField(max_length=100, blank=False, default=None) description = models.CharField(max_length=500, blank=False, default=None) start_date = models.DateTimeField(blank=False, default=get_current_time()) end_date = models.DateTimeField(blank=False, default=get_current_time()) creation_date = models.DateTimeField(auto_now=True) is_responsible = models.BooleanField(default=False) contact_phone_number = models.CharField(max_length=100, blank=False, default=None) categories = models.ManyToManyField(Category, blank=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, blank=False, default=None, null=True) ticket_amount = models.IntegerField(default=0) available_places = models.IntegerField(default=0) ticket_fee = models.IntegerField(default=0) vip_ticket_fee = models.IntegerField(default=0) users = models.ManyToManyField(CustomUser, blank=True, related_name="cohosts") host = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, related_name="host", null=True) is_refunded_to_host = models.BooleanField(default=False) all_user_payments_refunded = models.BooleanField(default=False) def serialize(self, extra_info=False, address=True): data = { "public_id": self.public_id, "title": self.title, "description": self.description, "start_date": self.start_date, "end_date": self.end_date, "ticket_fee": self.ticket_fee, "vip_ticket_fee": self.vip_ticket_fee, "available_places": self.available_places, "ticket_amount": self.ticket_amount } data['users'] = {} data['users']["companies"] = [ i.serialize() for i in self.users.filter(is_company=True) ] if self.users.filter(is_company=True) else [] if address: data["address"] = self.address.serialize() if self.host: data['users']["companies"].append(self.host.serialize()) if extra_info: data["is_responsible"] = self.is_responsible data["contact_phone_number"] = self.contact_phone_number data["category"] = [i.serialize() for i in self.categories.all() ] if self.categories.all() else [] # tickets = Ticket.objects.filter(event=self) # data['users']["buyers"] = [i.user.serialize() for i in tickets] if tickets else [] return data def update(self, other): self.title = other.get("title") if other.get("title") else self.title self.description = other.get("description") if other.get( "description") else self.description self.contact_phone_number = other.get( "contact_phone_number") if other.get( "contact_phone_number") else self.contact_phone_number, self.start_date = other.get("start_date") if other.get( "start_date") else self.start_date, self.end_date = other.get("end_date") if other.get( "end_date") else self.end_date try: self.save() except IntegrityError: raise EventAlreadyExists() return self def __str__(self): return self.title