Geen omschrijving

seed_ecoloop.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. from __future__ import annotations
  2. from decimal import Decimal
  3. from django.core.management.base import BaseCommand
  4. from django.contrib.auth import get_user_model
  5. from django.utils import timezone
  6. from orgs.models import Organization, UserProfile
  7. from recycle_core.models import (
  8. MaterialCategory,
  9. Material,
  10. ProvidedService,
  11. PriceList,
  12. PriceListItem,
  13. Customer,
  14. CustomerSite,
  15. PickupOrder,
  16. PickupItem,
  17. WeighTicket,
  18. WeighLine,
  19. ScrapListing,
  20. ScrapListingItem,
  21. ScrapBid,
  22. )
  23. from recycle_core.services.billing import generate_invoice_for_pickup
  24. User = get_user_model()
  25. class Command(BaseCommand):
  26. help = "Seed demo data for Ecoloop: org, materials, price list, customer, pickup, weigh ticket, invoice"
  27. def add_arguments(self, parser):
  28. parser.add_argument("--org", default="DEMO", help="Organization code/id/name to seed (default: DEMO)")
  29. parser.add_argument("--bidder-org", dest="bidder_org", default="REC1", help="Bidder org code/id/name (default: REC1)")
  30. parser.add_argument("--reset", action="store_true", help="Delete existing data for the target orgs before seeding")
  31. def handle(self, *args, **options):
  32. now = timezone.now()
  33. def _resolve_org(ident: str, *, default_name: str) -> Organization:
  34. if ident and ident.isdigit():
  35. org = Organization.objects.filter(pk=int(ident)).first()
  36. if org:
  37. return org
  38. org = (
  39. Organization.objects.filter(code=ident).first()
  40. or Organization.objects.filter(name=ident).first()
  41. )
  42. if org:
  43. return org
  44. # Create with defaults if not found
  45. return Organization.objects.create(code=ident, name=default_name, timezone="UTC", currency_code="THB")
  46. org_ident = options.get("org") or "DEMO"
  47. bidder_ident = options.get("bidder_org") or "REC1"
  48. org = _resolve_org(org_ident, default_name=("Ecoloop " + str(org_ident)))
  49. bidder_org = _resolve_org(bidder_ident, default_name="Recycler Co.")
  50. # Optionally reset existing demo data (scoped to the selected orgs)
  51. if options.get("reset"):
  52. from recycle_core.models import (
  53. ScrapAward,
  54. ScrapBid,
  55. ScrapListingInvite,
  56. ScrapListingItem,
  57. ScrapListing,
  58. WeighLine,
  59. WeighTicket,
  60. PickupItem,
  61. PickupOrder,
  62. InvoiceLine,
  63. Invoice,
  64. Payment,
  65. Payout,
  66. ServiceAgreement,
  67. CustomerSite,
  68. Customer,
  69. PriceListItem,
  70. PriceList,
  71. Material,
  72. MaterialCategory,
  73. ProvidedService,
  74. )
  75. def _wipe_for(o: Organization):
  76. # Marketplace
  77. ScrapAward.objects.filter(listing__organization=o).delete()
  78. ScrapBid.objects.filter(listing__organization=o).delete()
  79. ScrapListingInvite.objects.filter(listing__organization=o).delete()
  80. ScrapListingItem.objects.filter(listing__organization=o).delete()
  81. ScrapListing.objects.filter(organization=o).delete()
  82. # Operations
  83. WeighLine.objects.filter(ticket__pickup__organization=o).delete()
  84. WeighTicket.objects.filter(pickup__organization=o).delete()
  85. PickupItem.objects.filter(pickup__organization=o).delete()
  86. PickupOrder.objects.filter(organization=o).delete()
  87. # Billing
  88. InvoiceLine.objects.filter(invoice__organization=o).delete()
  89. Payment.objects.filter(invoice__organization=o).delete()
  90. Invoice.objects.filter(organization=o).delete()
  91. Payout.objects.filter(organization=o).delete()
  92. # Customers and agreements
  93. ServiceAgreement.objects.filter(customer__organization=o).delete()
  94. CustomerSite.objects.filter(customer__organization=o).delete()
  95. Customer.objects.filter(organization=o).delete()
  96. # Pricing
  97. PriceListItem.objects.filter(price_list__organization=o).delete()
  98. PriceList.objects.filter(organization=o).delete()
  99. # Inventory and services
  100. Material.objects.filter(organization=o).delete()
  101. ProvidedService.objects.filter(organization=o).delete()
  102. MaterialCategory.objects.filter(organization=o).delete()
  103. _wipe_for(org)
  104. _wipe_for(bidder_org)
  105. self.stdout.write(self.style.WARNING("Existing data removed for selected orgs (reset)."))
  106. # Users
  107. manager = User.objects.filter(username="manager").first()
  108. if not manager:
  109. manager = User.objects.create_user(username="manager", email="manager@example.com", password="manager123")
  110. driver = User.objects.filter(username="driver").first()
  111. if not driver:
  112. driver = User.objects.create_user(username="driver", email="driver@example.com", password="driver123")
  113. buyer = User.objects.filter(username="buyer").first()
  114. if not buyer:
  115. buyer = User.objects.create_user(username="buyer", email="buyer@example.com", password="buyer123")
  116. # Ensure recycle_core user profiles and roles
  117. UserProfile.objects.get_or_create(user=manager, defaults={"organization": org, "role": UserProfile.ROLE_MANAGER})
  118. UserProfile.objects.get_or_create(user=driver, defaults={"organization": org, "role": UserProfile.ROLE_DRIVER})
  119. UserProfile.objects.get_or_create(user=buyer, defaults={"organization": bidder_org, "role": UserProfile.ROLE_MANAGER})
  120. # Materials and categories
  121. plastics, _ = MaterialCategory.objects.get_or_create(organization=org, name="Plastics")
  122. metals, _ = MaterialCategory.objects.get_or_create(organization=org, name="Metals")
  123. paper, _ = MaterialCategory.objects.get_or_create(organization=org, name="Paper")
  124. pet, _ = Material.objects.get_or_create(organization=org, category="Plastics", name="PET", defaults={"default_unit": Material.UNIT_KG})
  125. hdpe, _ = Material.objects.get_or_create(organization=org, category="Plastics", name="HDPE", defaults={"default_unit": Material.UNIT_KG})
  126. can, _ = Material.objects.get_or_create(organization=org, category="Metals", name="Aluminum Can", defaults={"default_unit": Material.UNIT_KG})
  127. cardboard, _ = Material.objects.get_or_create(organization=org, category="Paper", name="Cardboard", defaults={"default_unit": Material.UNIT_KG})
  128. # Price list
  129. pl, _ = PriceList.objects.get_or_create(
  130. organization=org,
  131. name="Standard",
  132. defaults={"currency_code": "THB"},
  133. )
  134. # Sell prices (invoice customer)
  135. PriceListItem.objects.get_or_create(price_list=pl, material=pet, unit=Material.UNIT_KG, direction=PriceListItem.DIRECTION_SELL, defaults={"unit_price": Decimal("5.00")})
  136. PriceListItem.objects.get_or_create(price_list=pl, material=hdpe, unit=Material.UNIT_KG, direction=PriceListItem.DIRECTION_SELL, defaults={"unit_price": Decimal("4.00")})
  137. PriceListItem.objects.get_or_create(price_list=pl, material=can, unit=Material.UNIT_KG, direction=PriceListItem.DIRECTION_SELL, defaults={"unit_price": Decimal("12.00")})
  138. PriceListItem.objects.get_or_create(price_list=pl, material=cardboard, unit=Material.UNIT_KG, direction=PriceListItem.DIRECTION_SELL, defaults={"unit_price": Decimal("2.00")})
  139. # Buy prices (pay customer)
  140. PriceListItem.objects.get_or_create(price_list=pl, material=pet, unit=Material.UNIT_KG, direction=PriceListItem.DIRECTION_BUY, defaults={"unit_price": Decimal("1.50")})
  141. PriceListItem.objects.get_or_create(price_list=pl, material=hdpe, unit=Material.UNIT_KG, direction=PriceListItem.DIRECTION_BUY, defaults={"unit_price": Decimal("1.20")})
  142. # Customer and site
  143. customer, _ = Customer.objects.get_or_create(
  144. organization=org,
  145. name="Acme Factory",
  146. defaults={
  147. "email": "ops@acme.example",
  148. "phone": "+66 000 0000",
  149. "billing_address": "123 Demo Rd, Bangkok",
  150. "price_list": pl,
  151. },
  152. )
  153. site, _ = CustomerSite.objects.get_or_create(
  154. customer=customer,
  155. name="Acme Plant #1",
  156. defaults={
  157. "address": "123 Demo Rd, Bangkok",
  158. "contact_name": "Somchai",
  159. "contact_phone": "+66 111 1111",
  160. "contact_email": "somchai@acme.example",
  161. },
  162. )
  163. # Provided services for the public website
  164. demo_services = [
  165. ("Pickup & Logistics", "Scheduled and on-demand scrap pickups handled safely and on time.",
  166. "We provide reliable pickup scheduling, routing, and documentation for your facilities.\n\n- Route planning and dispatch\n- On-demand requests\n- Driver assignments and tracking"),
  167. ("Material Sorting", "Sorting and consolidation to maximize recycling value.",
  168. "Our team sorts materials to your specifications to improve purity and value.\n\n- On-site sorting support\n- Bale and bag standards\n- Quality checks"),
  169. ("Weighing & Ticketing", "Accurate weighing with digital tickets and audit trail.",
  170. "Every pickup is weighed with calibrated equipment and recorded.\n\n- Calibrated scale records\n- Digital weigh tickets\n- Audit logs"),
  171. ("Invoicing & Payouts", "Transparent invoices and fast payouts.",
  172. "Automated invoicing and payouts reduce admin overhead.\n\n- Invoice generation\n- Payment tracking\n- Reconciliations"),
  173. ("Reporting & Analytics", "Reports that track volumes, value, and sustainability.",
  174. "Dashboards keep stakeholders informed.\n\n- Material volumes\n- Revenue and cost\n- ESG metrics"),
  175. ("Marketplace & Bidding", "Invite vetted recyclers and get competitive bids.",
  176. "Run open or sealed listings to find the best offer.\n\n- Public or invite-only\n- Bid history\n- Award workflows"),
  177. ("Compliance & Audits", "Documentation and controls for compliance.",
  178. "Stay compliant with audit-ready records.\n\n- Document control\n- Chain of custody\n- Access controls"),
  179. ("Consulting & Training", "Best practices and training for your team.",
  180. "Improve recycling outcomes with training and SOPs.\n\n- SOP development\n- Staff workshops\n- Continuous improvement"),
  181. ]
  182. for idx, (title, desc, body) in enumerate(demo_services):
  183. ProvidedService.objects.get_or_create(
  184. organization=org,
  185. title=title,
  186. defaults={
  187. "description": desc,
  188. "body": body,
  189. "display_order": idx,
  190. "is_enabled": True,
  191. },
  192. )
  193. pickup = PickupOrder.objects.create(
  194. organization=org,
  195. customer=customer,
  196. site=site,
  197. status=PickupOrder.STATUS_SCHEDULED,
  198. scheduled_at=now + timezone.timedelta(days=1),
  199. assigned_driver=driver,
  200. created_by=manager,
  201. notes="Demo pickup order",
  202. )
  203. PickupItem.objects.create(pickup=pickup, material=pet, estimated_qty=Decimal("100.0"), unit=Material.UNIT_KG)
  204. PickupItem.objects.create(pickup=pickup, material=can, estimated_qty=Decimal("50.0"), unit=Material.UNIT_KG)
  205. ticket = WeighTicket.objects.create(
  206. pickup=pickup,
  207. ticket_number=f"WT-{pickup.id}",
  208. gross_weight=Decimal("200.000"),
  209. tare_weight=Decimal("40.000"),
  210. net_weight=Decimal("160.000"),
  211. unit=Material.UNIT_KG,
  212. recorded_by=manager,
  213. )
  214. WeighLine.objects.create(ticket=ticket, material=pet, quantity=Decimal("110.000"), unit=Material.UNIT_KG)
  215. WeighLine.objects.create(ticket=ticket, material=can, quantity=Decimal("50.000"), unit=Material.UNIT_KG)
  216. pickup.status = PickupOrder.STATUS_WEIGHED
  217. pickup.save(update_fields=["status"])
  218. invoice = generate_invoice_for_pickup(pickup)
  219. # Create a demo scrap listing and a bid
  220. listing = ScrapListing.objects.create(
  221. organization=org,
  222. customer=customer,
  223. site=site,
  224. title="Monthly PET + Cans lot",
  225. description="Estimated quantities of PET and aluminum cans available",
  226. auction_type=ScrapListing.TYPE_OPEN,
  227. currency_code="THB",
  228. reserve_price=Decimal("500.00"),
  229. min_increment=Decimal("50.00"),
  230. status=ScrapListing.STATUS_OPEN,
  231. is_public=False,
  232. starts_at=now,
  233. created_by=manager,
  234. )
  235. ScrapListingItem.objects.create(listing=listing, material=pet, quantity_estimate=Decimal("100.0"), unit=Material.UNIT_KG)
  236. ScrapListingItem.objects.create(listing=listing, material=can, quantity_estimate=Decimal("50.0"), unit=Material.UNIT_KG)
  237. # Invite-only demo: invite bidder_org then place bid
  238. from recycle_core.models import ScrapListingInvite
  239. ScrapListingInvite.objects.get_or_create(listing=listing, invited_org=bidder_org, invited_user=buyer)
  240. ScrapBid.objects.create(listing=listing, bidder_org=bidder_org, bidder_user=buyer, price_total=Decimal("550.00"), message="Ready to collect within 48h")
  241. self.stdout.write(self.style.SUCCESS("Seeded Ecoloop demo data"))
  242. self.stdout.write(f"Organization: {org.name} ({org.code})")
  243. self.stdout.write(f"Customer: {customer.name}")
  244. self.stdout.write(f"Pickup: {pickup.id} status={pickup.status}")
  245. self.stdout.write(f"WeighTicket: {ticket.ticket_number}")
  246. self.stdout.write(f"Invoice: {invoice.id} total={invoice.total_amount} {invoice.currency_code}")
  247. self.stdout.write(f"Scrap Listing: {listing.id} status={listing.status}")