Esempio n. 1
0
def schedule_email_with_discount_code(user,
                                      discount_percentage=50,
                                      dry=False,
                                      output_dir=None):
    discount_code = DiscountCode.objects.filter(
        identifier='email_user_discount_code_{}'.format(user.id)).first()
    if discount_code is None:
        discount_code = DiscountCode.objects.create(
            identifier='email_user_discount_code_{}'.format(user.id),
            usage_limit=1,
            code=DiscountCode.objects.generate_code(),
            discount_percentage=discount_percentage)
    request = get_current_request(force=False)
    if request is not None:
        language = get_language(request)
    else:
        last_answer = Answer.objects.filter(user=user).order_by('-id').first()
        language = last_answer.lang if last_answer is not None else 'en'
    language = canonize_language_for_email(language)
    ScheduledEmail.objects.schedule_more(
        '*****@*****.**',
        'Anatom: Děkujeme, že sis vybral(a) nás'
        if language == 'cs' else 'Practice Anatomy: Thank you chose us',
        os.path.join(settings.BASE_DIR, 'anatomy', 'templates', 'email',
                     'thanks_discount_code_{}.html'.format(language)),
        users=[user],
        template_kwargs={'discount_code': discount_code},
        dry=dry,
        output_dir=output_dir)
Esempio n. 2
0
 def to_json(self, nested=False):
     data = {
         "id": self.pk,
         "identifier": self.identifier,
         "item_id": self.item_id,
         "object_type": "fc_flashcard",
         "active": self.active,
         "lang": self.lang,
         "term": self.get_term().to_json(nested=True),
         "disable_open_questions": self.disable_open_questions,
         "restrict_open_questions": self.restrict_open_questions,
     }
     if hasattr(self, "options"):
         data["options"] = [o.to_json(nested=True) for o in sorted(self.options, key=lambda f: f.term.name)]
     if hasattr(self, 'practice_meta'):
         data['practice_meta'] = self.practice_meta
     request = get_current_request(force=False)
     if not nested and (request is None or not request.GET.get('without_contexts', False)):
         data["context"] = self.get_context().to_json(nested=True)
     else:
         data["context_id"] = self.context_id
     if self.term_secondary is not None:
         data["term_secondary"] = self.get_term_secondary().to_json(nested=True)
     if self.description is not None:
         data['description'] = self.description
     if self.additional_info is not None:
         data['additional_info'] = self.additional_info
     return data
Esempio n. 3
0
def schedule_welcome_email(sender, instance, created=False, **kwargs):
    if not created:
        return
    if instance.user.email is None or instance.user.email == '':
        return
    request = get_current_request(force=False)
    if request is None:
        return
    language = get_language(request)
    language = canonize_language_for_email(language)
    ScheduledEmail.objects.schedule_more(
        '*****@*****.**',
        'Anatom: Vítej' if language == 'cs' else 'Practice Anatomy: Welcome',
        os.path.join(settings.BASE_DIR, 'anatomy', 'templates', 'email',
                     'welcome_{}.html'.format(language)),
        users=[instance.user])
    # reminder e-mails
    templates = glob.glob(
        os.path.join(settings.BASE_DIR, 'anatomy', 'templates', 'email',
                     'relation_question_{}_*.html'.format(language)))
    random.shuffle(templates)
    shifts = [1, 3, 7]
    last_datetime = datetime.datetime.now()
    for i, template in enumerate(templates):
        shift = shifts[min(i, len(shifts) - 1)]
        last_datetime = last_datetime + datetime.timedelta(days=shift)
        ScheduledEmail.objects.schedule_more(
            '*****@*****.**',
            'Anatom: Otázka dne'
            if language == 'cs' else 'Practice Anatomy: Today\'s question',
            template,
            users=[instance.user],
            scheduled=last_datetime)
Esempio n. 4
0
 def to_json(self, nested=False):
     data = {
         "id": self.pk,
         "identifier": self.identifier,
         "item_id": self.item_id,
         "object_type": "fc_flashcard",
         "active": self.active,
         "lang": self.lang,
         "term": self.get_term().to_json(nested=True),
         "disable_open_questions": self.disable_open_questions,
         "restrict_open_questions": self.restrict_open_questions,
     }
     if hasattr(self, "options"):
         data["options"] = [
             o.to_json(nested=True)
             for o in sorted(self.options, key=lambda f: f.term.name)
         ]
     if hasattr(self, 'practice_meta'):
         data['practice_meta'] = self.practice_meta
     request = get_current_request(force=False)
     if not nested and (request is None
                        or not request.GET.get('without_contexts', False)):
         data["context"] = self.get_context().to_json(nested=True)
     else:
         data["context_id"] = self.context_id
     if self.term_secondary is not None:
         data["term_secondary"] = self.get_term_secondary().to_json(
             nested=True)
     if self.description is not None:
         data['description'] = self.description
     if self.additional_info is not None:
         data['additional_info'] = self.additional_info
     return data
Esempio n. 5
0
 def reset_current_session(self):
     current_request = get_current_request(force=False)
     if current_request is None:
         return
     if 'proso_user_current_session_id' not in current_request.session:
         return
     del current_request.sesion['proso_user_current_session_id']
     del current_request.session['proso_user_current_session_last_touch']
Esempio n. 6
0
 def reset_current_session(self):
     current_request = get_current_request(force=False)
     if current_request is None:
         return
     if 'proso_user_current_session_id' not in current_request.session:
         return
     del current_request.sesion['proso_user_current_session_id']
     del current_request.session['proso_user_current_session_last_touch']
Esempio n. 7
0
 def prepare_related(self):
     related = [
         Flashcard.related_term(),
         Flashcard.related_term_secondary()
     ]
     request = get_current_request(force=False)
     if request is None or not request.GET.get('without_contexts', False):
         related.append(Flashcard.related_context())
     return self.select_related(*related)
Esempio n. 8
0
    def __init__(self,
                 predictive_model,
                 weight_probability=10.0,
                 weight_number_of_answers=5.0,
                 weight_time_ago=5,
                 weight_parent_time_ago=5.0,
                 weight_parent_number_of_answers=2.5,
                 target_probability=DEFAULT_TARGET_PROBABILITY,
                 time_ago_max=120,
                 recompute_parent_score=True,
                 history_adjustment=True,
                 estimate_parent_factors=True):
        from proso.django.request import get_current_request
        from proso_models.models import get_filter
        from proso_concepts.models import Concept

        req = get_current_request()

        categories = get_filter(req)
        categories = list(set().union(*categories))
        categories.sort(reverse=True)
        category_identifier = Concept.objects.filter(
            query=json.dumps([categories])).first().identifier

        LOGGER.debug("REQUEST FILTERS: %s" % json.dumps([categories]))
        LOGGER.debug("REQUEST FILTER -> CATEGORY_IDENTIFIER: %s" %
                     category_identifier)

        if category_identifier in [
                "9286c11ae03051824142", "0abbc00aab49f3ab3087",
                "e7576f2d7d9acdc8938d", "e0a6b9187f402bc4b6b4",
                "5003410ef72a80a76ab8", "6b799a540d42f7164d57",
                "777959a7e2799da678ce", "32110d4fd300c32b6dda",
                "b239ffe83950753eff4b", "55dfd24083b6c5248539",
                "0c74a5bff211f8c1366b", "176c56aa2399180149c0",
                "3f987d036bf3b84033c6", "cf3e1afe7556fc9b5302"
        ]:
            target_probability = 0.80
        elif category_identifier in [
                "5d96cf6829a091825ab1", "07907708da836f3e41c0",
                "88775c0f18142298fdab", "99b2a9bd43cd5226eec1",
                "dd326eccb76dbfae6dd1", "09b896106800eb5f1931",
                "149c12764fe26ebcf685"
        ]:
            target_probability = 0.50
        else:
            target_probability = 0.65

        LOGGER.debug("REQUEST FILTER -> USING TARGET_PROBABILITY == %f" %
                     target_probability)

        super().__init__(predictive_model, weight_probability,
                         weight_number_of_answers, weight_time_ago,
                         weight_parent_time_ago,
                         weight_parent_number_of_answers, target_probability,
                         time_ago_max, recompute_parent_score,
                         history_adjustment, estimate_parent_factors)
Esempio n. 9
0
 def get_current_session_id(self):
     current_request = get_current_request(force=False)
     if current_request is None:
         return None
     session_id = current_request.session.get('proso_user_current_session_id')
     session_last_touch = current_request.session.get('proso_user_current_session_last_touch')
     session_last_touch = datetime.datetime.strptime(session_last_touch, '%Y-%m-%d %H:%M:%S') if session_last_touch else None
     if session_id is None or (datetime.datetime.now() - session_last_touch).total_seconds() > 15 * 60:
         current_session = Session(user_id=current_request.user.id)
         current_session.save()
         current_request.session['proso_user_current_session_id'] = current_session.id
     current_request.session['proso_user_current_session_last_touch'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
     return int(current_request.session.get('proso_user_current_session_id'))
Esempio n. 10
0
 def to_json(self, nested=False):
     json = {
         "id": self.pk,
         "identifier": self.identifier,
         "item_id": self.item_id,
         "object_type": "fc_context",
         "lang": self.lang,
         "name": self.name,
         "active": self.active,
     }
     request = get_current_request(force=False)
     if request is None or not request.GET.get('without_content', False):
         json['content'] = self.content
     return json
Esempio n. 11
0
 def to_json(self, nested=False):
     json = {
         "id": self.pk,
         "identifier": self.identifier,
         "item_id": self.item_id,
         "object_type": "fc_context",
         "lang": self.lang,
         "name": self.name,
         "active": self.active,
     }
     request = get_current_request(force=False)
     if request is None or not request.GET.get('without_content', False):
         json['content'] = self.content
     return json
Esempio n. 12
0
def schedule_email_with_discount_code_after_long_practice(
        sender, instance, created=False, **kwargs):
    if not issubclass(sender, Answer):
        return
    if not created:
        return
    request = get_current_request(force=False)
    if request is None:
        return
    if not request.user.is_authenticated() or not request.user.email:
        return
    answer_count = Answer.objects.filter(user=request.user).count()
    if answer_count != 200:
        return
    if Subscription.objects.is_active(request.user, 'full'):
        return
    schedule_email_with_discount_code(request.user)
Esempio n. 13
0
    def subscribe(self, user, plan_description, discount_code, referral_user, return_url):
        if discount_code is not None:
            discount_code.is_valid(user, plan_description=plan_description, throw_exception=True)
        if referral_user is not None and referral_user.id == user.id:
            raise BadRequestException("The referral user can not be the same as the given subscriber.")
        price = plan_description.price if discount_code is None else discount_code.get_updated_price(plan_description.price)
        lang = get_current_request().LANGUAGE_CODE.split('-')[0].split('_')[0].upper()
        if lang not in {'CS', 'EN', 'DE'}:
            lang = 'EN'
        if price > 0:
            payment = Payment.objects.create_single_payment(
                order_number=str(uuid.uuid1()),
                order_description=plan_description.description,
                order_items={
                    plan_description.name: plan_description.price,
                },
                contact=Payment.objects.create_contact(email=user.email),
                currency=plan_description.currency,
                amount=price,
                return_url=return_url,
                lang=lang
            )
        else:
            payment = None

        subscription = Subscription(
            plan_description=plan_description,
            payment=payment,
            user=user,
            discount=discount_code,
            referral=referral_user
        )
        if payment is None:
            subscription.expiration = datetime.now() + relativedelta(months=subscription.plan_description.plan.months_validity)
        subscription.save()
        return subscription
Esempio n. 14
0
def init_session_http_user_agent(sender, instance, **kwargs):
    if instance.http_user_agent is None:
        current_request = get_current_request(force=False)
        if current_request:
            instance.http_user_agent = HttpUserAgent.objects.from_content(
                current_request.META.get('HTTP_USER_AGENT', ''))
Esempio n. 15
0
def init_session_location(sender, instance, **kwargs):
    if instance.location is None:
        current_request = get_current_request(force=False)
        ip_address = get_ip(current_request) if current_request else None
        if ip_address:
            instance.location = Location.objects.from_ip_address(ip_address)
Esempio n. 16
0
def init_session_http_user_agent(sender, instance, **kwargs):
    if instance.http_user_agent is None:
        current_request = get_current_request(force=False)
        if current_request:
            instance.http_user_agent = HttpUserAgent.objects.from_content(current_request.META.get('HTTP_USER_AGENT', ''))
Esempio n. 17
0
def init_session_location(sender, instance, **kwargs):
    if instance.location is None:
        current_request = get_current_request(force=False)
        ip_address = get_ip(current_request) if current_request else None
        if ip_address:
            instance.location = Location.objects.from_ip_address(ip_address)
Esempio n. 18
0
 def prepare_related(self):
     related = [Flashcard.related_term(), Flashcard.related_term_secondary()]
     request = get_current_request(force=False)
     if request is None or not request.GET.get('without_contexts', False):
         related.append(Flashcard.related_context())
     return self.select_related(*related)