Bez popisu

seed_ecoloop.py 14KB

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