def mailPagamentRetrasat(request,slug):
    """
        Envia un mail avisant que el pagament de la inscripció de les JAEM no s'ha efectuat
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)

    try:
        person = Person.objects.get(slug__iexact=slug)
    except Person.DoesNotExist:
        raise Http404


    kwvars = {
        'object': person,
    }
    if person.lang == '2':
        mailtemplate = 'pagamentretrasat_cat'
    else:
        mailtemplate = 'pagamentretrasat_esp'

    context = Context(kwvars)
    status = sendTemplateMail(context,mailtemplate,[person.email_address])
    if status == _('Mail sent'):
        person.date_mailnotpaid = datetime.now()
        person.save()

    json = simplejson.dumps(status)
    return HttpResponse(json, mimetype='application/json')
def mail(request,slug,code):
    """
        Envia i genera el pdf del justificant de Pagament a les JAEM
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)

    try:
        person = Person.objects.get(slug__iexact=slug)
    except Person.DoesNotExist:
        raise Http404

    avui = _date(datetime.now(), "d \d\e F \d\e Y")


    if person.lang == '1':
        cur_language = translation.get_language()
        try:
            translation.activate('es')
            avui = _date(datetime.now(), "d \d\e F \d\e Y")
        finally:
            translation.activate(cur_language)

    kwvars = {
        'object': person,
        'avui': avui
    }
    context = Context(kwvars)
    status = sendTemplateMail(context,code,[person.email_address])
    json = simplejson.dumps(status)
    return HttpResponse(json, mimetype='application/json')
def mailPagamentRetrasatExcursion(request,id):
    """
        Envia un mail avisant que el pagament de la inscripció al sopar de les JAEM
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)

    try:
        excursion = Excursion.objects.get(id=id)
    except Excursion.DoesNotExist:
        raise Http404


    kwvars = {
        'object': excursion,
    }
    if excursion.person and excursion.person.lang == '2':
        mailtemplate = 'exc_pagamentretrasat_cat'
    else:
        mailtemplate = 'exc_pagamentretrasat_esp'

    context = Context(kwvars)
    status = sendTemplateMail(context,mailtemplate,[excursion.email_address])
    if status == _('Mail sent'):
        excursion.date_mailnotpaid = datetime.now()
        excursion.save()

    json = simplejson.dumps(status)
    return HttpResponse(json, mimetype='application/json')
def mailJustificantPagament(request,slug):
    """
        Envia i genera el pdf del justificant de Pagament a les JAEM
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)

    try:
        person = Person.objects.get(slug__iexact=slug)
    except Person.DoesNotExist:
        raise Http404

    avui = _date(datetime.now(), "d \d\e F \d\e Y")


    if person.lang == '1':
        cur_language = translation.get_language()
        try:
            translation.activate('es')
            avui = _date(datetime.now(), "d \d\e F \d\e Y")
        finally:
            translation.activate(cur_language)

    kwvars = {
        'object': person,
        'avui': avui
    }
    # ('R', _('Registrant')) -> justpagament
    # else (convidat, organitzacio, etc) -> justregistre
    if person.contact_type == 'R':
        if person.lang == '2':
            mailtemplate = 'justpagament_cat'
        else:
            mailtemplate = 'justpagament_esp'
    else:
        if person.lang == '2':
            mailtemplate = 'justregistre_cat'
        else:
            mailtemplate = 'justregistre_esp'

    context = Context(kwvars)
    status = sendTemplateMail(context,mailtemplate,[person.email_address])
    if status == _('Mail sent'):
        person.date_mailregister = datetime.now()
        person.save()

    json = simplejson.dumps(status)
    return HttpResponse(json, mimetype='application/json')
    def handle_noargs(self, **options):
        print "Enviament confirmacio inscripcio ok"

        person_list = Person.objects.all()
        person_list = person_list.filter(date_mailregister__isnull = True, status='ok_all')[:5]

        for person in person_list:
            print person.fullname
            avui = _date(datetime.now(), "d \d\e F \d\e Y")
            cur_language = translation.get_language()

            try:
                if person.lang == '2':
                    translation.activate('ca')
                    avui = _date(datetime.now(), "d \d\e F \d\e Y")
                else:
                    translation.activate('es')
                    avui = _date(datetime.now(), "d \d\e F \d\e Y")
            finally:
                translation.activate(cur_language)

            kwvars = {
                'object': person,
                'avui': avui
            }
            # ('R', _('Registrant')) -> justpagament
            # else (convidat, organitzacio, etc) -> justregistre
            if person.contact_type == 'R':
                if person.lang == '2':
                    mailtemplate = 'justpagament_cat'
                else:
                    mailtemplate = 'justpagament_esp'
            else:
                if person.lang == '2':
                    mailtemplate = 'justregistre_cat'
                else:
                    mailtemplate = 'justregistre_esp'

            context = Context(kwvars)
            status = sendTemplateMail(context,mailtemplate,[person.email_address])
            if status == _('Mail sent'):
                person.date_mailregister = datetime.now()
                person.save()
                print "Mail sended to %s" % person.email_address
            else:
                print "Error ocurred sendint to %s. Error message: %s" % (excursion.email_address, status )
    def handle_noargs(self, **options):
        print "Enviament confirmacio inscripcio ok"

        regtaller_list = TallerRegistration.objects.all()
        regtaller_list = regtaller_list.filter(date_mailassignation__isnull = True)[:25]

        for regtaller in regtaller_list:
            kwvars = {
                'object': regtaller
            }
            mailtemplate = 'tll_assignation_es' if regtaller.person.lang != '2' else 'tll_assignation_ca'
            context = Context(kwvars)
            status = sendTemplateMail(context,mailtemplate,[regtaller.email_address])
            if status == _('Mail sent'):
                regtaller.date_mailassignation = datetime.now()
                regtaller.save()
                print "Mail sended to %s" % regtaller.email_address
            else:
                print "Error ocurred sendint to %s. Error message: %s" % (regtaller.email_address, status )
def mailJustificantPagamentExcursion(request,id):
    """
        Envia i genera el pdf del justificant de Pagament del sopar de les JAEM
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/?next=%s' % request.path)

    try:
        excursion = Excursion.objects.get(id=id)
    except Excursion.DoesNotExist:
        raise Http404

    avui = _date(datetime.now(), "d \d\e F \d\e Y")


    if excursion.person and excursion.person.lang == '1':
        cur_language = translation.get_language()
        try:
            translation.activate('es')
            avui = _date(datetime.now(), "d \d\e F \d\e Y")
        finally:
            translation.activate(cur_language)

    kwvars = {
        'object': excursion,
        'avui': avui
    }

    if excursion.person and excursion.person.lang == '2':
        mailtemplate = 'exc_justpagament_cat'
    else:
        mailtemplate = 'exc_justpagament_esp'

    context = Context(kwvars)
    status = sendTemplateMail(context,mailtemplate,[excursion.email_address])
    if status == _('Mail sent'):
        excursion.date_mailregister = datetime.now()
        excursion.save()

    json = simplejson.dumps(status)
    return HttpResponse(json, mimetype='application/json')
def create(request, template='contacts/excursion/create.html'):
    """Create a excursion.

    :param template: A custom template.
    """

    user = request.user

    if not user.is_authenticated():
        try:
            user = User.objects.get(first_name='Anonymous')
        except:
            username = str(random.randint(0,1000000))
            u = User(username=username, first_name='Anonymous', last_name='User')
            u.set_unusable_password()
            u.save()
            user = User.objects.get(first_name='Anonymous')

    if request.method == 'POST':
        form = ExcursionCreateForm(request.POST)

        if form.is_valid():
            p = form.save(commit=False)
            person_list = Person.objects.filter(email_address__iexact=p.email_address)
            person = None
            if person_list.count() > 0:
                for iter_person in person_list:
                    if person is None: person = iter_person
                    if iter_person.first_name.lower().strip() == p.first_name.lower().strip():
                        person = iter_person
                        break
            else:
                raise Exception( _("This email address doesn't exist in the inscription database"))

            p.person = person
            p.user_add = user
            p.user_modify = user
            p.date_registration = datetime.now()
            p.save()
            if user.is_authenticated() and user.first_name != 'Anonymous':
                return HttpResponseRedirect(p.get_update_url())
            else:
                # Enviam correu OK + Mostram success
                kwvars = {
                    'object': p
                }
                context = Context(kwvars)
                mailtemplate = 'exc_registration_es' if p.person.lang != '2' else 'exc_registration_ca'
                status = sendTemplateMail(context,mailtemplate,[p.email_address])
                if status == _('Mail sent'):
                    mail_ok = True
                else:
                    mail_ok = False

                return render_to_response('contacts/excursion/new_success.html', {'object': p, 'mail_ok' : mail_ok, 'mail_status': status}, RequestContext(request))

    else:
        form = ExcursionCreateForm()

    kwvars = {
        'form': form
    }

    return render_to_response(template, kwvars, RequestContext(request))
def create(request, template="contacts/regtaller/create.html"):
    """Create a taller registration.

    :param template: A custom template.
    """

    user = request.user

    if not user.is_authenticated():
        try:
            user = User.objects.get(first_name="Anonymous")
        except:
            username = str(random.randint(0, 1000000))
            u = User(username=username, first_name="Anonymous", last_name="User")
            u.set_unusable_password()
            u.save()
            user = User.objects.get(first_name="Anonymous")

    if request.method == "POST":
        form = TallerRegistrationCreateForm(request.POST)

        if form.is_valid():

            p = form.save(commit=False)
            person_list = Person.objects.filter(email_address__iexact=p.email_address)
            person = None
            if person_list.count() > 0:
                for iter_person in person_list:
                    if person is None:
                        person = iter_person
                    if iter_person.first_name.lower().strip() == p.first_name.lower().strip():
                        person = iter_person
                        break
            else:
                raise Exception(_("This email address doesn't exist in the inscription database"))

            p.person = person
            # delete previous registration
            try:
                regtaller = TallerRegistration.objects.get(person_id__exact=person.id)
                regtaller.delete()
            except TallerRegistration.DoesNotExist:
                pass

            p.user_add = user
            p.user_modify = user
            p.date_registration = datetime.now()
            p.save()

            # tallers
            order = 0
            for taller_id in form.cleaned_data["tallers"].split(","):
                order = order + 1
                trelation = TallerRelation(taller_id=taller_id, taller_registration_id=p.id, preference_order=order)
                trelation.save()

            if user.is_authenticated() and user.first_name != "Anonymous":
                return HttpResponseRedirect(p.get_absolute_url())
            else:
                # Enviam correu OK + Mostram success
                kwvars = {"object": p}
                context = Context(kwvars)
                mailtemplate = "tll_registration_es" if p.person.lang != "2" else "tll_registration_ca"
                status = sendTemplateMail(context, mailtemplate, [p.email_address])
                if status == _("Mail sent"):
                    mail_ok = True
                else:
                    mail_ok = False

                return render_to_response(
                    "contacts/regtaller/new_success.html",
                    {"object": p, "mail_ok": mail_ok, "mail_status": status},
                    RequestContext(request),
                )

    else:
        form = TallerRegistrationCreateForm()

    kwvars = {"form": form}

    return render_to_response(template, kwvars, RequestContext(request))