-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmodels.py
executable file
·4708 lines (4212 loc) · 192 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import logging
import re
import uuid
from datetime import time
from random import randint
import channels.layers
from asgiref.sync import async_to_sync
from autoslug import AutoSlugField
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models import (
Case,
Count,
ExpressionWrapper,
F,
FloatField,
IntegerField,
Max,
OuterRef,
Q,
Subquery,
Sum,
Value,
When,
)
from django.db.models.expressions import RawSQL
from django.db.models.functions import Coalesce
from django.db.models.query import QuerySet
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.urls import reverse
from django.utils import html, timezone
from django.utils.safestring import mark_safe
from django_ses.signals import bounce_received, complaint_received
from easy_thumbnails.fields import ThumbnailerImageField
from location_field.models.plain import PlainLocationField
from markdownfield.models import MarkdownField, RenderedMarkdownField
from markdownfield.validators import VALIDATOR_STANDARD
from pytz import timezone as pytz_timezone
logger = logging.getLogger(__name__)
def nearby_auctions(
latitude,
longitude,
distance=100,
include_already_joined=False,
user=None,
return_slugs=False,
):
"""Return a list of auctions or auction slugs that are within a specified distance of the given location"""
auctions = []
slugs = []
distances = []
locations = (
PickupLocation.objects.annotate(distance=distance_to(latitude, longitude))
.exclude(distance__gt=distance)
.filter(
auction__date_end__gte=timezone.now(),
auction__date_start__lte=timezone.now(),
)
.exclude(auction__promote_this_auction=False)
.exclude(auction__isnull=True)
)
if user:
if user.is_authenticated and not include_already_joined:
locations = locations.exclude(auction__auctiontos__user=user)
locations = locations.exclude(auction__auctionignore__user=user)
elif user and not include_already_joined:
locations = locations.exclude(auction__auctiontos__user=user)
for location in locations:
if location.auction.slug not in slugs:
auctions.append(location.auction)
slugs.append(location.auction.slug)
distances.append(location.distance)
if return_slugs:
return slugs
else:
return auctions, distances
def median_value(queryset, term):
count = queryset.count()
return queryset.values_list(term, flat=True).order_by(term)[int(round(count / 2))]
def add_price_info(qs):
"""Add fields `pre_register_discount`, `your_cut` and `club_cut` to a given Lot queryset."""
if not (isinstance(qs, QuerySet) and qs.model == Lot):
msg = "must be passed a queryset of the Lot model"
raise TypeError(msg)
return qs.annotate(
pre_register_discount=Case(
When(auctiontos_seller__isnull=True, then=Value(0.0)),
When(
added_by=F("user"),
then=F("auctiontos_seller__auction__pre_register_lot_discount_percent"),
),
default=Value(0.0),
output_field=FloatField(),
),
your_cut=ExpressionWrapper(
Case(
When(
Q(auctiontos_seller__isnull=True, winning_price__isnull=False),
then=F("winning_price"),
),
When(
Q(auctiontos_seller__isnull=True, winning_price__isnull=True),
then=Value(0.0),
),
When(donation=True, then=Value(0.0)),
When(
Q(winning_price__isnull=False, active=False),
then=(
(
F("winning_price")
* Case(
When(
auctiontos_seller__is_club_member=True,
then=(
(
100
- F(
"auctiontos_seller__auction__winning_bid_percent_to_club_for_club_members"
)
+ F("pre_register_discount")
)
/ 100
),
),
default=(
(
100
- F("auctiontos_seller__auction__winning_bid_percent_to_club")
+ F("pre_register_discount")
)
/ 100
),
output_field=FloatField(),
)
)
- Case(
When(
auctiontos_seller__is_club_member=True,
then=F("auction__lot_entry_fee_for_club_members"),
),
default=F("auction__lot_entry_fee"),
output_field=FloatField(),
)
)
* (100 - F("partial_refund_percent"))
/ 100,
),
When(
Q(winning_price__isnull=True, active=False),
then=Case(
When(donation=True, then=Value(0.0)),
default=Value(0.0) - F("auctiontos_seller__auction__unsold_lot_fee"),
),
),
default=Value(0.0),
output_field=FloatField(),
),
output_field=FloatField(),
),
club_cut=ExpressionWrapper(
Case(
When(Q(active=False, winning_price__isnull=True), then=Value(0.0)),
When(winning_price__isnull=True, then=Value(0.0)),
default=(F("winning_price") * (100 - F("partial_refund_percent")) / 100) - F("your_cut"),
),
output_field=FloatField(),
),
)
def find_image(name, user, auction):
"""Find an image from the most recent lot with a given name"""
qs = LotImage.objects.filter(
(Q(lot_number__user__userdata__share_lot_images=True) | Q(lot_number__user__isnull=True)),
lot_number__lot_name=name,
lot_number__is_deleted=False,
lot_number__banned=False,
is_primary=True,
lot_number__auction__created_by__pk__in=auction.auction_admins_pks,
).order_by("-lot_number__date_posted")
if user:
image_from_user = qs.filter(lot_number__user=user).first()
if image_from_user:
return image_from_user
return qs.first()
def distance_to(
latitude,
longitude,
unit="miles",
lat_field_name="latitude",
lng_field_name="longitude",
approximate_distance_to=10,
):
"""
GeoDjango has been fustrating with MySQL and Point objects.
This function is a workaound done using raw SQL.
Given a latitude and longitude, it will return raw SQL that can be used to annotate a queryset
The model being annotated must have fields named 'latitude' and 'longitude' for this to work
For example:
qs = model.objects.all()\
.annotate(distance=distance_to(latitude, longitude))\
.order_by('distance')
"""
if unit == "miles":
correction = 0.6213712 # close enough
else:
correction = 1 # km
for i in [
latitude,
longitude,
lat_field_name,
lng_field_name,
approximate_distance_to,
]:
if '"' in str(i) or "'" in str(i):
msg = "invalid character passed to distance_to, possible sql injection risk"
raise TypeError(msg)
# Great circle distance formula, CEILING is used to keep people from triangulating locations
gcd_formula = f"CEILING( 6371 * acos(least(greatest( \
cos(radians({latitude})) * cos(radians({lat_field_name})) \
* cos(radians({lng_field_name}) - radians({longitude})) + \
sin(radians({latitude})) * sin(radians({lat_field_name})) \
, -1), 1)) * {correction} / {approximate_distance_to}) * {approximate_distance_to}"
distance_raw_sql = RawSQL(gcd_formula, ())
# This one works fine when I print qs.query and run the output in SQL but does not work when Django runs the qs
# Seems to be an issue with annotating on related entities
# Injection attacks don't seem possible here because latitude and longitude can only contain a float as set in update_user_location()
# gcd_formula = f"CEILING( 6371 * acos(least(greatest( \
# cos(radians(%s)) * cos(radians({lat_field_name})) \
# * cos(radians({lng_field_name}) - radians(%s)) + \
# sin(radians(%s)) * sin(radians({lat_field_name})) \
# , -1), 1)) * %s / {approximate_distance_to}) * {approximate_distance_to}"
# distance_raw_sql = RawSQL(
# gcd_formula,
# (latitude, longitude, latitude, correction)
# )
return distance_raw_sql
def add_tos_info(qs):
"""Add fields to a given AuctionTOS queryset."""
if not (isinstance(qs, QuerySet) and qs.model == AuctionTOS):
msg = "must be passed a queryset of the AuctionTOS model"
raise TypeError(msg)
return qs.annotate(
lots_bid_actual=Coalesce(
Subquery(
Bid.objects.exclude(is_deleted=True)
.filter(user=OuterRef("user"), lot_number__auction=OuterRef("auction"))
.values("user")
.annotate(count=Count("pk", distinct=True))
.values("count"),
output_field=IntegerField(),
),
0,
),
lots_bid=Case(When(Q(manually_added=True), then=Value(0)), default=F("lots_bid_actual")),
lots_viewed_actual=Coalesce(
Subquery(
PageView.objects.filter(user=OuterRef("user"), lot_number__auction=OuterRef("auction"))
.values("user")
.annotate(count=Count("lot_number", distinct=True))
.values("count"),
output_field=IntegerField(),
),
0,
),
lots_viewed=Case(When(Q(manually_added=True), then=Value(0)), default=F("lots_viewed_actual")),
lots_won=Count("auctiontos_winner", distinct=True),
lots_submitted=Count("auctiontos_seller", distinct=True),
other_auctions=Coalesce(
Subquery(
AuctionTOS.objects.filter(email=OuterRef("email"))
.exclude(id=OuterRef("id"))
.values("email")
.annotate(count=Count("*"))
.values("count"),
output_field=IntegerField(),
),
0,
),
lots_outbid=Case(
When(lots_won__gt=F("lots_bid"), then=0),
default=F("lots_bid") - F("lots_won"),
output_field=IntegerField(),
),
account_age_ms=Case(
When(
Q(manually_added=True),
then=ExpressionWrapper(timezone.now() - F("createdon"), output_field=IntegerField()),
),
default=ExpressionWrapper(timezone.now() - F("user__date_joined"), output_field=IntegerField()),
),
account_age_days=ExpressionWrapper(F("account_age_ms") / 86400000000, output_field=IntegerField()),
other_user_bans_actual=Coalesce(
Subquery(
UserBan.objects.filter(banned_user=OuterRef("user"))
.values("pk")
.annotate(count=Count("*"))
.values("count"),
output_field=IntegerField(),
),
0,
),
other_user_bans=Case(
When(Q(manually_added=True), then=Value(0)),
default=F("other_user_bans_actual"),
),
trust=ExpressionWrapper(
1 * F("lots_bid")
+ 0.2 * F("lots_viewed")
+ 2 * F("lots_won")
+ 2 * F("lots_submitted")
+ 5 * F("other_auctions")
- 2 * F("lots_outbid")
+ 0.01 * F("account_age_days")
- 100 * F("other_user_bans"),
output_field=IntegerField(),
),
)
def add_tos_distance_info(qs):
"""Add a distance_traveled to an auctiontos query"""
if not (isinstance(qs, QuerySet) and qs.model == AuctionTOS):
msg = "must be passed a queryset of the AuctionTOS model"
raise TypeError(msg)
return (
qs.select_related("user__userdata")
.select_related("pickup_location")
.annotate(
new_distance_traveled=Case(
When(Q(manually_added=True), then=Value(-1)),
default=distance_to(
"""`auctions_userdata`.`latitude`""",
"""`auctions_userdata`.`longitude`""",
lat_field_name="""`auctions_pickuplocation`.`latitude`""",
lng_field_name="""`auctions_pickuplocation`.`longitude`""",
approximate_distance_to=1,
),
output_field=IntegerField(),
),
)
)
def guess_category(text):
"""Given some text, look up lots with similar names and make a guess at the category this `text` belongs to based on the category used there"""
keywords = []
words = re.findall("[A-Z|a-z]{3,}", text.lower())
for word in words:
if word not in settings.IGNORE_WORDS:
keywords.append(word)
if not keywords:
return None
lot_qs = (
Lot.objects.exclude(is_deleted=True)
.filter(
category_automatically_added=False,
species_category__isnull=False,
is_deleted=False,
)
.exclude(species_category__name="Uncategorized")
.exclude(auction__promote_this_auction=False)
)
q_objects = Q()
for keyword in keywords:
q_objects |= Q(lot_name__iregex=rf"\b{re.escape(keyword)}\b")
lot_qs = lot_qs.filter(q_objects)
# category = lot_qs.values('species_category').annotate(count=Count('species_category')).order_by('-count').first()
# attempting this as a single-shot query is extremely difficult to debug
categories = {}
for lot in lot_qs:
matches = 0
for keyword in keywords:
if keyword in lot.lot_name.lower():
matches += 1
category_total = categories.get(lot.species_category.pk, 0)
categories[lot.species_category.pk] = category_total + matches
sorted_categories = sorted(categories.items(), key=lambda x: x[1], reverse=True)
for key, value in sorted_categories:
logger.debug("%s, %s", Category.objects.filter(pk=key).first(), value)
return Category.objects.filter(pk=key).first()
return None
class BlogPost(models.Model):
"""
A simple markdown blog. At the moment, I don't feel that adding a full CMS is necessary
"""
title = models.CharField(max_length=255)
slug = AutoSlugField(populate_from="title", unique=True)
body = MarkdownField(
rendered_field="body_rendered",
validator=VALIDATOR_STANDARD,
blank=True,
null=True,
)
body_rendered = RenderedMarkdownField(blank=True, null=True)
date_posted = models.DateTimeField(auto_now_add=True)
extra_js = models.TextField(max_length=16000, null=True, blank=True)
def __str__(self):
return self.title
class Location(models.Model):
"""
Allows users to specify a region -- USA, Canada, South America, etc.
"""
name = models.CharField(max_length=255)
def __str__(self):
return str(self.name)
class GeneralInterest(models.Model):
"""Clubs and products belong to a general interest"""
name = models.CharField(max_length=255)
def __str__(self):
return str(self.name)
class Club(models.Model):
"""Users can self-select which club they belong to"""
name = models.CharField(max_length=255)
abbreviation = models.CharField(max_length=255, blank=True, null=True)
homepage = models.CharField(max_length=255, blank=True, null=True)
facebook_page = models.CharField(max_length=255, blank=True, null=True)
contact_email = models.CharField(max_length=255, blank=True, null=True)
date_contacted = models.DateTimeField(blank=True, null=True)
date_contacted_for_in_person_auctions = models.DateTimeField(blank=True, null=True)
notes = models.CharField(max_length=300, blank=True, null=True)
notes.help_text = "Only visible in the admin site, never made public"
interests = models.ManyToManyField(GeneralInterest, blank=True)
active = models.BooleanField(default=True)
latitude = models.FloatField(blank=True, null=True)
longitude = models.FloatField(blank=True, null=True)
location = models.CharField(max_length=500, blank=True, null=True)
location.help_text = "Search Google maps with this address"
location_coordinates = PlainLocationField(based_fields=["location"], blank=True, null=True, verbose_name="Map")
class Meta:
ordering = ["name"]
def __str__(self):
return str(self.name)
class Category(models.Model):
"""Picklist of species. Used for product, lot, and interest"""
name = models.CharField(max_length=255)
name_on_label = models.CharField(max_length=255, default="")
def __str__(self):
return str(self.name)
class Meta:
verbose_name_plural = "Categories"
ordering = ["name"]
class Product(models.Model):
"""A species or item in the auction
This is not really used much anymore,
it was intended to exist for every possible species of fish, but that's just too much for the scope of this project"""
common_name = models.CharField(max_length=255)
common_name.help_text = "The name usually used to describe this species"
scientific_name = models.CharField(max_length=255, blank=True)
scientific_name.help_text = "Latin name used to describe this species"
breeder_points = models.BooleanField(default=True)
category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
def __str__(self):
return f"{self.common_name} ({self.scientific_name})"
class Meta:
verbose_name_plural = "Products and species"
class Auction(models.Model):
"""An auction is a collection of lots"""
title = models.CharField("Auction name", max_length=255, blank=False, null=False)
title.help_text = "This is the name people will see when joining your auction"
slug = AutoSlugField(populate_from="title", unique=True)
is_online = models.BooleanField(default=True)
is_online.help_text = "Is this is an online auction with in-person pickup at one or more locations?"
sealed_bid = models.BooleanField(default=False)
sealed_bid.help_text = "Users won't be able to see what the current bid is"
lot_entry_fee = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(10)])
lot_entry_fee.help_text = "The amount the seller will be charged if a lot sells"
unsold_lot_fee = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(10)])
unsold_lot_fee.help_text = "The amount the seller will be charged if their lot doesn't sell"
winning_bid_percent_to_club = models.PositiveIntegerField(
default=0, validators=[MinValueValidator(0), MaxValueValidator(100)]
)
winning_bid_percent_to_club.help_text = (
"In addition to the Lot entry fee, this percent of the winning price will be taken by the club"
)
pre_register_lot_discount_percent = models.PositiveIntegerField(
default=0, validators=[MinValueValidator(0), MaxValueValidator(100)]
)
pre_register_lot_discount_percent.help_text = "Decrease the club cut if users add lots through this website"
pre_register_lot_entry_fee_discount = models.PositiveIntegerField(
default=0, validators=[MinValueValidator(0), MaxValueValidator(10)]
)
pre_register_lot_entry_fee_discount.help_text = (
"Decrease the lot entry fee by this amount if users add lots through this website"
)
force_donation_threshold = models.PositiveIntegerField(
default=None,
blank=True,
null=True,
validators=[MinValueValidator(0), MaxValueValidator(10)],
verbose_name="Donation threshold",
)
force_donation_threshold.help_text = (
"Most auctions should leave this blank. Force lots to be a donation if they sell for this amount or less."
)
date_posted = models.DateTimeField(auto_now_add=True)
date_start = models.DateTimeField("Auction start date")
date_start.help_text = "Bidding starts on this date"
lot_submission_start_date = models.DateTimeField("Lot submission opens", null=True, blank=True)
lot_submission_start_date.help_text = "Users can submit (but not bid on) lots on this date"
lot_submission_end_date = models.DateTimeField("Lot submission ends", null=True, blank=True)
date_end = models.DateTimeField("Bidding end date", blank=True, null=True)
date_end.help_text = "Bidding will end on this date. If last-minute bids are placed, bidding can go up to 1 hour past this time on those lots."
date_online_bidding_starts = models.DateTimeField("Online bidding opens", blank=True, null=True)
date_online_bidding_ends = models.DateTimeField("Online bidding ends", blank=True, null=True)
watch_warning_email_sent = models.BooleanField(default=False)
invoiced = models.BooleanField(default=False)
created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)
location = models.CharField(max_length=300, null=True, blank=True)
location.help_text = "State or region of this auction"
summernote_description = models.TextField(verbose_name="Rules", default="", blank=True)
# notes = MarkdownField(
# rendered_field="notes_rendered",
# validator=VALIDATOR_STANDARD,
# blank=True,
# null=True,
# verbose_name="Rules",
# default="",
# )
# notes.help_text = "To add a link: [Link text](https://www.google.com)"
# notes_rendered = RenderedMarkdownField(blank=True, null=True)
code_to_add_lots = models.CharField(max_length=255, blank=True, null=True)
code_to_add_lots.help_text = (
"This is like a password: People in your club will enter this code to put their lots in this auction"
)
lot_promotion_cost = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1)])
first_bid_payout = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0)])
first_bid_payout.help_text = "This is a feature to encourage bidding. Give each bidder this amount, for free. <a href='/blog/encouraging-participation/' target='_blank'>More information</a>"
promote_this_auction = models.BooleanField(default=True)
promote_this_auction.help_text = "Show this to everyone in the list of auctions. <span class='text-warning'>Uncheck if this is a test or private auction</span>."
is_chat_allowed = models.BooleanField(default=True)
max_lots_per_user = models.PositiveIntegerField(null=True, blank=True, validators=[MaxValueValidator(100)])
max_lots_per_user.help_text = "A user won't be able to add more than this many lots to this auction"
allow_additional_lots_as_donation = models.BooleanField(default=True)
allow_additional_lots_as_donation.help_text = "If you don't set max lots per user, this has no effect"
email_first_sent = models.BooleanField(default=False)
email_second_sent = models.BooleanField(default=False)
email_third_sent = models.BooleanField(default=False)
email_fourth_sent = models.BooleanField(default=False)
email_fifth_sent = models.BooleanField(default=False)
reprint_reminder_sent = models.BooleanField(default=False)
make_stats_public = models.BooleanField(default=True)
make_stats_public.help_text = "Allow any user who has a link to this auction's stats to see them. Uncheck to only allow the auction creator to view stats"
bump_cost = models.PositiveIntegerField(blank=True, default=1, validators=[MinValueValidator(1)])
bump_cost.help_text = "The amount a user will be charged each time they move a lot to the top of the list"
use_categories = models.BooleanField(default=True, verbose_name="Use category field")
use_categories.help_text = "Not shown on the bulk add lots form. Check to use categories like Cichlids, Livebearers, etc. This option is required if you want to promote your auction on the main auctions list."
is_deleted = models.BooleanField(default=False)
ONLINE_BIDDING_OPTIONS = (
("allow", "Allow buy now and bidding"),
("buy_now_only", "Allow buy now only"),
("disable", "No online bidding"),
)
online_bidding = models.CharField(max_length=20, choices=ONLINE_BIDDING_OPTIONS, blank=False, default="allow")
# allow_bidding_on_lots = models.BooleanField(default=True, verbose_name="Allow online bidding")
only_approved_sellers = models.BooleanField(default=False)
only_approved_sellers.help_text = "Require admin approval before users can add lots. This will not change permissions for users that have already joined."
only_approved_bidders = models.BooleanField(default=False)
only_approved_bidders.help_text = "Require admin approval before users can bid. This only applies to new users: Users that you manually add and users who have a paid invoice in a past auctions will be allowed to bid."
require_phone_number = models.BooleanField(default=False)
require_phone_number.help_text = "Require users to have entered a phone number before they can join this auction"
email_users_when_invoices_ready = models.BooleanField(default=True)
invoice_payment_instructions = models.CharField(max_length=255, blank=True, null=True, default="")
invoice_payment_instructions.help_text = "Shown to the user on their invoice. For example, 'You will receive a seperate PayPal invoice with payment instructions'"
invoice_rounding = models.BooleanField(default=True)
invoice_rounding.help_text = (
"Round invoice totals to whole dollar amounts. Check if you plan to accept cash payments."
)
minimum_bid = models.PositiveIntegerField(default=2, validators=[MinValueValidator(1)])
minimum_bid.help_text = "Lowest price any lot will be sold for"
lot_entry_fee_for_club_members = models.PositiveIntegerField(
default=0, validators=[MinValueValidator(0), MaxValueValidator(10)]
)
lot_entry_fee_for_club_members.help_text = (
"Used instead of the standard entry fee, when you designate someone as a club member"
)
winning_bid_percent_to_club_for_club_members = models.PositiveIntegerField(
default=0, validators=[MinValueValidator(0), MaxValueValidator(100)]
)
winning_bid_percent_to_club_for_club_members.help_text = (
"Used instead of the standard split, when you designate someone as a club member"
)
SET_LOT_WINNER_URLS = (
("", "Standard, bidder number/lot number only"),
("presentation", "Show a picture of the lot"),
("autocomplete", "Autocomplete, search by name or bidder number"),
)
set_lot_winners_url = models.CharField(
max_length=20, choices=SET_LOT_WINNER_URLS, blank=True, default="presentation"
)
set_lot_winners_url.verbose_name = "Set lot winners"
BUY_NOW_CHOICES = (
("disable", "Don't allow"),
("allow", "Allow"),
("required", "Required for all lots"),
)
buy_now = models.CharField(max_length=20, choices=BUY_NOW_CHOICES, default="allow")
buy_now.help_text = "Allow lots to be sold without bidding, for a user-specified price."
RESERVE_CHOICES = (
("disable", "Don't allow"),
("allow", "Allow"),
("required", "Required for all lots"),
)
reserve_price = models.CharField(
max_length=20,
choices=RESERVE_CHOICES,
default="allow",
verbose_name="Seller set minimum bid",
)
reserve_price.help_text = "Allow users to set a minimum bid on their lots"
tax = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0)])
tax.help_text = "Added to invoices for all won lots"
advanced_lot_adding = models.BooleanField(default=False)
advanced_lot_adding.help_text = "Show lot number, quantity and description fields when bulk adding lots"
use_quantity_field = models.BooleanField(default=False, blank=True)
custom_checkbox_name = models.CharField(
max_length=50, default="", blank=True, null=True, verbose_name="Custom checkbox name"
)
custom_checkbox_name.help_text = "Shown when users add lots"
use_reference_link = models.BooleanField(default=True, blank=True)
use_reference_link.help_text = "Not shown on the bulk add lots form. Especially handy for videos."
use_description = models.BooleanField(default=True, blank=True)
use_description.help_text = "Not shown on the bulk add lots form"
use_donation_field = models.BooleanField(default=True, blank=True)
use_i_bred_this_fish_field = models.BooleanField(default=True, blank=True, verbose_name="Use Breeder Points field")
use_custom_checkbox_field = models.BooleanField(default=False, blank=True)
use_custom_checkbox_field.help_text = "Optional information such as CARES, native species, difficult to keep, etc."
CUSTOM_CHOICES = (
("disable", "Off"),
("allow", "Optional"),
("required", "Required for all lots"),
)
custom_field_1 = models.CharField(
max_length=20,
choices=CUSTOM_CHOICES,
default="disable",
verbose_name="Custom field for lots",
)
custom_field_1.help_text = (
"Additional information on the label such as notes, scientific name, collection location..."
)
custom_field_1_name = models.CharField(
max_length=50, default="Notes", blank=True, null=True, verbose_name="Custom field name"
)
custom_field_1_name.help_text = "What's the custom field used for? This is shown to users"
allow_bulk_adding_lots = models.BooleanField(default=True)
allow_bulk_adding_lots.help_text = "Uncheck to force users to add lots one at a time. Turning this off encourage more detail and pictures about each lot, but makes adding lots take longer. Admins can always bulk add lots for other users."
copy_users_when_copying_this_auction = models.BooleanField(default=False)
copy_users_when_copying_this_auction.help_text = "Save yourself a few clicks when bulk importing users"
extra_promo_text = models.CharField(max_length=50, default="", blank=True, null=True)
extra_promo_link = models.URLField(blank=True, null=True)
allow_deleting_bids = models.BooleanField(default=False, blank=True)
allow_deleting_bids.help_text = "Allow users to delete their own bids until the auction ends"
auto_add_images = models.BooleanField("Automatically add images to lots", default=True, blank=True)
auto_add_images.help_text = (
"Images taken from older lots with the same name in any auctions created by you or other admins"
)
message_users_when_lots_sell = models.BooleanField(default=True, blank=True)
message_users_when_lots_sell.help_text = "Recommended if you are recording winners as lots sell. When you enter a lot number on the set lot winners screen, send a notification to any users watching that lot"
label_print_fields = models.CharField(
max_length=1000,
blank=True,
null=True,
default="qr_code,lot_name,min_bid_label,buy_now_label,quantity_label,seller_name,donation_label,custom_field_1,i_bred_this_fish_label,custom_checkbox_label",
)
use_seller_dash_lot_numbering = models.BooleanField(default=False, blank=True)
use_seller_dash_lot_numbering.help_text = "Include the seller's bidder number with the lot number. This option is not recommended as users find it confusing."
def __str__(self):
result = self.title
if "auction" not in self.title.lower():
result += " auction"
if not self.title.lower().startswith("the "):
result = "The " + result
return result
def delete(self, *args, **kwargs):
self.is_deleted = True
self.save()
def save(self, *args, **kwargs):
if self.date_start.year < 2000:
current_year = timezone.now().year
self.date_start = self.date_start.replace(year=current_year)
super().save(*args, **kwargs)
def find_user(self, name="", email="", exclude_pk=None):
"""Used for duplicate checks and when adding users to an auction
Returns an AuctionTOS instance or None"""
qs = AuctionTOS.objects.filter(auction__pk=self.pk)
if not name and not email:
return None
if exclude_pk:
qs = qs.exclude(pk=exclude_pk)
if email:
email_search = qs.filter(email=email).first()
if email_search:
return email_search
if name:
from .filters import AuctionTOSFilter
name_search = AuctionTOSFilter.generic(self, qs, name, match_names_only=True).first()
if name_search:
return name_search
return None
@property
def estimate_end(self):
try:
if self.is_online:
return None
expected_sell_percent = 95
lots_to_use_for_estimate = 10
percent_complete = self.total_unsold_lots / self.total_lots
if percent_complete > expected_sell_percent:
return None
lots = self.lots_qs.exclude(date_end__isnull=True).order_by("-date_end")[:lots_to_use_for_estimate]
if lots.count() < lots_to_use_for_estimate:
return None
first_lot = lots[0]
last_lot = lots[lots_to_use_for_estimate - 1]
time_diff = first_lot.date_end - last_lot.date_end
elapsed_seconds = time_diff.total_seconds()
rate = elapsed_seconds / lots_to_use_for_estimate
mintues_to_end = int(self.total_unsold_lots * rate / 60)
if mintues_to_end < 15:
return None
return mintues_to_end
except Exception as e:
logger.error(e)
return None
@property
def location_qs(self):
"""All locations associated with this auction"""
return PickupLocation.objects.filter(auction=self.pk).order_by("name")
@property
def physical_location_qs(self):
"""Find all non-default locations"""
# I am not sure why we were excluding the default location, but it doesn't make sense to
# return self.location_qs.exclude(Q(pickup_by_mail=True)|Q(is_default=True))
return self.location_qs.exclude(pickup_by_mail=True)
@property
def location_with_location_qs(self):
"""Find all locations that have coordinates - useful to see if there's an actual location associated with this auction. By default, auctions get a location with no coordinates added"""
return self.physical_location_qs.exclude(latitude=0, longitude=0)
@property
def number_of_locations(self):
"""The number of physical locations this auction has"""
return self.physical_location_qs.count()
@property
def all_location_count(self):
"""All locations, even mail"""
return self.location_qs.count()
@property
def allow_mailing_lots(self):
if self.location_qs.filter(pickup_by_mail=True).first():
return True
return False
@property
def auction_type(self):
"""Returns whether this is an online, in-person, or hybrid auction for use in tooltips and templates. See also auction_type_as_str for a friendly display version"""
number_of_locations = self.number_of_locations
if self.is_online and number_of_locations == 1:
return "online_one_location"
if self.is_online and number_of_locations > 1:
return "online_multi_location"
if self.is_online and number_of_locations == 0:
return "online_no_location"
if not self.is_online and number_of_locations == 1:
return "inperson_one_location"
if not self.is_online and number_of_locations > 1:
return "inperson_multi_location"
return "unknown"
@property
def auction_type_as_str(self):
"""Returns friendly string of whether this is an online, in-person, or hybrid auction"""
auction_type = self.auction_type
if auction_type == "online_one_location":
return "online auction with in-person pickup"
if auction_type == "online_multi_location":
return "online auction with in-person pickup at multiple locations"
if auction_type == "online_no_location":
return "online auction with no specified pickup location"
if auction_type == "inperson_one_location":
return "in-person auction"
if auction_type == "inperson_multi_location":
return "in person auction with lot delivery to additional locations"
return "unknown auction type"
@property
def template_promo_info(self):
if not self.extra_promo_text or self.closed or self.in_person_closed:
return ""
if self.extra_promo_link:
return mark_safe(
f"<br><a class='magic text-warning' href='{self.extra_promo_link}'>{self.extra_promo_text}</a>"
)
return mark_safe(f"<br><span class='magic text-warning'>{self.extra_promo_text}</span>")
@property
def template_date_timestamp(self):
"""For use in all auctions list"""
if self.closed or self.in_progress:
return self.date_end
return self.date_start
@property
def template_status(self):
"""What's the `template_date_timestamp` for this auction?"""
if self.in_progress:
return "Now until:"
if not self.started:
return "Starts:"
return ""
@property
def template_pre_register_fee(self):
"""only for templates, winning_bid_percent_to_club - pre_register_lot_discount_percent"""
return self.winning_bid_percent_to_club - self.pre_register_lot_discount_percent
def get_absolute_url(self):
return self.url
def get_edit_url(self):
return f"/auctions/{self.slug}/edit/"
@property
def url(self):
return f"/auctions/{self.slug}/"
@property
def label_print_link(self):
return f"{self.get_absolute_url()}?printredirect={reverse('print_my_labels', kwargs={'slug': self.slug})}"
@property
def label_print_unprinted_link(self):
return f"{self.get_absolute_url()}?printredirect={reverse('print_my_unprinted_labels', kwargs={'slug': self.slug})}"
@property
def add_lot_link(self):
return f"/lots/new/?auction={self.slug}"
@property
def view_lot_link(self):
return f"/lots/?auction={self.slug}&status=all"
@property
def user_admin_link(self):
return reverse("auction_tos_list", kwargs={"slug": self.slug})
@property
def set_lot_winners_link(self):
# return f"{self.get_absolute_url()}lots/set-winners/{self.set_lot_winners_url}"
return f"{self.get_absolute_url()}lots/set-winners/"
def permission_check(self, user):
"""See if `user` can make changes to this auction"""
if self.created_by == user:
return True
if user.is_superuser:
return True
if not user.is_authenticated:
return False
tos = AuctionTOS.objects.filter(is_admin=True, user=user, user__isnull=False, auction=self.pk).first()
if tos:
return True
return False
@property
def pickup_locations_before_end(self):
"""If there's a problem with the pickup location times, all of them need to be after the end date of the auction (or after the start date for an in-person auction).
Returns the edit url for the first pickup location whose end time is before the auction end"""
locations = self.location_qs
time_to_use = self.date_end
if not self.is_online:
time_to_use = self.date_start
for location in locations:
error = False
try:
if location.pickup_time < time_to_use:
error = True
if location.second_pickup_time:
if location.second_pickup_time < time_to_use:
error = True
except:
error = False
if error:
return reverse("edit_pickup", kwargs={"pk": location.pk})
return False
@property
def timezone(self):
try:
return pytz_timezone(self.created_by.userdata.timezone)
except:
return pytz_timezone(settings.TIME_ZONE)
@property
def time_start_is_at_night(self):
date_start_local = self.date_start.astimezone(self.timezone)
start_time = date_start_local.time()
midnight = time(0, 0)
six_am = time(6, 0)
return midnight <= start_time <= six_am
@property
def dynamic_end(self):
"""The absolute latest a lot in this auction can end"""
if self.sealed_bid:
return self.date_end
else:
dynamic_end = datetime.timedelta(minutes=60)
return self.date_end + dynamic_end
@property
def date_end_as_str(self):
"""Human-reable end date of the auction; this will always be an empty string for in-person auctions"""
if self.is_online:
return self.date_end
else:
return ""
@property
def minutes_to_end(self):
if not self.date_end:
return 9999
timedelta = self.date_end - timezone.now()
seconds = timedelta.total_seconds()
if seconds < 0:
return 0
minutes = seconds // 60
return minutes
@property
def ending_soon(self):