before clean migrations

This commit is contained in:
Jonas 12t 2021-09-27 17:25:58 +04:00
parent f666d24eff
commit b242129b49
23 changed files with 853 additions and 396 deletions

View File

@ -4,7 +4,7 @@ from django.contrib.auth.models import Group
from solo.admin import SingletonModelAdmin from solo.admin import SingletonModelAdmin
from AuthBillet.models import HumanUser, SuperHumanUser, TermUser from AuthBillet.models import HumanUser, SuperHumanUser, TermUser
from BaseBillet.models import Configuration, Event, OptionGenerale, Article, Billet, Reservation, LigneArticle from BaseBillet.models import Configuration, Event, OptionGenerale, Article, Billet, Reservation, LigneArticle, TarifsAdhesion
from django.contrib.auth.admin import UserAdmin from django.contrib.auth.admin import UserAdmin
from Customers.models import Client from Customers.models import Client
@ -117,6 +117,12 @@ class ConfigurationAdmin(SingletonModelAdmin):
'carte_restaurant', 'carte_restaurant',
) )
}), }),
('Adhésions', {
'fields': (
'adhesion_obligatoire',
'cadeau_adhesion',
),
}),
('Paiements', { ('Paiements', {
'fields': ( 'fields': (
'mollie_api_key', 'mollie_api_key',
@ -144,6 +150,16 @@ class ConfigurationAdmin(SingletonModelAdmin):
staff_admin_site.register(Configuration, ConfigurationAdmin) staff_admin_site.register(Configuration, ConfigurationAdmin)
class TarifsAdhesionAdmin(admin.ModelAdmin):
list_display = (
'name',
'tarif'
)
list_editable = ('tarif',)
ordering = ('tarif',)
staff_admin_site.register(TarifsAdhesion, TarifsAdhesionAdmin)
class EventAdmin(admin.ModelAdmin): class EventAdmin(admin.ModelAdmin):
list_display = ( list_display = (

View File

@ -1,8 +1,9 @@
# Generated by Django 2.2 on 2021-06-23 09:09 # Generated by Django 2.2 on 2021-09-27 12:56
from django.db import migrations, models from django.db import migrations, models
import django.db.models.deletion import django.db.models.deletion
import django.utils.timezone import django.utils.timezone
import uuid
class Migration(migrations.Migration): class Migration(migrations.Migration):
@ -11,7 +12,7 @@ class Migration(migrations.Migration):
dependencies = [ dependencies = [
('auth', '0011_update_proxy_permissions'), ('auth', '0011_update_proxy_permissions'),
('Customers', '0001_initial'), ('Customers', '0003_auto_20210623_1351'),
] ]
operations = [ operations = [
@ -27,8 +28,10 @@ class Migration(migrations.Migration):
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('uuid_user', models.UUIDField(default=uuid.uuid4, editable=False)),
('email', models.EmailField(max_length=254, unique=True, verbose_name='email')), ('email', models.EmailField(max_length=254, unique=True, verbose_name='email')),
('username', models.CharField(blank=True, max_length=200, null=True)), ('username', models.CharField(blank=True, max_length=200, null=True)),
('phone', models.CharField(blank=True, max_length=20, null=True)),
('espece', models.CharField(choices=[('TE', 'Terminal'), ('AN', 'Android'), ('HU', 'Humain')], default='HU', max_length=2)), ('espece', models.CharField(choices=[('TE', 'Terminal'), ('AN', 'Android'), ('HU', 'Humain')], default='HU', max_length=2)),
('offre', models.CharField(choices=[('PU', 'Public'), ('FR', 'Gratuit'), ('PR', 'Premium'), ('EN', 'Entreprise'), ('CU', 'Custom')], default='PU', max_length=2)), ('offre', models.CharField(choices=[('PU', 'Public'), ('FR', 'Gratuit'), ('PR', 'Premium'), ('EN', 'Entreprise'), ('CU', 'Custom')], default='PU', max_length=2)),
('client_achat', models.ManyToManyField(blank=True, related_name='user_achats', to='Customers.Client')), ('client_achat', models.ManyToManyField(blank=True, related_name='user_achats', to='Customers.Client')),

View File

@ -1,18 +0,0 @@
# Generated by Django 2.2 on 2021-06-29 12:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AuthBillet', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='tibilletuser',
name='phone',
field=models.CharField(blank=True, max_length=12, null=True),
),
]

View File

@ -1,18 +0,0 @@
# Generated by Django 2.2 on 2021-06-29 12:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AuthBillet', '0002_tibilletuser_phone'),
]
operations = [
migrations.AlterField(
model_name='tibilletuser',
name='phone',
field=models.CharField(blank=True, max_length=20, null=True),
),
]

View File

@ -46,7 +46,9 @@ class TibilletManager(BaseUserManager):
class TibilletUser(AbstractUser): class TibilletUser(AbstractUser):
#TODO regarder du coté du dashboard de jet, ça plante avec uuid ! #TODO regarder du coté du dashboard de jet, ça plante avec uuid !
# uuid_user = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True, db_index=True) # uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True, db_index=True)
uuid_user = models.UUIDField(default=uuid.uuid4, editable=False)
USERNAME_FIELD = 'email' USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # removes email from REQUIRED_FIELDS REQUIRED_FIELDS = [] # removes email from REQUIRED_FIELDS

View File

@ -0,0 +1,32 @@
# Generated by Django 2.2 on 2021-09-27 06:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0048_auto_20210926_1531'),
]
operations = [
migrations.CreateModel(
name='TarifsAdhesion',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
('tarif', models.FloatField()),
],
),
migrations.AddField(
model_name='configuration',
name='adhesion_obligatoire',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,28 @@
# Generated by Django 2.2 on 2021-09-27 07:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0049_auto_20210927_1047'),
]
operations = [
migrations.AlterModelOptions(
name='tarifsadhesion',
options={'ordering': ('-tarif',)},
),
migrations.AddField(
model_name='configuration',
name='cadeau_adhesion',
field=models.FloatField(default=0),
),
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,29 @@
# Generated by Django 2.2 on 2021-09-27 09:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0050_auto_20210927_1132'),
]
operations = [
migrations.AddField(
model_name='article',
name='categorie_article',
field=models.CharField(choices=[('B', 'Billet'), ('P', "Pack d'objets"), ('R', 'Recharge cashless'), ('T', 'Vetement'), ('M', 'Merchandasing')], default='B', max_length=3, verbose_name='Status de la réservation'),
),
migrations.AlterField(
model_name='configuration',
name='cadeau_adhesion',
field=models.FloatField(default=0, help_text="Recharge cadeau a l'adhésion"),
),
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,24 @@
# Generated by Django 2.2 on 2021-09-27 09:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0051_auto_20210927_1334'),
]
operations = [
migrations.AddField(
model_name='article',
name='id_stripe',
field=models.CharField(blank=True, max_length=30, null=True),
),
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,26 @@
# Generated by Django 2.2 on 2021-09-27 09:48
from django.db import migrations, models
import django.db.models.deletion
import stdimage.models
import stdimage.validators
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0052_auto_20210927_1335'),
]
operations = [
migrations.AddField(
model_name='article',
name='img',
field=stdimage.models.StdImageField(blank=True, null=True, upload_to='images/', validators=[stdimage.validators.MaxSizeValidator(1920, 1920)], verbose_name='Image'),
),
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,29 @@
# Generated by Django 2.2 on 2021-09-27 09:50
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0053_auto_20210927_1348'),
]
operations = [
migrations.RemoveField(
model_name='article',
name='id',
),
migrations.AddField(
model_name='article',
name='uuid',
field=models.UUIDField(db_index=True, default=uuid.uuid4, primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,29 @@
# Generated by Django 2.2 on 2021-09-27 10:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0054_auto_20210927_1350'),
]
operations = [
migrations.RenameField(
model_name='article',
old_name='id_stripe',
new_name='id_price_stripe',
),
migrations.AlterField(
model_name='article',
name='categorie_article',
field=models.CharField(choices=[('B', 'Billet'), ('P', "Pack d'objets"), ('R', 'Recharge cashless'), ('T', 'Vetement'), ('M', 'Merchandasing'), ('A', 'Adhésion')], default='B', max_length=3, verbose_name="Type d'article"),
),
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,24 @@
# Generated by Django 2.2 on 2021-09-27 10:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0055_auto_20210927_1407'),
]
operations = [
migrations.AddField(
model_name='article',
name='id_product_stripe',
field=models.CharField(blank=True, max_length=30, null=True),
),
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,19 @@
# Generated by Django 2.2 on 2021-09-27 11:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0056_auto_20210927_1407'),
]
operations = [
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,19 @@
# Generated by Django 2.2 on 2021-09-27 12:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0057_auto_20210927_1543'),
]
operations = [
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,19 @@
# Generated by Django 2.2 on 2021-09-27 12:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0058_auto_20210927_1634'),
]
operations = [
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,25 @@
# Generated by Django 2.2 on 2021-09-27 13:18
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0059_auto_20210927_1634'),
]
operations = [
migrations.AlterField(
model_name='article',
name='uuid',
field=models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -0,0 +1,19 @@
# Generated by Django 2.2 on 2021-09-27 13:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('BaseBillet', '0060_auto_20210927_1718'),
]
operations = [
migrations.AlterField(
model_name='lignearticle',
name='reservation',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='BaseBillet.Reservation'),
),
]

View File

@ -10,9 +10,11 @@ from solo.models import SingletonModel
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from stdimage import StdImageField from stdimage import StdImageField
from stdimage.validators import MaxSizeValidator from stdimage.validators import MaxSizeValidator
from django.db import connection
from PaiementStripe.models import Paiement_stripe from PaiementStripe.models import Paiement_stripe
from TiBillet import settings from TiBillet import settings
import stripe
class OptionGenerale(models.Model): class OptionGenerale(models.Model):
@ -38,6 +40,17 @@ def poids_option_generale(sender, instance: OptionGenerale, created, **kwargs):
instance.save() instance.save()
class TarifsAdhesion(models.Model):
name = models.CharField(max_length=30)
tarif = models.FloatField()
class Meta:
ordering = ('-tarif',)
def __str__(self):
return f"{self.name} {self.tarif}"
class Configuration(SingletonModel): class Configuration(SingletonModel):
organisation = models.CharField(max_length=50) organisation = models.CharField(max_length=50)
short_description = models.CharField(max_length=250) short_description = models.CharField(max_length=250)
@ -52,6 +65,9 @@ class Configuration(SingletonModel):
facebook = models.URLField(blank=True, null=True) facebook = models.URLField(blank=True, null=True)
instagram = models.URLField(blank=True, null=True) instagram = models.URLField(blank=True, null=True)
adhesion_obligatoire = models.BooleanField(default=False)
cadeau_adhesion = models.FloatField(default=0, help_text="Recharge cadeau a l'adhésion")
carte_restaurant = StdImageField(upload_to='images/', carte_restaurant = StdImageField(upload_to='images/',
null=True, blank=True, null=True, blank=True,
validators=[MaxSizeValidator(1920, 1920)], validators=[MaxSizeValidator(1920, 1920)],
@ -141,6 +157,8 @@ class VAT(models.Model):
class Article(models.Model): class Article(models.Model):
uuid = models.UUIDField(primary_key=True, db_index=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50, name = models.CharField(max_length=50,
blank=True, null=True) blank=True, null=True)
prix = models.FloatField() prix = models.FloatField()
@ -151,9 +169,94 @@ class Article(models.Model):
publish = models.BooleanField(default=False) publish = models.BooleanField(default=False)
img = StdImageField(upload_to='images/',
null=True, blank=True,
validators=[MaxSizeValidator(1920, 1920)],
variations={
'fhd': (1920, 1920),
'hdr': (720, 720),
'med': (480, 480),
'thumbnail': (150, 90),
},
delete_orphans=True,
verbose_name='Image'
)
BILLET, PACK, RECHARGE_CASHLESS, VETEMENT, MERCH, ADHESION = 'B', 'P', 'R', 'T', 'M', 'A'
TYPE_CHOICES = [
(BILLET, _('Billet')),
(PACK, _("Pack d'objets")),
(RECHARGE_CASHLESS, _('Recharge cashless')),
(VETEMENT, _('Vetement')),
(MERCH, _('Merchandasing')),
(ADHESION, ('Adhésion')),
]
categorie_article = models.CharField(max_length=3, choices=TYPE_CHOICES, default=BILLET,
verbose_name=_("Type d'article"))
id_product_stripe = models.CharField(max_length=30, null=True, blank=True)
id_price_stripe = models.CharField(max_length=30, null=True, blank=True)
def range_max(self): def range_max(self):
return range(self.reservation_par_user_max + 1) return range(self.reservation_par_user_max + 1)
def get_id_product_stripe(self):
configuration = Configuration.get_solo()
if configuration.stripe_api_key and not self.id_product_stripe:
if configuration.stripe_mode_test:
stripe.api_key = configuration.stripe_test_api_key
else:
stripe.api_key = configuration.stripe_api_key
if self.img :
# noinspection PyUnresolvedReferences
domain_url = connection.tenant.domains.all()[0].domain
images = [f"https://{domain_url}{self.img.med.url}",]
else:
images = []
product = stripe.Product.create(
name=f"{self.name}",
images=images
)
self.id_product_stripe = product.id
self.save()
return self.id_product_stripe
elif self.id_product_stripe:
return self.id_product_stripe
else:
return False
def get_id_price_stripe(self):
configuration = Configuration.get_solo()
if configuration.stripe_api_key and not self.id_price_stripe:
if configuration.stripe_mode_test:
stripe.api_key = configuration.stripe_test_api_key
else:
stripe.api_key = configuration.stripe_api_key
price = stripe.Price.create(
unit_amount=int("{0:.2f}".format(self.prix).replace('.', '')),
currency="eur",
product=self.get_id_product_stripe(),
)
self.id_price_stripe = price.id
self.save()
return self.id_price_stripe
elif self.id_price_stripe:
return self.id_price_stripe
else:
return False
def reset_id_stripe(self):
self.id_price_stripe = None
self.id_product_stripe = None
self.save()
def __str__(self): def __str__(self):
return f"{self.name}" return f"{self.name}"

View File

@ -1,22 +1,140 @@
import json import json
from datetime import datetime from datetime import datetime
from django.http import HttpResponse, Http404 from django.contrib.auth import get_user_model
from django.db import connection
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404 from django.shortcuts import get_object_or_404
import stripe import stripe
# Create your views here. # Create your views here.
from django.utils import timezone from django.utils import timezone
from django.views import View from django.views import View
from BaseBillet.models import Configuration from AuthBillet.models import HumanUser
from BaseBillet.models import Configuration, Article, LigneArticle
from PaiementStripe.models import Paiement_stripe from PaiementStripe.models import Paiement_stripe
# from QrcodeCashless.views import postPaimentRecharge
from QrcodeCashless.views import postPaimentRecharge
import logging import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class creation_checkout_stripe():
def __init__(self,
email_paiement: str,
liste_ligne_article: list,
metadata: dict,
absolute_domain: str
) -> None:
self.absolute_domain = absolute_domain
self.configuration = Configuration.get_solo()
self.email_paiement = email_paiement
self.user = self._user_paiement()
self.detail = self._detail()
self.total = self._total()
self.liste_ligne_article = liste_ligne_article
self.metadata = metadata
self.metadata_json = json.dumps(self.metadata)
self.paiement_stripe_db = self._paiement_stripe_db()
self.stripe_api_key = self._stripe_api_key()
self.line_items = self._line_items()
self.checkout_session = self._checkout_session()
def _user_paiement(self):
User = get_user_model()
user_paiement, created = User.objects.get_or_create(
email=self.email_paiement)
if created:
user_paiement: HumanUser
user_paiement.client_source = connection.tenant
user_paiement.client_achat.add(connection.tenant)
user_paiement.is_active = False
else:
user_paiement.client_achat.add(connection.tenant)
user_paiement.save()
return user_paiement
def _total(self):
total = 0
for ligne in self.liste_ligne_article:
ligne: LigneArticle
total += ligne.qty * ligne.article.prix
return total
def _detail(self):
detail = ""
for ligne in self.liste_ligne_article:
ligne: LigneArticle
detail += f"{ligne.article}"
return detail
def _paiement_stripe_db(self):
paiementStripeDb = Paiement_stripe.objects.create(
user=self.user,
detail=self.detail,
total=self.total,
metadata_stripe=self.metadata_json,
)
return paiementStripeDb
def _stripe_api_key(self):
if self.configuration.stripe_mode_test:
stripe.api_key = self.configuration.stripe_test_api_key
else:
stripe.api_key = self.configuration.stripe_api_key
return stripe.api_key
def _line_items(self):
line_items = []
for ligne in self.liste_ligne_article:
ligne: LigneArticle
line_items.append(
{
"price": f"{ligne.article.get_id_price_stripe()}",
"quantity": ligne.qty,
}
)
def _checkout_session(self):
checkout_session = stripe.checkout.Session.create(
customer_email=f'{self.user.email}',
line_items=self.line_items,
payment_method_types=['card'],
mode='payment',
metadata=self.metadata,
success_url=f'{self.absolute_domain}/stripe/return/{self.paiement_stripe_db.uuid}',
cancel_url=f'{self.absolute_domain}/stripe/return/{self.paiement_stripe_db.uuid}',
client_reference_id=f"{self.user.uuid_user}",
)
print(checkout_session.id)
self.paiement_stripe_db.id_stripe = checkout_session.id
self.paiement_stripe_db.status = Paiement_stripe.PENDING
self.paiement_stripe_db.save()
return checkout_session
def is_valid(self):
if self.checkout_session.id and \
self.checkout_session.url :
return True
else:
return False
def redirect_to_stripe(self):
return HttpResponseRedirect(self.checkout_session.url)
class retour_stripe(View): class retour_stripe(View):
def get(self, request, uuid_stripe): def get(self, request, uuid_stripe):
@ -28,12 +146,12 @@ class retour_stripe(View):
else: else:
stripe.api_key = configuration.stripe_api_key stripe.api_key = configuration.stripe_api_key
if paiement_stripe.status != Paiement_stripe.VALID : if paiement_stripe.status != Paiement_stripe.VALID:
checkout_session = stripe.checkout.Session.retrieve(paiement_stripe.id_stripe) checkout_session = stripe.checkout.Session.retrieve(paiement_stripe.id_stripe)
if checkout_session.payment_status == "unpaid": if checkout_session.payment_status == "unpaid":
paiement_stripe.status = Paiement_stripe.PENDING paiement_stripe.status = Paiement_stripe.PENDING
if checkout_session.expires_at > datetime.now().timestamp() : if checkout_session.expires_at > datetime.now().timestamp():
paiement_stripe.status = Paiement_stripe.EXPIRE paiement_stripe.status = Paiement_stripe.EXPIRE
paiement_stripe.save() paiement_stripe.save()
@ -51,7 +169,7 @@ class retour_stripe(View):
try: try:
assert metadata_stripe == metadata_db assert metadata_stripe == metadata_db
assert set(metadata_db.keys()) == set(metadata_stripe.keys()) assert set(metadata_db.keys()) == set(metadata_stripe.keys())
for key in set(metadata_stripe.keys()) : for key in set(metadata_stripe.keys()):
assert metadata_db[key] == metadata_stripe[key] assert metadata_db[key] == metadata_stripe[key]
except: except:
logger.error(f"{timezone.now()} " logger.error(f"{timezone.now()} "
@ -60,10 +178,14 @@ class retour_stripe(View):
raise Http404 raise Http404
# on check si il y a un rechargement de carte cashless dans la commande # on check si il y a un rechargement de carte cashless dans la commande
if metadata_db.get('recharge_carte_uuid') : if metadata_db.get('recharge_carte_uuid'):
logger.info(f'{timezone.now()} retour stripe pour rechargement carte : {metadata_db.get("recharge_carte_uuid")}') logger.info(
print (f'{timezone.now()} retour stripe pour rechargement carte : {metadata_db.get("recharge_carte_uuid")}') f'{timezone.now()} retour stripe pour rechargement carte : {metadata_db.get("recharge_carte_uuid")}')
return postPaimentRecharge(paiement_stripe, request) print(
f'{timezone.now()} retour stripe pour rechargement carte : {metadata_db.get("recharge_carte_uuid")}')
print('gerer la recharge sur le serveur cashless')
# return postPaimentRecharge(paiement_stripe, request)
@ -71,11 +193,13 @@ class retour_stripe(View):
else: else:
paiement_stripe.status = Paiement_stripe.CANCELED paiement_stripe.status = Paiement_stripe.CANCELED
paiement_stripe.save() paiement_stripe.save()
return HttpResponse(f'Le paiement a été annulé.') return HttpResponse(f'Le paiement annulé.')
return HttpResponse(f'ok {uuid_stripe}') return HttpResponse(f'Paiement validé')
'''
class webhook_stripe(View): class webhook_stripe(View):
def get(self, request): def get(self, request):
print(f"webhook_stripe GET") print(f"webhook_stripe GET")
@ -103,3 +227,4 @@ class webhook_stripe(View):
print(f"webhook_stripe POST {event}") print(f"webhook_stripe POST {event}")
return HttpResponse(f'ok {event}') return HttpResponse(f'ok {event}')
'''

View File

@ -16,7 +16,7 @@
<link rel="stylesheet" href="{% static 'html5up-dimension/assets/css/noscript.css' %}"/> <link rel="stylesheet" href="{% static 'html5up-dimension/assets/css/noscript.css' %}"/>
</noscript> </noscript>
</head> </head>
<body class="is-preload"> < class="is-preload">
<!-- Wrapper --> <!-- Wrapper -->
<div id="wrapper"> <div id="wrapper">
@ -96,6 +96,11 @@
<!-- Historique --> <!-- Historique -->
<article id="historique"> <article id="historique">
<div class="table-wrapper"> <div class="table-wrapper">
{% if messages %}
{% for message in messages %}
<h3>{{ message }}</h3>
{% endfor %}
{% endif %}
<h2 class="major">Solde</h2> <h2 class="major">Solde</h2>
<table> <table>
@ -109,14 +114,14 @@
{% for asset in assets %} {% for asset in assets %}
<tr> <tr>
<td>{{ asset.nom }}</td> <td>{{ asset.nom }}</td>
<td>{{ asset.qty |floatformat:2|intcomma }}</td> <td>{{ asset.qty | floatformat:2 | intcomma }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
<tfoot> <tfoot>
<tr> <tr>
<td colspan="1"></td> <td colspan="1"></td>
<td>{{ total_monnaie |floatformat:2|intcomma }}</td> <td>{{ total_monnaie | floatformat:2 | intcomma }}</td>
</tr> </tr>
</tfoot> </tfoot>
</table> </table>
@ -148,10 +153,6 @@
</div> </div>
</article> </article>
<article id="adhesionsuccess">
<h2 class="major">Adhésion</h2>
<h4>Merci !</h4>
</article>
<article id="success"> <article id="success">
<h2 class="major">Rechargement OK</h2> <h2 class="major">Rechargement OK</h2>
@ -168,14 +169,14 @@
{% for asset in assets %} {% for asset in assets %}
<tr> <tr>
<td>{{ asset.nom }}</td> <td>{{ asset.nom }}</td>
<td>{{ asset.qty |floatformat:2|intcomma }}</td> <td>{{ asset.qty | floatformat:2 | intcomma }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
<tfoot> <tfoot>
<tr> <tr>
<td colspan="1"></td> <td colspan="1"></td>
<td>{{ total_monnaie |floatformat:2|intcomma }}</td> <td>{{ total_monnaie | floatformat:2 | intcomma }}</td>
</tr> </tr>
</tfoot> </tfoot>
</table> </table>
@ -185,14 +186,6 @@
</ul> </ul>
</article> </article>
<article id="error">
<h2 class="major">ERREUR</h2>
<h3>Le paiement n'a pas fonctionné.</h3>
<h4>Vérifiez votre moyen de paiement ou contacter un administrateur</h4>
<ul class="actions">
<li><a href="#historique" class="button primary">Voir l'historique</a></li>
</ul>
</article>
<!-- adhesion --> <!-- adhesion -->
<article id="adherer"> <article id="adherer">
@ -200,19 +193,36 @@
<form method="post" action="#"> <form method="post" action="#">
{% csrf_token %} {% csrf_token %}
<div class="fields"> <div class="fields">
<div class="field half"> <div class="field">
<label for="email">Entrez votre Email</label>
<input id="email" name="email" required="True" type="email"/>
</div>
</div>
<ul class="actions">
<li><input type="submit" value="continuer" class="primary"/></li>
</ul>
</form>
</article>
<!-- adhesion -->
<article id="demande_nom_prenom_tel">
<h2 class="major">Adhésion {{ client_name }}</h2>
<h4 id="knew_text">Nous avons déja : </h4>
<h4>Il nous manque ces informations pour votre adhésion :</h4>
<form method="post" action="#">
{% csrf_token %}
<div class="fields">
<input id="adhesion_email" name="email" required="True" type="email" style="display: none"/>
<div id="adhesion_name" class="field half">
<label for="name">Nom</label> <label for="name">Nom</label>
<input id="name" name="name" required="True" type="text"/> <input id="name" name="name" required="True" type="text"/>
</div> </div>
<div class="field half"> <div id="adhesion_prenom" class="field half">
<label for="prenom">Prénom</label> <label for="prenom">Prénom</label>
<input id="prenom" name="prenom" required="True" type="text"/> <input id="prenom" name="prenom" required="True" type="text"/>
</div> </div>
<div class="field half"> <div id="adhesion_tel" class="field half">
<label for="email">Email</label>
<input id="email" name="email" required="True" type="email"/>
</div>
<div class="field half">
<label for="tel">Téléphone</label> <label for="tel">Téléphone</label>
<input id="tel" name="tel" required="True" type="tel"/> <input id="tel" name="tel" required="True" type="tel"/>
</div> </div>
@ -223,255 +233,94 @@
</form> </form>
</article> </article>
<!-- Elements --> <article id="adhesionsuccess">
<article id="elements"> <h2 class="major">Adhésion</h2>
<h2 class="major">Elements</h2> {% if messages %}
{% for message in messages %}
<h3>{{ message }}</h3>
{% endfor %}
{% endif %}
<section> {% if adhesion_obligatoire %}
<h3 class="major">Text</h3> {% if tarifs_adhesion %}
<p>This is <b>bold</b> and this is <strong>strong</strong>. This is <i>italic</i> and this is <em>emphasized</em>. <h4>Payer en ligne avec un vrai robot :</h4>
This is <sup>superscript</sup> text and this is <sub>subscript</sub> text. {% for tarif in tarifs_adhesion %}
This is <u>underlined</u> and this is code: <code>for (;;) { ... }</code>. Finally, <a href="#">this
is a link</a>.</p>
<hr/>
<h2>Heading Level 2</h2>
<h3>Heading Level 3</h3>
<h4>Heading Level 4</h4>
<h5>Heading Level 5</h5>
<h6>Heading Level 6</h6>
<hr/>
<h4>Blockquote</h4>
<blockquote>Fringilla nisl. Donec accumsan interdum nisi, quis tincidunt felis sagittis eget tempus
euismod. Vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis
volutpat ac adipiscing accumsan faucibus. Vestibulum ante ipsum primis in faucibus lorem ipsum dolor
sit amet nullam adipiscing eu felis.
</blockquote>
<h4>Preformatted</h4>
<pre><code>i = 0;
while (!deck.isInOrder()) {
print 'Iteration ' + i;
deck.shuffle();
i++;
}
print 'It took ' + i + ' iterations to sort the deck.';</code></pre>
</section>
<section>
<h3 class="major">Lists</h3>
<h4>Unordered</h4>
<ul>
<li>Dolor pulvinar etiam.</li>
<li>Sagittis adipiscing.</li>
<li>Felis enim feugiat.</li>
</ul>
<h4>Alternate</h4>
<ul class="alt">
<li>Dolor pulvinar etiam.</li>
<li>Sagittis adipiscing.</li>
<li>Felis enim feugiat.</li>
</ul>
<h4>Ordered</h4>
<ol>
<li>Dolor pulvinar etiam.</li>
<li>Etiam vel felis viverra.</li>
<li>Felis enim feugiat.</li>
<li>Dolor pulvinar etiam.</li>
<li>Etiam vel felis lorem.</li>
<li>Felis enim et feugiat.</li>
</ol>
<h4>Icons</h4>
<ul class="icons">
<li><a href="#" class="icon brands fa-twitter"><span class="label">Twitter</span></a></li>
<li><a href="#" class="icon brands fa-facebook-f"><span class="label">Facebook</span></a></li>
<li><a href="#" class="icon brands fa-instagram"><span class="label">Instagram</span></a></li>
<li><a href="#" class="icon brands fa-github"><span class="label">Github</span></a></li>
</ul>
<h4>Actions</h4>
<ul class="actions"> <ul class="actions">
<li><a href="#" class="button primary">Default</a></li> <li><a id="{{ tarif.name | slugify }}" href="#paiementadhesionenligne"
<li><a href="#" class="button">Default</a></li> class="button primary field">{{ tarif.name }} {{ tarif.tarif }}€</a></li>
</ul> </ul>
<ul class="actions stacked"> {% endfor %}
<li><a href="#" class="button primary">Default</a></li> <h4>Payer à l'acceuil de l'association avec un vrai humain :</h4>
<li><a href="#" class="button">Default</a></li>
</ul>
</section>
<section>
<h3 class="major">Table</h3>
<h4>Default</h4>
<div class="table-wrapper">
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item One</td>
<td>Ante turpis integer aliquet porttitor.</td>
<td>29.99</td>
</tr>
<tr>
<td>Item Two</td>
<td>Vis ac commodo adipiscing arcu aliquet.</td>
<td>19.99</td>
</tr>
<tr>
<td>Item Three</td>
<td> Morbi faucibus arcu accumsan lorem.</td>
<td>29.99</td>
</tr>
<tr>
<td>Item Four</td>
<td>Vitae integer tempus condimentum.</td>
<td>19.99</td>
</tr>
<tr>
<td>Item Five</td>
<td>Ante turpis integer aliquet porttitor.</td>
<td>29.99</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2"></td>
<td>100.00</td>
</tr>
</tfoot>
</table>
</div>
<h4>Alternate</h4>
<div class="table-wrapper">
<table class="alt">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item One</td>
<td>Ante turpis integer aliquet porttitor.</td>
<td>29.99</td>
</tr>
<tr>
<td>Item Two</td>
<td>Vis ac commodo adipiscing arcu aliquet.</td>
<td>19.99</td>
</tr>
<tr>
<td>Item Three</td>
<td> Morbi faucibus arcu accumsan lorem.</td>
<td>29.99</td>
</tr>
<tr>
<td>Item Four</td>
<td>Vitae integer tempus condimentum.</td>
<td>19.99</td>
</tr>
<tr>
<td>Item Five</td>
<td>Ante turpis integer aliquet porttitor.</td>
<td>29.99</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2"></td>
<td>100.00</td>
</tr>
</tfoot>
</table>
</div>
</section>
<section>
<h3 class="major">Buttons</h3>
<ul class="actions"> <ul class="actions">
<li><a href="#" class="button primary">Primary</a></li> <li><a href="#" class="button primary field">CONTINUER</a></li>
<li><a href="#" class="button">Default</a></li>
</ul> </ul>
<ul class="actions"> {% endif %}
<li><a href="#" class="button">Default</a></li> {% endif %}
<li><a href="#" class="button small">Small</a></li> </article>
</ul>
<ul class="actions">
<li><a href="#" class="button primary icon solid fa-download">Icon</a></li>
<li><a href="#" class="button icon solid fa-download">Icon</a></li>
</ul>
<ul class="actions">
<li><span class="button primary disabled">Disabled</span></li>
<li><span class="button disabled">Disabled</span></li>
</ul>
</section>
<section> <article id="paiementadhesionenligne">
<h3 class="major">Form</h3> <h2 class="major">Paiement en ligne</h2>
{% if messages %}
{% for message in messages %}
<h3>{{ message }}</h3>
{% endfor %}
{% endif %}
<h3>Adhésion : <span id="text_name_adhesion"></span> <span id="text_tarif_adhesion"></span></h3>
<form method="post" action="#"> <form method="post" action="#">
{% csrf_token %}
<div class="fields"> <div class="fields">
<div class="field half"> <div class="field" style="display: none">
<label for="demo-name">Name</label> {% if email %}
<input type="text" name="demo-name" id="demo-name" value="" placeholder="Jane Doe"/> <input type="email" name="email" id="email_paiement_adhesion" required="True"
value="{{ email }}"/>
{% else %}
<input type="email" name="email" id="email" required="True"/>
{% endif %}
</div> </div>
<div class="field half">
<label for="demo-email">Email</label> <div class="field" style="display: none">
<input type="email" name="demo-email" id="demo-email" value="" <input id="montant_adhesion" type="number" step="any" name="montant_adhesion"
placeholder="jane@untitled.tld"/> required="True"/>
</div> </div>
<div class="field"> <div class="field">
<label for="demo-category">Category</label> <h4>Voulez vous recharger votre carte en même temps ? Laissez vide si non.</h4>
<select name="demo-category" id="demo-category"> <label for="montant_recharge">Recharge cashless (€) :</label>
<option value="">-</option> <input id="montant_recharge" type="number" step="any" name="montant_recharge" />
<option value="1">Manufacturing</option>
<option value="1">Shipping</option>
<option value="1">Administration</option>
<option value="1">Human Resources</option>
</select>
</div>
<div class="field half">
<input type="radio" id="demo-priority-low" name="demo-priority" checked>
<label for="demo-priority-low">Low</label>
</div>
<div class="field half">
<input type="radio" id="demo-priority-high" name="demo-priority">
<label for="demo-priority-high">High</label>
</div>
<div class="field half">
<input type="checkbox" id="demo-copy" name="demo-copy">
<label for="demo-copy">Email me a copy</label>
</div>
<div class="field half">
<input type="checkbox" id="demo-human" name="demo-human" checked>
<label for="demo-human">Not a robot</label>
</div>
<div class="field">
<label for="demo-message">Message</label>
<textarea name="demo-message" id="demo-message" placeholder="Enter your message"
rows="6"></textarea>
</div> </div>
</div> </div>
<ul class="actions"> <ul class="actions">
<li><input type="submit" value="Send Message" class="primary"/></li> <li><input type="submit" value="Payer" class="primary"/></li>
<li><input type="reset" value="Reset"/></li>
</ul> </ul>
</form> </form>
</section>
</article> </article>
<article id="erreurpaiement">
<h2 class="major">ERREUR</h2>
<h3>Le paiement n'a pas fonctionné.</h3>
<h4>Vérifiez votre moyen de paiement ou contacter un administrateur</h4>
{% if messages %}
{% for message in messages %}
<h3>{{ message }}</h3>
{% endfor %}
{% endif %}
<ul class="actions">
<li><a href="#historique" class="button primary">Voir l'historique</a></li>
</ul>
</article>
<article id="erreur">
<h2 class="major">ERREUR</h2>
<h3>Oups, Quelque chose s'est mal passé.</h3>
{% if messages %}
{% for message in messages %}
<h3>{{ message }}</h3>
{% endfor %}
{% endif %}
</article>
</div> </div>
<!-- Footer --> <!-- Footer -->
@ -492,5 +341,57 @@ print 'It took ' + i + ' iterations to sort the deck.';</code></pre>
<script src="{% static 'html5up-dimension/assets/js/util.js' %}"></script> <script src="{% static 'html5up-dimension/assets/js/util.js' %}"></script>
<script src="{% static 'html5up-dimension/assets/js/main.js' %}"></script> <script src="{% static 'html5up-dimension/assets/js/main.js' %}"></script>
{# Script qui n'affiche que les champs dont nous avons besoin lors de l'adhésion #}
<script type="text/javascript">
document.getElementById("knew_text").hidden = true;
{% if messages %}
{% for message in messages %}
{% if message.extra_tags == 'email' %}
document.getElementById("adhesion_email").value = "{{ message }}";
{% endif %}
{% if message.extra_tags == 'name' %}
document.getElementById("adhesion_name").hidden = true;
document.getElementById("name").readOnly = true;
document.getElementById("name").value = "connu";
document.getElementById("knew_text").textContent += "votre nom,";
document.getElementById("knew_text").hidden = false;
{% endif %}
{% if message.extra_tags == 'prenom' %}
document.getElementById("adhesion_prenom").hidden = true;
document.getElementById("prenom").readOnly = true;
document.getElementById("prenom").value = "connu";
document.getElementById("knew_text").textContent += "votre prénom,";
document.getElementById("knew_text").hidden = false;
{% endif %}
{% if message.extra_tags == 'tel' %}
document.getElementById("adhesion_tel").hidden = true;
document.getElementById("tel").readOnly = true;
document.getElementById("tel").value = "connu";
document.getElementById("knew_text").textContent += "votre numéro de téléphone,";
document.getElementById("knew_text").hidden = false;
{% endif %}
{% endfor %}
{% endif %}
</script>
{#Script pour remplir la page d'adhésion de paiement#}
<script>
{% for tarif in tarifs_adhesion %}
document.getElementById('{{ tarif.name | slugify }}').onclick = function () {
console.log('{{ tarif.name | slugify }}')
document.getElementById("montant_adhesion").value = "{{ tarif.tarif }}";
document.getElementById("text_name_adhesion").textContent = "{{ tarif.name }}";
document.getElementById("text_tarif_adhesion").textContent = "{{ tarif.tarif }}€";
}
{% endfor %}
</script>
</body> </body>
</html> </html>

View File

@ -1,7 +1,7 @@
from datetime import datetime from datetime import datetime
import requests, json import requests, json
from django.contrib.auth import get_user_model from django.contrib import messages
from django.db import connection from django.db import connection
from django.http import HttpResponseRedirect, HttpResponse, Http404 from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render from django.shortcuts import render
@ -13,11 +13,10 @@ import stripe
# Create your views here. # Create your views here.
from django.views import View from django.views import View
from rest_framework import status from rest_framework import status
from rest_framework.response import Response
from AuthBillet.models import TibilletUser, HumanUser from BaseBillet.models import Configuration, Article, TarifsAdhesion, LigneArticle
from BaseBillet.models import Configuration, Article
from PaiementStripe.models import Paiement_stripe from PaiementStripe.models import Paiement_stripe
from PaiementStripe.views import creation_checkout_stripe
from QrcodeCashless.models import CarteCashless from QrcodeCashless.models import CarteCashless
import logging import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -47,6 +46,11 @@ class gen_one_bisik(View):
class index_scan(View): class index_scan(View):
template_name = "html5up-dimension/index.html" template_name = "html5up-dimension/index.html"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.carte = None
self.adhesion = None
def check_carte_serveur_cashless(self, uuid): def check_carte_serveur_cashless(self, uuid):
configuration = Configuration.get_solo() configuration = Configuration.get_solo()
# on questionne le serveur cashless pour voir si la carte existe : # on questionne le serveur cashless pour voir si la carte existe :
@ -104,6 +108,8 @@ class index_scan(View):
request, request,
self.template_name, self.template_name,
{ {
'tarifs_adhesion': TarifsAdhesion.objects.all(),
'adhesion_obligatoire': configuration.adhesion_obligatoire,
'assets': json_reponse.get('assets'), 'assets': json_reponse.get('assets'),
'total_monnaie': json_reponse.get('total_monnaie'), 'total_monnaie': json_reponse.get('total_monnaie'),
'history': json_reponse.get('history'), 'history': json_reponse.get('history'),
@ -140,98 +146,112 @@ class index_scan(View):
data = request.POST data = request.POST
print(data) print(data)
# c'est une recharge # c'est une recharge
if data.get('montant_recharge') : if data.get('montant_recharge') and data.get('email'):
# montant_recharge = data.get('montant_recharge')
reponse_server_cashless = self.check_carte_serveur_cashless(carte.uuid)
montant_recharge = float("{0:.2f}".format(float(data.get('montant_recharge')))) montant_recharge = float("{0:.2f}".format(float(data.get('montant_recharge'))))
configuration = Configuration.get_solo() if montant_recharge > 0:
if reponse_server_cashless.status_code == 200 and \ # reponse_server_cashless = self.check_carte_serveur_cashless(carte.uuid)
montant_recharge > 0: # configuration = Configuration.get_solo()
User = get_user_model()
user_recharge, created = User.objects.get_or_create(
email=data.get('email'))
if created:
user_recharge: HumanUser
user_recharge.client_source = connection.tenant
user_recharge.client_achat.add(connection.tenant)
user_recharge.is_active = False
else:
user_recharge.client_achat.add(connection.tenant)
user_recharge.save()
art, created = Article.objects.get_or_create( art, created = Article.objects.get_or_create(
name="Recharge Stripe", name="Recharge Carte",
prix="1", prix=1,
publish=False, publish=False,
categorie_article=Article.RECHARGE_CASHLESS,
) )
ligne_article = LigneArticle.objects.create(
article = art,
qty = montant_recharge,
)
metadata = { metadata = {
'recharge_carte_uuid': str(carte.uuid), 'recharge_carte_uuid': str(carte.uuid),
'recharge_carte_montant': str(montant_recharge), 'recharge_carte_montant': str(montant_recharge),
} }
metadata_json = json.dumps(metadata)
paiementStripe = Paiement_stripe.objects.create( new_checkout_session = creation_checkout_stripe(
user=user_recharge, email_paiement = data.get('email'),
detail=f"{art.name}", liste_ligne_article = [ligne_article,],
total=montant_recharge, metadata = metadata,
metadata_stripe=metadata_json, absolute_domain = request.build_absolute_uri().partition('/qr')[0],
) )
absolute_domain = request.build_absolute_uri().partition('/qr')[0] if new_checkout_session.is_valid() :
print(new_checkout_session.checkout_session.stripe_id)
return new_checkout_session.redirect_to_stripe()
if configuration.stripe_mode_test: # c'est la première étape de l'adhésion
stripe.api_key = configuration.stripe_test_api_key elif data.get('email') \
and not data.get('prenom') \
and not data.get('prenom') \
and not data.get('tel') :
sess = requests.Session()
configuration = Configuration.get_solo()
r = sess.post(
f'{configuration.server_cashless}/api/billetterie_qrcode_adhesion',
headers={
'Authorization': f'Api-Key {configuration.key_cashless}'
},
data={
'email': data.get('email'),
'uuid_carte': carte.uuid,
})
sess.close()
# nouveau membre crée avec uniquqment l'email on demande la suite.
if r.status_code in (201, 204) :
messages.success(request, f"{data.get('email')}", extra_tags='email')
return HttpResponseRedirect(f'#demande_nom_prenom_tel')
#partial information :
elif r.status_code == 206:
partial = json.loads(r.text)
messages.success(request, f"{data.get('email')}", extra_tags='email')
if partial.get('name'):
messages.success(request, f"Email déja connu. Name déja connu", extra_tags='name')
if partial.get('prenom'):
messages.success(request, f"Email déja connu. prenom déja connu", extra_tags='prenom')
if partial.get('tel'):
messages.success(request, f"Email déja connu. tel déja connu", extra_tags='tel')
return HttpResponseRedirect(f'#demande_nom_prenom_tel')
else: else:
stripe.api_key = configuration.stripe_api_key messages.error(request, f'Erreur {r.status_code} {r.text}')
return HttpResponseRedirect(f'#erreur')
checkout_session = stripe.checkout.Session.create( # suite de l'adhesion
customer_email=f'{user_recharge.email}', elif data.get('email') and data.get('name') and data.get('prenom') and data.get('tel'):
line_items=[{ sess = requests.Session()
'price_data': { configuration = Configuration.get_solo()
'currency': 'eur', r = sess.post(
f'{configuration.server_cashless}/api/billetterie_qrcode_adhesion',
'product_data': { headers={
'name': 'Recharge Cashless', 'Authorization': f'Api-Key {configuration.key_cashless}'
"images": [f'{carte.detail.img_url}', ],
}, },
'unit_amount': int("{0:.2f}".format(montant_recharge).replace('.', '')), data={
}, 'prenom': data.get('prenom'),
'quantity': 1, 'name': data.get('name'),
'email': data.get('email'),
'tel': data.get('tel'),
'uuid_carte': carte.uuid,
})
}], sess.close()
payment_method_types=[
'card',
],
mode='payment',
metadata=metadata,
success_url=f'{absolute_domain}/stripe/return/{paiementStripe.uuid}',
cancel_url=f'{absolute_domain}/stripe/return/{paiementStripe.uuid}',
# submit_type='Go go go',
client_reference_id=f"{data.get('numero_carte_cashless')}",
)
print(checkout_session.id) # nouveau membre crée, on demande la suite.
paiementStripe.id_stripe = checkout_session.id if r.status_code == 202 :
paiementStripe.status = Paiement_stripe.PENDING messages.success(request, f"Merci ! Membre créé et carte liée.")
paiementStripe.save()
return HttpResponseRedirect(checkout_session.url) return HttpResponseRedirect(f'#adhesionsuccess')
else :
messages.error(request, f'Erreur {r.status_code} {r.text}')
return HttpResponseRedirect(f'#erreur')
elif data.get('prenom') \
and data.get('name') \
and data.get('email') \
and data.get('tel'):
print("adhésion !")
absolute_domain = request.build_absolute_uri().partition('/qr')[0]
return HttpResponseRedirect(f'{absolute_domain}/qr/{carte.uuid}#adhesionsuccess')
def postPaimentRecharge(paiementStripe: Paiement_stripe, request): def postPaimentRecharge(paiementStripe: Paiement_stripe, request):
absolute_domain = request.build_absolute_uri().partition('/stripe/return')[0]
if paiementStripe.status == Paiement_stripe.PAID: if paiementStripe.status == Paiement_stripe.PAID:
metadata_db_json = paiementStripe.metadata_stripe metadata_db_json = paiementStripe.metadata_stripe
@ -273,10 +293,10 @@ def postPaimentRecharge(paiementStripe: Paiement_stripe, request):
paiementStripe.status = Paiement_stripe.VALID paiementStripe.status = Paiement_stripe.VALID
paiementStripe.save() paiementStripe.save()
return HttpResponseRedirect(f'{absolute_domain}/qr/{uuid_carte}#success') return HttpResponseRedirect(f'#success')
elif paiementStripe.status == Paiement_stripe.VALID: elif paiementStripe.status == Paiement_stripe.VALID:
# Le paiement a bien été accepté par le passé et envoyé au serveur cashless. messages.success(request, f"Le paiement a déja été validé.")
return HttpResponseRedirect(f'{absolute_domain}/qr/{uuid_carte}#historique') return HttpResponseRedirect(f'#historique')
return HttpResponseRedirect(f'{absolute_domain}/qr/{uuid_carte}#error') return HttpResponseRedirect(f'#erreurpaiement')

View File

@ -23,7 +23,8 @@ from Administration.admin_tenant import staff_admin_site
urlpatterns = [ urlpatterns = [
path('jet/', include('jet.urls', 'jet')), # Django JET URLS path('jet/', include('jet.urls', 'jet')), # Django JET URLS
re_path(r'^jet/dashboard/', include('jet.dashboard.urls', 'jet-dashboard')), # Django JET dashboard URLS re_path(r'^jet/dashboard/', include('jet.dashboard.urls', 'jet-dashboard')), # Django JET dashboard URLS
path('admin/', staff_admin_site.urls, name="staff_admin_site"), # path('admin/', staff_admin_site.urls, name="staff_admin_site"),
re_path(r'^admin\/{0,}', staff_admin_site.urls, name="staff_admin_site"),
re_path(r'^auth/', include('djoser.urls')), re_path(r'^auth/', include('djoser.urls')),
re_path(r'^auth/', include('djoser.urls.authtoken')), re_path(r'^auth/', include('djoser.urls.authtoken')),