Example #1
0
def send_order_confirmation_email(request, subject, buyer_name, buyer_email, order, media_order=None, message=None,
                                  reward_pack_list=None):
    service = get_service_instance()
    coupon_count = 0
    if reward_pack_list:
        template_name = 'shopping/mails/order_notice_with_reward.html'
        for pack in reward_pack_list:
            coupon_count += pack.count
    else:
        template_name = 'shopping/mails/order_notice.html'

    with transaction.atomic(using=WALLETS_DB_ALIAS):
        try:
            crcy = currencies(request)['CURRENCY']
            html_content = get_mail_content(subject, template_name=template_name,
                                            extra_context={'buyer_name': buyer_name, 'order': order, 'message': message,
                                                           'IS_BANK': getattr(settings, 'IS_BANK', False),
                                                           'coupon_count': coupon_count, 'crcy': crcy})
            sender = '%s <no-reply@%s>' % (service.project_name, service.domain)
            msg = XEmailMessage(subject, html_content, sender, [buyer_email])
            bcc = [email.strip() for email in service.config.notification_email.split(',') if email.strip()]
            delcom = order.delivery_option.company
            if service != delcom:
                db = delcom.database
                add_database(db)
                try:
                    delcom_config = OperatorProfile.objects.using(db).get(service=delcom)
                    bcc += [email.strip() for email in delcom_config.notification_email.split(',') if email.strip()]
                    bcc.append(delcom.member.email)
                except:
                    pass
            bcc.append(service.member.email)
            msg.bcc = list(set(bcc))
            msg.content_subtype = "html"
            Thread(target=lambda m: m.send(), args=(msg,)).start()
        except:
            logger.error("%s - Failed to send order confirmation email." % service, exc_info=True)
Example #2
0
def send_order_confirmation_email(request, subject, buyer_name, buyer_email, dara, order, message=None,
                                  reward_pack_list=None):
    service = get_service_instance()
    coupon_count = 0
    if reward_pack_list:
        template_name = 'shopping/mails/order_notice_with_reward.html'
        for pack in reward_pack_list:
            coupon_count += pack.count
    else:
        template_name = 'playground/mails/order_notice.html'
    # invitation_url = 'https://daraja.ikwen.com/daraja/companies/'
    invitation_url = 'https://daraja.ikwen.com/'
    crcy = currencies(request)['CURRENCY']
    sender = 'Daraja Playground <*****@*****.**>'
    extra_context = {'buyer_name': buyer_name, 'order': order, 'message': message,
                     'IS_BANK': getattr(settings, 'IS_BANK', False),
                     'coupon_count': coupon_count, 'crcy': crcy, 'dara': dara}
    if dara:
        extra_context['invitation_url'] = invitation_url
    html_content = get_mail_content(subject, template_name=template_name, extra_context=extra_context)

    msg = XEmailMessage(subject, html_content, sender, [buyer_email])
    bcc = [email.strip() for email in service.config.notification_email.split(',') if email.strip()]
    delcom = order.delivery_option.company
    if service != delcom:
        db = delcom.database
        add_database(db)
        try:
            delcom_config = OperatorProfile.objects.using(db).get(service=delcom)
            bcc += [email.strip() for email in delcom_config.notification_email.split(',') if email.strip()]
            bcc.append(delcom.member.email)
        except:
            pass
    bcc.append(service.member.email)
    msg.bcc = list(set(bcc))
    msg.content_subtype = "html"
    Thread(target=lambda m: m.send(), args=(msg,)).start()
Example #3
0
def confirm_invoice_payment(request, *args, **kwargs):
    tx = kwargs[
        'tx']  # Decoration with @momo_gateway_callback makes 'tx' available in kwargs
    school = Service.objects.get(pk=tx.service_id)
    school_config = SchoolConfig.objects.get(service=school)
    ikwen_charges = tx.amount * school_config.ikwen_share_rate / 100

    tx.fees = ikwen_charges
    tx.save()
    mean = tx.wallet
    db = school.database
    add_database(db)
    invoice = Invoice.objects.using(db).get(pk=tx.object_id)
    payment = Payment.objects.using(db).create(
        invoice=invoice,
        method=Payment.MOBILE_MONEY,
        amount=tx.amount,
        processor_tx_id=tx.processor_tx_id)
    invoice.paid = tx.amount
    invoice.status = Invoice.PAID
    invoice.save()
    student = invoice.student
    if not school_config.is_public or (school_config.is_public
                                       and not invoice.is_tuition):
        amount = tx.amount - ikwen_charges
        school.raise_balance(amount, provider=mean)
    else:
        amount = tx.amount
    student.set_has_new(using=school.database)
    student.save(using='default')

    set_counters(school)
    increment_history_field(school, 'turnover_history', tx.amount)
    increment_history_field(school, 'earnings_history', amount)
    increment_history_field(school, 'transaction_count_history')
    increment_history_field(school, 'transaction_earnings_history', amount)

    member = invoice.member
    if member.email:
        try:
            currency = Currency.active.default().symbol
        except:
            currency = school_config.currency_code
        invoice_url = school.url + reverse('billing:invoice_detail',
                                           args=(invoice.id, ))
        subject, message, sms_text = get_payment_confirmation_message(
            payment, member)
        html_content = get_mail_content(
            subject,
            message,
            template_name='billing/mails/notice.html',
            extra_context={
                'member_name': member.first_name,
                'invoice': invoice,
                'cta': _("View invoice"),
                'invoice_url': invoice_url,
                'currency': currency
            })
        sender = '%s <no-reply@%s>' % (school_config.company_name,
                                       school.domain)
        msg = XEmailMessage(subject, html_content, sender, [member.email])
        msg.content_subtype = "html"
        bcc = [
            email.strip()
            for email in school_config.notification_emails.split(',')
            if email.strip()
        ]
        bcc += [school_config.contact_email, school.member.email]
        msg.bcc = list(set(bcc))
        try:
            invoicing_config = get_invoicing_config_instance()
            invoice_pdf_file = generate_pdf_invoice(invoicing_config, invoice)
            msg.attach_file(invoice_pdf_file)
        except:
            pass
    return HttpResponse(
        "Notification for transaction %s received with status %s" %
        (tx.id, tx.status))
Example #4
0
def confirm_correction_payment(request, *args, **kwargs):
    status = request.GET['status']
    message = request.GET['message']
    operator_tx_id = request.GET['operator_tx_id']
    phone = request.GET['phone']
    tx_id = kwargs['tx_id']
    try:
        tx = MoMoTransaction.objects.using(WALLETS_DB_ALIAS).get(pk=tx_id)
        if not getattr(settings, 'DEBUG', False):
            tx_timeout = getattr(settings, 'IKWEN_PAYMENT_GATEWAY_TIMEOUT',
                                 15) * 60
            expiry = tx.created_on + timedelta(seconds=tx_timeout)
            if datetime.now() > expiry:
                return HttpResponse("Transaction %s timed out." % tx_id)
    except:
        raise Http404("Transaction %s not found" % tx_id)

    callback_signature = kwargs.get('signature')
    no_check_signature = request.GET.get('ncs')
    if getattr(settings, 'DEBUG', False):
        if not no_check_signature:
            if callback_signature != tx.task_id:
                return HttpResponse('Invalid transaction signature')
    else:
        if callback_signature != tx.task_id:
            return HttpResponse('Invalid transaction signature')

    if status != MoMoTransaction.SUCCESS:
        return HttpResponse(
            "Notification for transaction %s received with status %s" %
            (tx_id, status))

    school = get_service_instance()
    school_config = SchoolConfig.objects.get(service=school)
    ikwen_charges = tx.amount * school_config.my_kids_share_rate / 100
    teacher_earnings = tx.amount * (100 -
                                    school_config.my_kids_share_rate) / 100

    tx.status = status
    tx.message = message
    tx.processor_tx_id = operator_tx_id
    tx.phone = phone
    tx.is_running = False
    tx.fees = ikwen_charges
    tx.save()
    # mean = tx.wallet
    #
    # amount = tx.amount - ikwen_charges
    # payment = Payment.objects.get(object_id=tx.object_id)

    assignment = Assignment.objects.get(title=tx.message.rstrip(' correction'))
    correction = assignment.assignmentcorrection
    parent = request.user
    subject = assignment.subject
    classroom = assignment.classroom
    teacher = subject.get_teacher(classroom=classroom)
    daraja = Application.objects.get(slug=DARAJA)
    try:
        dara_weblet = Service.objects.using(UMBRELLA).get(
            app=daraja, member=teacher.member)
        dara_db = dara_weblet.database
        dara_weblet_self = Service.objects.using(dara_db).get(
            pk=dara_weblet.id)
        set_counters(dara_weblet_self)
        increment_history_field(dara_weblet_self, 'turnover_history',
                                teacher_earnings)
        increment_history_field(dara_weblet_self, 'earnings_history',
                                teacher_earnings)
        increment_history_field(dara_weblet_self, 'transaction_count_history')
        # share_payment_and_set_stats(invoice, mean)
    except:
        logger.error("The teacher %s doesn't yet have a Dara account" %
                     teacher)
    foulassi_weblet = get_service_instance()
    try:
        currency = Currency.active.default().symbol
    except:
        currency = school_config.currency_code
    body = _(
        "A student just purchase the correction of %(assignment_title)s in %(subject_name)s"
        % {
            'assignment_title': assignment.title,
            'subject_name': subject.name
        })
    member_teacher = teacher.member
    subject = _("New correction of %s paid" % correction)
    cta_url = 'https://daraja.ikwen.com' + reverse('daraja:dashboard')
    html_content = get_mail_content(
        subject,
        template_name='foulassi/mails/correction_paid.html',
        extra_context={
            'teacher': member_teacher.first_name,
            'classroom': classroom,
            'cta_url': cta_url,
            'subject': assignment.subject.name,
            'assignment': assignment,
            'currency': currency
        })
    sender = '%s <no-reply@%s>' % (school_config.company_name, school.domain)
    msg = XEmailMessage(subject, html_content, sender, [member_teacher.email])
    msg.bcc = ['*****@*****.**', '*****@*****.**']
    msg.content_subtype = "html"
    try:
        msg.send()
    except Exception as e:
        logger.debug(e.message)
    send_push(foulassi_weblet, member_teacher, subject, body, cta_url)

    body = _(
        "You just pay the correction of %(assignment_title)s from %(subject_name)s "
        % {
            'assignment_title': assignment.title,
            'subject_name': subject.name
        })
    subject = _("New correction paid")
    if parent.email:
        html_content = get_mail_content(
            subject,
            template_name='foulassi/mails/correction_paid_parent_notif.html',
            extra_context={
                'classroom': classroom,
                'parent_name': parent.first_name,
                'subject': assignment.subject.name,
                'assignment': assignment,
                'currency': currency
            })
        sender = '%s <no-reply@%s>' % (school_config.company_name,
                                       school.domain)
        msg = XEmailMessage(subject, html_content, sender, [parent.email])
        msg.bcc = ['*****@*****.**', '*****@*****.**']
        msg.content_subtype = "html"
        try:
            msg.send()
        except Exception as e:
            logger.debug(e.message)
    send_push(foulassi_weblet, parent, subject, body, cta_url)
    return HttpResponse(
        "Notification for transaction %s received with status %s" %
        (tx_id, status))
Example #5
0
def notify_cashout_and_reset_counters(request, transaction, *args, **kwargs):
    """
    Notifies IAO that request to cashout completed successfully and resets wallet balance accordingly
    :param request:
    :param transaction: MoMoTransaction object used to process this operation
    :return:
    """
    cashout_request = CashOutRequest.objects.using('wallets').get(
        pk=transaction.object_id)
    cashout_request.status = CashOutRequest.PAID
    cashout_request.reference = transaction.processor_tx_id
    charges = cashout_request.amount * cashout_request.rate / 100
    cashout_request.amount_paid = cashout_request.amount * (
        100 - cashout_request.rate) / 100
    cashout_request.save()
    weblet = Service.objects.using(UMBRELLA).get(pk=transaction.service_id)
    wallet = OperatorWallet.objects.using('wallets').get(
        nonrel_id=weblet.id, provider=transaction.wallet)
    method = CashOutMethod.objects.using(UMBRELLA).get(slug=transaction.wallet)
    address = CashOutAddress.objects.using(UMBRELLA).get(service=weblet,
                                                         method=method)
    with db_transaction.atomic(using='wallets'):
        queryset = MoMoTransaction.objects.using('wallets') \
            .filter(created_on__gt=cashout_request.paid_on, type=MoMoTransaction.CASH_OUT,
                    status=MoMoTransaction.SUCCESS, wallet=cashout_request.provider)
        iao = weblet.member
        if weblet.app.slug == DARAJA:
            dara = Dara.objects.get(member=iao)
            queryset = queryset.filter(dara_id=dara.id)
            if queryset.count() > 0:
                aggr = queryset.aggregate(Sum('dara_fees'))
                amount_successful = aggr['dara_fees__sum']
            else:
                amount_successful = 0
        else:
            queryset = queryset.filter(service_id=weblet.id)
            if queryset.count() > 0:
                aggr = queryset.aggregate(Sum('amount'))
                aggr_fees = queryset.aggregate(Sum('fees'))
                aggr_dara_fees = queryset.aggregate(Sum('dara_fees'))
                amount_successful = aggr['amount__sum'] - aggr_fees[
                    'fees__sum'] - aggr_dara_fees['dara_fees__sum']
            else:
                amount_successful = 0
        wallet.balance = amount_successful
        wallet.save(using='wallets')
        if getattr(settings, 'TESTING', False):
            IKWEN_SERVICE_ID = getattr(settings, 'IKWEN_ID')
            ikwen_service = Service.objects.using(UMBRELLA).get(
                pk=IKWEN_SERVICE_ID)
        else:
            from ikwen.conf.settings import IKWEN_SERVICE_ID
            ikwen_service = Service.objects.using(UMBRELLA).get(
                pk=IKWEN_SERVICE_ID)
        sender = 'ikwen <*****@*****.**>'
        event_originator = ikwen_service
        add_event(event_originator,
                  CASH_OUT_REQUEST_PAID,
                  member=iao,
                  object_id=cashout_request.id)

        subject = _("Money transfer confirmation")
        html_content = get_mail_content(
            subject,
            '',
            template_name='cashout/mails/payment_notice.html',
            extra_context={
                'cash_out_request': cashout_request,
                'charges': charges,
                'weblet': weblet,
                'address': address,
                'service': event_originator
            })
        msg = XEmailMessage(subject, html_content, sender, [iao.email])
        msg.service = ikwen_service
        msg.bcc = ['*****@*****.**', '*****@*****.**']
        msg.content_subtype = "html"
        Thread(target=lambda m: m.send(), args=(msg, )).start()

        set_counters(ikwen_service)
        increment_history_field(ikwen_service, 'cash_out_history',
                                cashout_request.amount)
        increment_history_field(ikwen_service, 'cash_out_count_history')