Optimise generateSampleData by ~10x

Does remove reversion creation for now...
This commit is contained in:
2021-02-01 13:53:58 +00:00
parent 87caab6c8e
commit 11db880ac3
6 changed files with 282 additions and 251 deletions

View File

@@ -0,0 +1,36 @@
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import Group
from assets import models
from RIGS import models as rigsmodels
class Command(BaseCommand):
help = 'Deletes testing sample data'
def handle(self, *args, **kwargs):
from django.conf import settings
if not (settings.DEBUG):
raise CommandError('You cannot run this command in production')
self.delete_objects(models.AssetCategory)
self.delete_objects(models.AssetStatus)
self.delete_objects(models.Supplier)
self.delete_objects(models.Connector)
self.delete_objects(models.Asset)
self.delete_objects(rigsmodels.VatRate)
self.delete_objects(rigsmodels.Profile)
self.delete_objects(rigsmodels.Person)
self.delete_objects(rigsmodels.Organisation)
self.delete_objects(rigsmodels.Venue)
self.delete_objects(Group)
self.delete_objects(rigsmodels.Event)
self.delete_objects(rigsmodels.EventItem)
self.delete_objects(rigsmodels.Invoice)
self.delete_objects(rigsmodels.Payment)
self.delete_objects(rigsmodels.RiskAssessment)
self.delete_objects(rigsmodels.EventChecklist)
def delete_objects(self, model):
for obj in model.objects.all():
obj.delete()

View File

@@ -1,11 +1,14 @@
from django.core.management import call_command from django.core.management import call_command
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
import time
class Command(BaseCommand): class Command(BaseCommand):
help = 'Adds sample data to use for testing' help = 'Adds sample data to use for testing'
can_import_settings = True can_import_settings = True
def handle(self, *args, **options): def handle(self, *args, **options):
begin = time.time()
call_command('generateSampleRIGSData') call_command('generateSampleRIGSData')
call_command('generateSampleAssetsData') call_command('generateSampleAssetsData')
end = time.time()
print(f"Total runtime of the program is {end - begin}")

View File

@@ -18,6 +18,12 @@ class Command(BaseCommand):
organisations = [] organisations = []
venues = [] venues = []
profiles = [] profiles = []
events = []
event_items = []
invoices = []
payments = []
ras = []
checklists = []
keyholder_group = None keyholder_group = None
finance_group = None finance_group = None
@@ -36,16 +42,25 @@ class Command(BaseCommand):
models.VatRate.objects.create(start_at='2014-03-05', rate=0.20, comment='test1') models.VatRate.objects.create(start_at='2014-03-05', rate=0.20, comment='test1')
self.setupGenericProfiles() self.setupGenericProfiles()
self.setupUsefulProfiles()
models.Profile.objects.bulk_create(self.profiles)
self.setupPeople() self.setupPeople()
models.Person.objects.bulk_create(self.people)
self.setupOrganisations() self.setupOrganisations()
models.Organisation.objects.bulk_create(self.organisations)
self.setupVenues() self.setupVenues()
models.Venue.objects.bulk_create(self.venues)
self.setupGroups() self.setupGroups()
self.setupEvents() self.setupEvents()
models.Event.objects.bulk_create(self.events)
self.setupUsefulProfiles() models.EventItem.objects.bulk_create(self.event_items)
models.Invoice.objects.bulk_create(self.invoices)
models.Payment.objects.bulk_create(self.payments)
models.RiskAssessment.objects.bulk_create(self.ras)
models.EventChecklist.objects.bulk_create(self.checklists)
def setupPeople(self): def setupPeople(self):
names = ["Regulus Black", "Sirius Black", "Lavender Brown", "Cho Chang", "Vincent Crabbe", "Vincent Crabbe", names = ["Regulus Black", "Sirius Black", "Lavender Brown", "Cho Chang", "Vincent Crabbe", "Vincent Crabbe",
@@ -61,24 +76,22 @@ class Command(BaseCommand):
"Charlie Weasley", "Fred Weasley", "George Weasley", "Ginny Weasley", "Molly Weasley", "Percy Weasley", "Charlie Weasley", "Fred Weasley", "George Weasley", "Ginny Weasley", "Molly Weasley", "Percy Weasley",
"Ron Weasley", "Dobby", "Fluffy", "Hedwig", "Moaning Myrtle", "Aragog", "Grawp"] # noqa "Ron Weasley", "Dobby", "Fluffy", "Hedwig", "Moaning Myrtle", "Aragog", "Grawp"] # noqa
for i, name in enumerate(names): for i, name in enumerate(names):
with reversion.create_revision(): pk = i + 1
reversion.set_user(random.choice(self.profiles)) person = models.Person(pk=pk, name=name)
newPerson = models.Person.objects.create(name=name) if i % 3 == 0:
if i % 3 == 0: person.email = "address@person.com"
newPerson.email = "address@person.com"
if i % 5 == 0: if i % 5 == 0:
newPerson.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" person.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
if i % 7 == 0: if i % 7 == 0:
newPerson.address = "1 Person Test Street \n Demoton \n United States of TEC \n RMRF 567" person.address = "1 Person Test Street \n Demoton \n United States of TEC \n RMRF 567"
if i % 9 == 0: if i % 9 == 0:
newPerson.phone = "01234 567894" person.phone = "01234 567894"
newPerson.save() self.people.append(person)
self.people.append(newPerson)
def setupOrganisations(self): def setupOrganisations(self):
names = ["Acme, inc.", "Widget Corp", "123 Warehousing", "Demo Company", "Smith and Co.", "Foo Bars", names = ["Acme, inc.", "Widget Corp", "123 Warehousing", "Demo Company", "Smith and Co.", "Foo Bars",
@@ -108,26 +121,25 @@ class Command(BaseCommand):
"Klimpys", "The Krusty Krab", "Monks Diner", "Milliways", "Minuteman Cafe", "Taco Grande", "Klimpys", "The Krusty Krab", "Monks Diner", "Milliways", "Minuteman Cafe", "Taco Grande",
"Tip Top Cafe", "Moes Tavern", "Central Perk", "Chasers"] # noqa "Tip Top Cafe", "Moes Tavern", "Central Perk", "Chasers"] # noqa
for i, name in enumerate(names): for i, name in enumerate(names):
with reversion.create_revision(): pk = i + 1
reversion.set_user(random.choice(self.profiles)) newOrganisation = models.Organisation(pk=pk, name=name)
newOrganisation = models.Organisation.objects.create(name=name)
if i % 2 == 0:
newOrganisation.has_su_account = True
if i % 3 == 0: if i % 2 == 0:
newOrganisation.email = "address@organisation.com" newOrganisation.has_su_account = True
if i % 5 == 0: if i % 3 == 0:
newOrganisation.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" newOrganisation.email = "address@organisation.com"
if i % 7 == 0: if i % 5 == 0:
newOrganisation.address = "1 Organisation Test Street \n Demoton \n United States of TEC \n RMRF 567" newOrganisation.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
if i % 9 == 0: if i % 7 == 0:
newOrganisation.phone = "01234 567894" newOrganisation.address = "1 Organisation Test Street \n Demoton \n United States of TEC \n RMRF 567"
newOrganisation.save() if i % 9 == 0:
self.organisations.append(newOrganisation) newOrganisation.phone = "01234 567894"
self.organisations.append(newOrganisation)
def setupVenues(self): def setupVenues(self):
names = ["Bear Island", "Crossroads Inn", "Deepwood Motte", "The Dreadfort", "The Eyrie", "Greywater Watch", names = ["Bear Island", "Crossroads Inn", "Deepwood Motte", "The Dreadfort", "The Eyrie", "Greywater Watch",
@@ -143,26 +155,24 @@ class Command(BaseCommand):
"Qohor", "The Red Waste", "Tyrosh", "Vaes Dothrak", "Valyria", "Village of the Lhazareen", "Volantis", "Qohor", "The Red Waste", "Tyrosh", "Vaes Dothrak", "Valyria", "Village of the Lhazareen", "Volantis",
"Yunkai"] # noqa "Yunkai"] # noqa
for i, name in enumerate(names): for i, name in enumerate(names):
with reversion.create_revision(): pk = i + 1
reversion.set_user(random.choice(self.profiles)) newVenue = models.Venue(pk=pk, name=name)
newVenue = models.Venue.objects.create(name=name) if i % 2 == 0:
if i % 2 == 0: newVenue.three_phase_available = True
newVenue.three_phase_available = True
if i % 3 == 0: if i % 3 == 0:
newVenue.email = "address@venue.com" newVenue.email = "address@venue.com"
if i % 5 == 0: if i % 5 == 0:
newVenue.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" newVenue.notes = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
if i % 7 == 0: if i % 7 == 0:
newVenue.address = "1 Venue Test Street \n Demoton \n United States of TEC \n RMRF 567" newVenue.address = "1 Venue Test Street \n Demoton \n United States of TEC \n RMRF 567"
if i % 9 == 0: if i % 9 == 0:
newVenue.phone = "01234 567894" newVenue.phone = "01234 567894"
newVenue.save() self.venues.append(newVenue)
self.venues.append(newVenue)
def setupGroups(self): def setupGroups(self):
self.keyholder_group = Group.objects.create(name='Keyholders') self.keyholder_group = Group.objects.create(name='Keyholders')
@@ -200,51 +210,51 @@ class Command(BaseCommand):
names = ["Clara Oswin Oswald", "Rory Williams", "Amy Pond", "River Song", "Martha Jones", "Donna Noble", names = ["Clara Oswin Oswald", "Rory Williams", "Amy Pond", "River Song", "Martha Jones", "Donna Noble",
"Jack Harkness", "Mickey Smith", "Rose Tyler"] "Jack Harkness", "Mickey Smith", "Rose Tyler"]
for i, name in enumerate(names): for i, name in enumerate(names):
newProfile = models.Profile.objects.create(username=name.replace(" ", ""), first_name=name.split(" ")[0], pk = i + 1
last_name=name.split(" ")[-1], newProfile = models.Profile(pk=pk, username=name.replace(" ", ""), first_name=name.split(" ")[0],
email=name.replace(" ", "") + "@example.com", last_name=name.split(" ")[-1],
initials="".join([j[0].upper() for j in name.split()])) email=name.replace(" ", "") + "@example.com",
initials="".join([j[0].upper() for j in name.split()]))
if i % 2 == 0: if i % 2 == 0:
newProfile.phone = "01234 567894" newProfile.phone = "01234 567894"
newProfile.save()
self.profiles.append(newProfile) self.profiles.append(newProfile)
def setupUsefulProfiles(self): def setupUsefulProfiles(self):
superUser = models.Profile.objects.create(username="superuser", first_name="Super", last_name="User", superUser = models.Profile(pk=10, username="superuser", first_name="Super", last_name="User",
initials="SU", initials="SU",
email="superuser@example.com", is_superuser=True, is_active=True, email="superuser@example.com", is_superuser=True, is_active=True,
is_staff=True) is_staff=True)
superUser.set_password('superuser') superUser.set_password('superuser')
superUser.save() self.profiles.append(superUser)
financeUser = models.Profile.objects.create(username="finance", first_name="Finance", last_name="User", financeUser = models.Profile(pk=11, username="finance", first_name="Finance", last_name="User",
initials="FU", initials="FU",
email="financeuser@example.com", is_active=True, is_approved=True) email="financeuser@example.com", is_active=True, is_approved=True)
financeUser.groups.add(self.finance_group) financeUser.groups.add(self.finance_group)
financeUser.groups.add(self.keyholder_group) financeUser.groups.add(self.keyholder_group)
financeUser.set_password('finance') financeUser.set_password('finance')
financeUser.save() self.profiles.append(financeUser)
hsUser = models.Profile.objects.create(username="hs", first_name="HS", last_name="User", hsUser = models.Profile(pk=12, username="hs", first_name="HS", last_name="User",
initials="HSU", initials="HSU",
email="hsuser@example.com", is_active=True, is_approved=True) email="hsuser@example.com", is_active=True, is_approved=True)
hsUser.groups.add(self.hs_group) hsUser.groups.add(self.hs_group)
hsUser.groups.add(self.keyholder_group) hsUser.groups.add(self.keyholder_group)
hsUser.set_password('hs') hsUser.set_password('hs')
hsUser.save() self.profiles.append(hsUser)
keyholderUser = models.Profile.objects.create(username="keyholder", first_name="Keyholder", last_name="User", keyholderUser = models.Profile(pk=13, username="keyholder", first_name="Keyholder", last_name="User",
initials="KU", initials="KU",
email="keyholderuser@example.com", is_active=True, is_approved=True) email="keyholderuser@example.com", is_active=True, is_approved=True)
keyholderUser.groups.add(self.keyholder_group) keyholderUser.groups.add(self.keyholder_group)
keyholderUser.set_password('keyholder') keyholderUser.set_password('keyholder')
keyholderUser.save() self.profiles.append(keyholderUser)
basicUser = models.Profile.objects.create(username="basic", first_name="Basic", last_name="User", initials="BU", basicUser = models.Profile(pk=14, username="basic", first_name="Basic", last_name="User", initials="BU",
email="basicuser@example.com", is_active=True, is_approved=True) email="basicuser@example.com", is_active=True, is_approved=True)
basicUser.set_password('basic') basicUser.set_password('basic')
basicUser.save() self.profiles.append(basicUser)
def setupEvents(self): def setupEvents(self):
names = ["Outdoor Concert", "Hall Open Mic Night", "Festival", "Weekend Event", "Magic Show", "Society Ball", names = ["Outdoor Concert", "Hall Open Mic Night", "Festival", "Weekend Event", "Magic Show", "Society Ball",
@@ -275,99 +285,106 @@ class Command(BaseCommand):
{'name': 'Loyalty Discount', 'description': 'Have some negative moneys', 'quantity': 1, 'cost': -50.00}] {'name': 'Loyalty Discount', 'description': 'Have some negative moneys', 'quantity': 1, 'cost': -50.00}]
dayDelta = -120 # start adding events from 4 months ago dayDelta = -120 # start adding events from 4 months ago
item_pk = 0
for i in range(150): # Let's add 100 events for i in range(150): # Let's add 100 events
with reversion.create_revision(): pk = i + 1
reversion.set_user(random.choice(self.profiles)) name = names[i % len(names)]
name = names[i % len(names)] startDate = datetime.date.today() + datetime.timedelta(days=dayDelta)
dayDelta = dayDelta + random.randint(0, 3)
startDate = datetime.date.today() + datetime.timedelta(days=dayDelta) newEvent = models.Event(pk=pk, name=name, start_date=startDate)
dayDelta = dayDelta + random.randint(0, 3)
newEvent = models.Event.objects.create(name=name, start_date=startDate) if random.randint(0, 2) > 1: # 1 in 3 have a start time
newEvent.start_time = datetime.time(random.randint(15, 20))
if random.randint(0, 2) > 1: # of those, 1 in 3 have an end time on the same day
newEvent.end_time = datetime.time(random.randint(21, 23))
elif random.randint(0, 1) > 0: # half of the others finish early the next day
newEvent.end_date = newEvent.start_date + datetime.timedelta(days=1)
newEvent.end_time = datetime.time(random.randint(0, 5))
elif random.randint(0, 2) > 1: # 1 in 3 of the others finish a few days ahead
newEvent.end_date = newEvent.start_date + datetime.timedelta(days=random.randint(1, 4))
if random.randint(0, 2) > 1: # 1 in 3 have a start time if random.randint(0, 6) > 0: # 5 in 6 have MIC
newEvent.start_time = datetime.time(random.randint(15, 20)) newEvent.mic = random.choice(self.profiles)
if random.randint(0, 2) > 1: # of those, 1 in 3 have an end time on the same day
newEvent.end_time = datetime.time(random.randint(21, 23))
elif random.randint(0, 1) > 0: # half of the others finish early the next day
newEvent.end_date = newEvent.start_date + datetime.timedelta(days=1)
newEvent.end_time = datetime.time(random.randint(0, 5))
elif random.randint(0, 2) > 1: # 1 in 3 of the others finish a few days ahead
newEvent.end_date = newEvent.start_date + datetime.timedelta(days=random.randint(1, 4))
if random.randint(0, 6) > 0: # 5 in 6 have MIC if random.randint(0, 6) > 0: # 5 in 6 have organisation
newEvent.mic = random.choice(self.profiles) newEvent.organisation = random.choice(self.organisations)
if random.randint(0, 6) > 0: # 5 in 6 have organisation if random.randint(0, 6) > 0: # 5 in 6 have person
newEvent.organisation = random.choice(self.organisations) newEvent.person = random.choice(self.people)
if random.randint(0, 6) > 0: # 5 in 6 have person if random.randint(0, 6) > 0: # 5 in 6 have venue
newEvent.person = random.choice(self.people) newEvent.venue = random.choice(self.venues)
if random.randint(0, 6) > 0: # 5 in 6 have venue # Could have any status, equally weighted
newEvent.venue = random.choice(self.venues) newEvent.status = random.choice(
[models.Event.BOOKED, models.Event.CONFIRMED, models.Event.PROVISIONAL, models.Event.CANCELLED])
# Could have any status, equally weighted newEvent.dry_hire = (random.randint(0, 7) == 0) # 1 in 7 are dry hire
newEvent.status = random.choice(
[models.Event.BOOKED, models.Event.CONFIRMED, models.Event.PROVISIONAL, models.Event.CANCELLED])
newEvent.dry_hire = (random.randint(0, 7) == 0) # 1 in 7 are dry hire if random.randint(0, 1) > 0: # 1 in 2 have description
newEvent.description = random.choice(descriptions)
if random.randint(0, 1) > 0: # 1 in 2 have description if random.randint(0, 1) > 0: # 1 in 2 have notes
newEvent.description = random.choice(descriptions) newEvent.notes = random.choice(notes)
if random.randint(0, 1) > 0: # 1 in 2 have notes self.events.append(newEvent)
newEvent.notes = random.choice(notes)
newEvent.save() # Now add some items
for j in range(random.randint(1, 5)):
itemData = itemOptions[random.randint(0, len(itemOptions) - 1)]
newItem = models.EventItem(pk=item_pk, event=newEvent, order=j, **itemData)
item_pk += 1
self.event_items.append(newItem)
# Now add some items # while newEvent.sum_total < 0:
for j in range(random.randint(1, 5)): # itemData = itemOptions[random.randint(0, len(itemOptions) - 1)]
itemData = itemOptions[random.randint(0, len(itemOptions) - 1)] # newItem = models.EventItem(pk=pk + j + 150, event=newEvent, order=j, **itemData)
newItem = models.EventItem.objects.create(event=newEvent, order=j, **itemData) # self.event_items.append(newItem)
newItem.save()
while newEvent.sum_total < 0: if newEvent.start_date < datetime.date.today(): # think about adding an invoice
itemData = itemOptions[random.randint(0, len(itemOptions) - 1)] if random.randint(0, 2) > 0: # 2 in 3 have had paperwork sent to treasury
newItem = models.EventItem.objects.create(event=newEvent, order=j, **itemData) newInvoice = models.Invoice(pk=pk, event=newEvent)
newItem.save() if newEvent.status is models.Event.CANCELLED: # void cancelled events
newInvoice.void = True
with reversion.create_revision(): elif random.randint(0, 2) > 1: # 1 in 3 have been paid
reversion.set_user(random.choice(self.profiles)) self.payments.append(models.Payment(pk=pk, invoice=newInvoice, amount=newInvoice.balance,
if newEvent.start_date < datetime.date.today(): # think about adding an invoice date=datetime.date.today()))
if random.randint(0, 2) > 0: # 2 in 3 have had paperwork sent to treasury self.invoices.append(newInvoice)
newInvoice = models.Invoice.objects.create(event=newEvent)
if newEvent.status is models.Event.CANCELLED: # void cancelled events
newInvoice.void = True
elif random.randint(0, 2) > 1: # 1 in 3 have been paid
models.Payment.objects.create(invoice=newInvoice, amount=newInvoice.balance,
date=datetime.date.today())
if i == 1 or random.randint(0, 5) > 0: # Event 1 and 1 in 5 have a RA if i == 1 or random.randint(0, 5) > 0: # Event 1 and 1 in 5 have a RA
models.RiskAssessment.objects.create(event=newEvent, supervisor_consulted=bool(random.getrandbits(1)), nonstandard_equipment=bool(random.getrandbits(1)), self.ras.append(
nonstandard_use=bool(random.getrandbits(1)), models.RiskAssessment(pk=pk, event=newEvent, supervisor_consulted=bool(random.getrandbits(1)),
contractors=bool(random.getrandbits(1)), nonstandard_equipment=bool(random.getrandbits(1)),
other_companies=bool(random.getrandbits(1)), nonstandard_use=bool(random.getrandbits(1)),
crew_fatigue=bool(random.getrandbits(1)), contractors=bool(random.getrandbits(1)),
big_power=bool(random.getrandbits(1)), other_companies=bool(random.getrandbits(1)),
generators=bool(random.getrandbits(1)), crew_fatigue=bool(random.getrandbits(1)),
other_companies_power=bool(random.getrandbits(1)), big_power=bool(random.getrandbits(1)),
nonstandard_equipment_power=bool(random.getrandbits(1)), generators=bool(random.getrandbits(1)),
multiple_electrical_environments=bool(random.getrandbits(1)), other_companies_power=bool(random.getrandbits(1)),
noise_monitoring=bool(random.getrandbits(1)), nonstandard_equipment_power=bool(random.getrandbits(1)),
known_venue=bool(random.getrandbits(1)), multiple_electrical_environments=bool(random.getrandbits(1)),
safe_loading=bool(random.getrandbits(1)), noise_monitoring=bool(random.getrandbits(1)),
safe_storage=bool(random.getrandbits(1)), known_venue=bool(random.getrandbits(1)),
area_outside_of_control=bool(random.getrandbits(1)), safe_loading=bool(random.getrandbits(1)),
barrier_required=bool(random.getrandbits(1)), safe_storage=bool(random.getrandbits(1)),
nonstandard_emergency_procedure=bool(random.getrandbits(1)), area_outside_of_control=bool(random.getrandbits(1)),
special_structures=bool(random.getrandbits(1)), barrier_required=bool(random.getrandbits(1)),
suspended_structures=bool(random.getrandbits(1)), nonstandard_emergency_procedure=bool(random.getrandbits(1)),
outside=bool(random.getrandbits(1))) special_structures=bool(random.getrandbits(1)),
suspended_structures=bool(random.getrandbits(1)),
outside=bool(random.getrandbits(1))))
if i == 0 or random.randint(0, 1) > 0: # Event 1 and 1 in 10 have a Checklist if i == 0 or random.randint(0, 1) > 0: # Event 1 and 1 in 10 have a Checklist
models.EventChecklist.objects.create(event=newEvent, power_mic=random.choice(self.profiles), safe_parking=bool(random.getrandbits(1)), self.checklists.append(
safe_packing=bool(random.getrandbits(1)), exits=bool(random.getrandbits(1)), trip_hazard=bool(random.getrandbits(1)), warning_signs=bool(random.getrandbits(1)), models.EventChecklist(pk=pk, event=newEvent, power_mic=random.choice(self.profiles),
ear_plugs=bool(random.getrandbits(1)), hs_location="Locked away safely", safe_parking=bool(random.getrandbits(1)),
extinguishers_location="Somewhere, I forgot", earthing=bool(random.getrandbits(1)), pat=bool(random.getrandbits(1)), safe_packing=bool(random.getrandbits(1)),
date=timezone.now(), venue=random.choice(self.venues)) exits=bool(random.getrandbits(1)),
trip_hazard=bool(random.getrandbits(1)),
warning_signs=bool(random.getrandbits(1)),
ear_plugs=bool(random.getrandbits(1)), hs_location="Locked away safely",
extinguishers_location="Somewhere, I forgot",
earthing=bool(random.getrandbits(1)), pat=bool(random.getrandbits(1)),
date=timezone.now(), venue=random.choice(self.venues)))

View File

@@ -1,23 +0,0 @@
from django.core.management.base import BaseCommand, CommandError
from assets import models
class Command(BaseCommand):
help = 'Deletes testing sample data'
def handle(self, *args, **kwargs):
from django.conf import settings
if not (settings.DEBUG):
raise CommandError('You cannot run this command in production')
self.delete_objects(models.AssetCategory)
self.delete_objects(models.AssetStatus)
self.delete_objects(models.Supplier)
self.delete_objects(models.Connector)
self.delete_objects(models.Asset)
def delete_objects(self, model):
for object in model.objects.all():
object.delete()

View File

@@ -11,6 +11,13 @@ from assets import models
class Command(BaseCommand): class Command(BaseCommand):
help = 'Creates some sample data for testing' help = 'Creates some sample data for testing'
categories = []
statuses = []
suppliers = []
connectors = []
cable_types = []
assets = []
def handle(self, *args, **kwargs): def handle(self, *args, **kwargs):
from django.conf import settings from django.conf import settings
@@ -19,67 +26,62 @@ class Command(BaseCommand):
random.seed('Some object to see the random number generator') random.seed('Some object to see the random number generator')
self.create_profile()
self.create_categories() self.create_categories()
models.AssetCategory.objects.bulk_create(self.categories)
self.create_statuses() self.create_statuses()
models.AssetStatus.objects.bulk_create(self.statuses)
self.create_suppliers() self.create_suppliers()
models.Supplier.objects.bulk_create(self.suppliers)
self.create_assets() self.create_assets()
self.create_connectors() self.create_connectors()
models.Connector.objects.bulk_create(self.connectors)
self.create_cable_types()
models.CableType.objects.bulk_create(self.cable_types)
self.create_cables() self.create_cables()
models.Asset.objects.bulk_create(self.assets)
# Make sure that there's at least one profile if this command is run standalone
def create_profile(self):
name = "Fred Johnson"
models.Profile.objects.create(username=name.replace(" ", ""), first_name=name.split(" ")[0], last_name=name.split(" ")[-1],
email=name.replace(" ", "") + "@example.com",
initials="".join([j[0].upper() for j in name.split()]))
def create_categories(self):
categories = ['Case', 'Video', 'General', 'Sound', 'Lighting', 'Rigging']
for cat in categories:
models.AssetCategory.objects.create(name=cat)
def create_statuses(self): def create_statuses(self):
statuses = [('In Service', True, 'success'), ('Lost', False, 'warning'), ('Binned', False, 'danger'), ('Sold', False, 'danger'), ('Broken', False, 'warning')] choices = [('In Service', True, 'success'), ('Lost', False, 'warning'), ('Binned', False, 'danger'), ('Sold', False, 'danger'), ('Broken', False, 'warning')]
pk = 1
for stat in statuses: for stat in choices:
models.AssetStatus.objects.create(name=stat[0], should_show=stat[1], display_class=stat[2]) self.statuses.append(models.AssetStatus(pk=pk, name=stat[0], should_show=stat[1], display_class=stat[2]))
pk += 1
def create_suppliers(self): def create_suppliers(self):
suppliers = ["Acme, inc.", "Widget Corp", "123 Warehousing", "Demo Company", "Smith and Co.", "Foo Bars", "ABC Telecom", "Fake Brothers", "QWERTY Logistics", "Demo, inc.", "Sample Company", "Sample, inc", "Acme Corp", "Allied Biscuit", "Ankh-Sto Associates", "Extensive Enterprise", "Galaxy Corp", "Globo-Chem", "Mr. Sparkle", "Globex Corporation", "LexCorp", "LuthorCorp", "North Central Positronics", "Omni Consimer Products", "Praxis Corporation", "Sombra Corporation", "Sto Plains Holdings", "Tessier-Ashpool", "Wayne Enterprises", "Wentworth Industries", "ZiffCorp", "Bluth Company", "Strickland Propane", "Thatherton Fuels", "Three Waters", "Water and Power", "Western Gas & Electric", "Mammoth Pictures", "Mooby Corp", "Gringotts", "Thrift Bank", "Flowers By Irene", "The Legitimate Businessmens Club", "Osato Chemicals", "Transworld Consortium", "Universal Export", "United Fried Chicken", "Virtucon", "Kumatsu Motors", "Keedsler Motors", "Powell Motors", "Industrial Automation", "Sirius Cybernetics Corporation", "U.S. Robotics and Mechanical Men", "Colonial Movers", "Corellian Engineering Corporation", "Incom Corporation", "General Products", "Leeding Engines Ltd.", "Blammo", # noqa choices = ["Acme, inc.", "Widget Corp", "123 Warehousing", "Demo Company", "Smith and Co.", "Foo Bars", "ABC Telecom", "Fake Brothers", "QWERTY Logistics", "Demo, inc.", "Sample Company", "Sample, inc", "Acme Corp", "Allied Biscuit", "Ankh-Sto Associates", "Extensive Enterprise", "Galaxy Corp", "Globo-Chem", "Mr. Sparkle", "Globex Corporation", "LexCorp", "LuthorCorp", "North Central Positronics", "Omni Consimer Products", "Praxis Corporation", "Sombra Corporation", "Sto Plains Holdings", "Tessier-Ashpool", "Wayne Enterprises", "Wentworth Industries", "ZiffCorp", "Bluth Company", "Strickland Propane", "Thatherton Fuels", "Three Waters", "Water and Power", "Western Gas & Electric", "Mammoth Pictures", "Mooby Corp", "Gringotts", "Thrift Bank", "Flowers By Irene", "The Legitimate Businessmens Club", "Osato Chemicals", "Transworld Consortium", "Universal Export", "United Fried Chicken", "Virtucon", "Kumatsu Motors", "Keedsler Motors", "Powell Motors", "Industrial Automation", "Sirius Cybernetics Corporation", "U.S. Robotics and Mechanical Men", "Colonial Movers", "Corellian Engineering Corporation", "Incom Corporation", "General Products", "Leeding Engines Ltd.", "Blammo", # noqa
"Input, Inc.", "Mainway Toys", "Videlectrix", "Zevo Toys", "Ajax", "Axis Chemical Co.", "Barrytron", "Carrys Candles", "Cogswell Cogs", "Spacely Sprockets", "General Forge and Foundry", "Duff Brewing Company", "Dunder Mifflin", "General Services Corporation", "Monarch Playing Card Co.", "Krustyco", "Initech", "Roboto Industries", "Primatech", "Sonky Rubber Goods", "St. Anky Beer", "Stay Puft Corporation", "Vandelay Industries", "Wernham Hogg", "Gadgetron", "Burleigh and Stronginthearm", "BLAND Corporation", "Nordyne Defense Dynamics", "Petrox Oil Company", "Roxxon", "McMahon and Tate", "Sixty Second Avenue", "Charles Townsend Agency", "Spade and Archer", "Megadodo Publications", "Rouster and Sideways", "C.H. Lavatory and Sons", "Globo Gym American Corp", "The New Firm", "SpringShield", "Compuglobalhypermeganet", "Data Systems", "Gizmonic Institute", "Initrode", "Taggart Transcontinental", "Atlantic Northern", "Niagular", "Plow King", "Big Kahuna Burger", "Big T Burgers and Fries", "Chez Quis", "Chotchkies", "The Frying Dutchman", "Klimpys", "The Krusty Krab", "Monks Diner", "Milliways", "Minuteman Cafe", "Taco Grande", "Tip Top Cafe", "Moes Tavern", "Central Perk", "Chasers"] # noqa "Input, Inc.", "Mainway Toys", "Videlectrix", "Zevo Toys", "Ajax", "Axis Chemical Co.", "Barrytron", "Carrys Candles", "Cogswell Cogs", "Spacely Sprockets", "General Forge and Foundry", "Duff Brewing Company", "Dunder Mifflin", "General Services Corporation", "Monarch Playing Card Co.", "Krustyco", "Initech", "Roboto Industries", "Primatech", "Sonky Rubber Goods", "St. Anky Beer", "Stay Puft Corporation", "Vandelay Industries", "Wernham Hogg", "Gadgetron", "Burleigh and Stronginthearm", "BLAND Corporation", "Nordyne Defense Dynamics", "Petrox Oil Company", "Roxxon", "McMahon and Tate", "Sixty Second Avenue", "Charles Townsend Agency", "Spade and Archer", "Megadodo Publications", "Rouster and Sideways", "C.H. Lavatory and Sons", "Globo Gym American Corp", "The New Firm", "SpringShield", "Compuglobalhypermeganet", "Data Systems", "Gizmonic Institute", "Initrode", "Taggart Transcontinental", "Atlantic Northern", "Niagular", "Plow King", "Big Kahuna Burger", "Big T Burgers and Fries", "Chez Quis", "Chotchkies", "The Frying Dutchman", "Klimpys", "The Krusty Krab", "Monks Diner", "Milliways", "Minuteman Cafe", "Taco Grande", "Tip Top Cafe", "Moes Tavern", "Central Perk", "Chasers"] # noqa
pk = 1
for supplier in choices:
self.suppliers.append(models.Supplier(pk=pk, name=supplier))
pk += 1
with reversion.create_revision(): def create_categories(self):
for supplier in suppliers: choices = ['Case', 'Video', 'General', 'Sound', 'Lighting', 'Rigging']
reversion.set_user(random.choice(rigsmodels.Profile.objects.all())) pk = 1
models.Supplier.objects.create(name=supplier) for cat in choices:
self.categories.append(models.AssetCategory(pk=pk, name=cat))
pk += 1
def create_assets(self): def create_assets(self):
asset_description = ['Large cable', 'Shiny thing', 'New lights', 'Really expensive microphone', 'Box of fuse flaps', 'Expensive tool we didn\'t agree to buy', 'Cable drums', 'Boring amount of tape', 'Video stuff no one knows how to use', 'More amplifiers', 'Heatshrink'] asset_description = ['Large cable', 'Shiny thing', 'New lights', 'Really expensive microphone', 'Box of fuse flaps', 'Expensive tool we didn\'t agree to buy', 'Cable drums', 'Boring amount of tape', 'Video stuff no one knows how to use', 'More amplifiers', 'Heatshrink']
pk = 1
for i in range(100):
asset = models.Asset(
pk=pk,
asset_id=str(pk),
description=random.choice(asset_description),
category=random.choice(self.categories),
status=random.choice(self.statuses),
date_acquired=timezone.now().date()
)
categories = models.AssetCategory.objects.all() if i % 4 == 0 and self.assets:
statuses = models.AssetStatus.objects.all() asset.parent = random.choice(self.assets)
suppliers = models.Supplier.objects.all()
with reversion.create_revision(): if i % 3 == 0:
for i in range(100): asset.purchased_from = random.choice(self.suppliers)
reversion.set_user(random.choice(rigsmodels.Profile.objects.all())) self.assets.append(asset)
asset = models.Asset( pk += 1
asset_id='{}'.format(models.Asset.get_available_asset_id()),
description=random.choice(asset_description),
category=random.choice(categories),
status=random.choice(statuses),
date_acquired=timezone.now().date()
)
if i % 4 == 0:
asset.parent = models.Asset.objects.order_by('?').first()
if i % 3 == 0:
asset.purchased_from = random.choice(suppliers)
asset.clean()
asset.save()
def create_cables(self): def create_cables(self):
asset_description = ['The worm', 'Harting without a cap', 'Heavy cable', 'Extension lead', 'IEC cable that we should remember to prep'] asset_description = ['The worm', 'Harting without a cap', 'Heavy cable', 'Extension lead', 'IEC cable that we should remember to prep']
@@ -87,42 +89,29 @@ class Command(BaseCommand):
csas = [0.75, 1.00, 1.25, 2.5, 4] csas = [0.75, 1.00, 1.25, 2.5, 4]
lengths = [1, 2, 5, 10, 15, 20, 25, 30, 50, 100] lengths = [1, 2, 5, 10, 15, 20, 25, 30, 50, 100]
cores = [3, 5] pk = 102 # Offset to avoid other asset IDs
circuits = [1, 2, 3, 6]
categories = models.AssetCategory.objects.all()
statuses = models.AssetStatus.objects.all()
suppliers = models.Supplier.objects.all()
connectors = models.Connector.objects.all()
for i in range(len(connectors)):
models.CableType.objects.create(plug=random.choice(connectors), socket=random.choice(connectors), circuits=random.choice(circuits), cores=random.choice(cores))
for i in range(100): for i in range(100):
asset = models.Asset( asset = models.Asset(
asset_id='{}'.format(models.Asset.get_available_asset_id()), pk=pk,
asset_id=random.choice(asset_prefixes) + str(pk),
description=random.choice(asset_description), description=random.choice(asset_description),
category=random.choice(categories), category=random.choice(self.categories),
status=random.choice(statuses), status=random.choice(self.statuses),
date_acquired=timezone.now().date(), date_acquired=timezone.now().date(),
is_cable=True, is_cable=True,
cable_type=random.choice(models.CableType.objects.all()), cable_type=random.choice(self.cable_types),
csa=random.choice(csas), csa=random.choice(csas),
length=random.choice(lengths), length=random.choice(lengths),
) )
if i % 5 == 0: if i % 4 == 0 and self.assets:
prefix = random.choice(asset_prefixes) asset.parent = random.choice(self.assets)
asset.asset_id = prefix + str(models.Asset.get_available_asset_id(wanted_prefix=prefix))
if i % 4 == 0:
asset.parent = models.Asset.objects.order_by('?').first()
if i % 3 == 0: if i % 3 == 0:
asset.purchased_from = random.choice(suppliers) asset.purchased_from = random.choice(self.suppliers)
self.assets.append(asset)
asset.clean() pk += 1
asset.save()
def create_connectors(self): def create_connectors(self):
connectors = [ connectors = [
@@ -131,6 +120,15 @@ class Command(BaseCommand):
{"description": "32/3", "current_rating": 32, "voltage_rating": 400, "num_pins": 5}, {"description": "32/3", "current_rating": 32, "voltage_rating": 400, "num_pins": 5},
{"description": "Socapex", "current_rating": 23, "voltage_rating": 600, "num_pins": 19}, {"description": "Socapex", "current_rating": 23, "voltage_rating": 600, "num_pins": 19},
] ]
pk = 1
for connector in connectors: for connector in connectors:
conn = models.Connector.objects.create(** connector) self.connectors.append(models.Connector(pk=pk, **connector))
conn.save() pk += 1
def create_cable_types(self):
cores = [3, 5]
circuits = [1, 2, 3, 6]
pk = 1
for i in range(10):
self.cable_types.append(models.CableType(pk=pk, plug=random.choice(self.connectors), socket=random.choice(self.connectors), circuits=random.choice(circuits), cores=random.choice(cores)))
pk += 1

View File

@@ -2,16 +2,16 @@
var gulp = require('gulp'); var gulp = require('gulp');
var terser = require('gulp-terser'); const terser = require('gulp-terser');
var sass = require('gulp-sass'); const sass = require('gulp-sass');
var flatten = require('gulp-flatten'); const flatten = require('gulp-flatten');
var autoprefixer = require('autoprefixer') const autoprefixer = require('autoprefixer')
var postcss = require('gulp-postcss') const postcss = require('gulp-postcss')
var sourcemaps = require('gulp-sourcemaps'); const sourcemaps = require('gulp-sourcemaps');
var browsersync = require('browser-sync').create(); const browsersync = require('browser-sync').create();
var { exec } = require("child_process"); const { exec } = require("child_process");
var spawn = require('child_process').spawn; const spawn = require('child_process').spawn;
var cssnano = require('cssnano'); const cssnano = require('cssnano');
sass.compiler = require('node-sass'); sass.compiler = require('node-sass');