Нема описа

models.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. from __future__ import annotations
  2. from django.conf import settings
  3. from django.contrib.auth import get_user_model
  4. from django.contrib.contenttypes.fields import GenericForeignKey
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.db import models
  7. from django.utils import timezone
  8. from django.utils.translation import gettext_lazy as _
  9. from orgs.models import Organization
  10. from markdownfield.models import MarkdownField, RenderedMarkdownField
  11. from markdownfield.validators import VALIDATOR_STANDARD
  12. User = get_user_model()
  13. class TimestampedModel(models.Model):
  14. created_at = models.DateTimeField(auto_now_add=True)
  15. updated_at = models.DateTimeField(auto_now=True)
  16. class Meta:
  17. abstract = True
  18. ## Organization and related tenancy models moved to orgs.models
  19. class MaterialCategory(TimestampedModel):
  20. organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="material_categories")
  21. # Limit to a curated, preset set of category names
  22. CATEGORY_CHOICES = (
  23. ("Plastics", "Plastics"),
  24. ("Metals", "Metals"),
  25. ("Paper", "Paper"),
  26. ("Glass", "Glass"),
  27. ("Electronics", "Electronics"),
  28. ("Wood", "Wood"),
  29. ("Rubber", "Rubber"),
  30. ("Textiles", "Textiles"),
  31. ("Organic", "Organic"),
  32. ("Mixed", "Mixed"),
  33. )
  34. name = models.CharField(max_length=255, choices=CATEGORY_CHOICES)
  35. class Meta:
  36. unique_together = ("organization", "name")
  37. def __str__(self):
  38. return self.name
  39. class ProvidedService(TimestampedModel):
  40. organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="services")
  41. TITLE_CHOICES = (
  42. ("Pickup & Logistics", _("Pickup & Logistics")),
  43. ("Material Sorting", _("Material Sorting")),
  44. ("Weighing & Ticketing", _("Weighing & Ticketing")),
  45. ("Invoicing & Payouts", _("Invoicing & Payouts")),
  46. ("Reporting & Analytics", _("Reporting & Analytics")),
  47. ("Marketplace & Bidding", _("Marketplace & Bidding")),
  48. ("Compliance & Audits", _("Compliance & Audits")),
  49. ("Consulting & Training", _("Consulting & Training")),
  50. )
  51. title = models.CharField(max_length=100, choices=TITLE_CHOICES)
  52. # Short summary text
  53. description = models.TextField()
  54. # Long-form markdown body
  55. body = MarkdownField(rendered_field="body_html", validator=VALIDATOR_STANDARD, blank=True, null=True)
  56. body_html = RenderedMarkdownField(blank=True, null=True)
  57. display_order = models.PositiveIntegerField(default=0)
  58. is_enabled = models.BooleanField(default=True)
  59. IMAGE_NAME_MAP = {
  60. "Pickup & Logistics": "pickup-logistics.png",
  61. "Material Sorting": "material-sorting.png",
  62. "Weighing & Ticketing": "weighing-ticketing.png",
  63. "Invoicing & Payouts": "invoicing-payouts.png",
  64. "Reporting & Analytics": "reporting-analytics.png",
  65. "Marketplace & Bidding": "marketplace-bidding.png",
  66. "Compliance & Audits": "compliance-audits.png",
  67. "Consulting & Training": "consulting-training.png",
  68. }
  69. @property
  70. def image_name(self) -> str:
  71. return self.IMAGE_NAME_MAP.get(self.title, "default-service.png")
  72. class Meta:
  73. ordering = ["display_order"]
  74. def __str__(self) -> str:
  75. return self.title
  76. class Material(TimestampedModel):
  77. organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="materials")
  78. # Preset category choices (no FK)
  79. CATEGORY_CHOICES = MaterialCategory.CATEGORY_CHOICES
  80. category = models.CharField(max_length=64, choices=CATEGORY_CHOICES)
  81. name = models.CharField(max_length=255)
  82. code = models.CharField(max_length=64, blank=True)
  83. # unit choices keep MVP simple; conversions out of scope for now
  84. UNIT_KG = "kg"
  85. UNIT_LB = "lb"
  86. UNIT_PCS = "pcs"
  87. UNIT_CHOICES = (
  88. (UNIT_KG, "Kilogram"),
  89. (UNIT_LB, "Pound"),
  90. (UNIT_PCS, "Pieces"),
  91. )
  92. default_unit = models.CharField(max_length=8, choices=UNIT_CHOICES, default=UNIT_KG)
  93. class Meta:
  94. unique_together = ("organization", "name")
  95. def __str__(self):
  96. return self.name
  97. class MaterialImage(TimestampedModel):
  98. material = models.ForeignKey(Material, on_delete=models.CASCADE, related_name="images")
  99. image = models.ImageField(upload_to="materials/%Y/%m/")
  100. caption = models.CharField(max_length=255, blank=True)
  101. display_order = models.PositiveIntegerField(default=0)
  102. class Meta:
  103. ordering = ["display_order", "id"]
  104. def __str__(self) -> str:
  105. return self.caption or f"MaterialImage #{self.id}"
  106. class PriceList(TimestampedModel):
  107. organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="price_lists")
  108. name = models.CharField(max_length=255)
  109. currency_code = models.CharField(max_length=8, default="USD")
  110. effective_from = models.DateField(null=True, blank=True)
  111. effective_to = models.DateField(null=True, blank=True)
  112. def __str__(self):
  113. return f"{self.name} ({self.currency_code})"
  114. class PriceListItem(TimestampedModel):
  115. DIRECTION_BUY = "buy" # we pay the customer
  116. DIRECTION_SELL = "sell" # we invoice the customer
  117. DIRECTION_CHOICES = (
  118. (DIRECTION_BUY, "Buy from customer"),
  119. (DIRECTION_SELL, "Sell to customer"),
  120. )
  121. price_list = models.ForeignKey(PriceList, on_delete=models.CASCADE, related_name="items")
  122. material = models.ForeignKey(Material, on_delete=models.PROTECT, related_name="price_items")
  123. unit = models.CharField(max_length=8, choices=Material.UNIT_CHOICES, default=Material.UNIT_KG)
  124. unit_price = models.DecimalField(max_digits=12, decimal_places=2)
  125. direction = models.CharField(max_length=8, choices=DIRECTION_CHOICES, default=DIRECTION_SELL)
  126. class Meta:
  127. unique_together = ("price_list", "material", "unit", "direction")
  128. class Customer(TimestampedModel):
  129. organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="customers")
  130. name = models.CharField(max_length=255)
  131. email = models.EmailField(blank=True)
  132. phone = models.CharField(max_length=64, blank=True)
  133. billing_address = models.TextField(blank=True)
  134. price_list = models.ForeignKey(PriceList, on_delete=models.SET_NULL, null=True, blank=True, related_name="customers")
  135. def __str__(self):
  136. return self.name
  137. class CustomerSite(TimestampedModel):
  138. customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="sites")
  139. name = models.CharField(max_length=255, blank=True)
  140. address = models.TextField()
  141. contact_name = models.CharField(max_length=255, blank=True)
  142. contact_phone = models.CharField(max_length=64, blank=True)
  143. contact_email = models.EmailField(blank=True)
  144. def __str__(self):
  145. return self.name or f"Site {self.id}"
  146. class ServiceAgreement(TimestampedModel):
  147. customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="agreements")
  148. site = models.ForeignKey(CustomerSite, on_delete=models.SET_NULL, null=True, blank=True, related_name="agreements")
  149. price_list = models.ForeignKey(PriceList, on_delete=models.PROTECT, related_name="agreements")
  150. valid_from = models.DateField(null=True, blank=True)
  151. valid_to = models.DateField(null=True, blank=True)
  152. class PickupOrder(TimestampedModel):
  153. STATUS_REQUESTED = "requested"
  154. STATUS_SCHEDULED = "scheduled"
  155. STATUS_EN_ROUTE = "en_route"
  156. STATUS_COLLECTING = "collecting"
  157. STATUS_AT_FACILITY = "at_facility"
  158. STATUS_WEIGHED = "weighed"
  159. STATUS_INVOICED = "invoiced"
  160. STATUS_COMPLETED = "completed"
  161. STATUS_CANCELED = "canceled"
  162. STATUS_CHOICES = (
  163. (STATUS_REQUESTED, "Requested"),
  164. (STATUS_SCHEDULED, "Scheduled"),
  165. (STATUS_EN_ROUTE, "En Route"),
  166. (STATUS_COLLECTING, "Collecting"),
  167. (STATUS_AT_FACILITY, "At Facility"),
  168. (STATUS_WEIGHED, "Weighed"),
  169. (STATUS_INVOICED, "Invoiced"),
  170. (STATUS_COMPLETED, "Completed"),
  171. (STATUS_CANCELED, "Canceled"),
  172. )
  173. organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="pickup_orders")
  174. customer = models.ForeignKey(Customer, on_delete=models.PROTECT, related_name="pickup_orders")
  175. site = models.ForeignKey(CustomerSite, on_delete=models.PROTECT, related_name="pickup_orders")
  176. status = models.CharField(max_length=16, choices=STATUS_CHOICES, default=STATUS_REQUESTED, db_index=True)
  177. scheduled_at = models.DateTimeField(null=True, blank=True)
  178. assigned_driver = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="assigned_pickups")
  179. created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="created_pickups")
  180. completed_at = models.DateTimeField(null=True, blank=True)
  181. notes = models.TextField(blank=True)
  182. def __str__(self):
  183. return f"Pickup #{self.id} - {self.customer.name}"
  184. class Meta:
  185. permissions = (
  186. ("assign_driver", "Can assign driver to pickup"),
  187. ("set_pickup_status", "Can set pickup status"),
  188. ("create_weigh_ticket", "Can create weigh ticket for pickup"),
  189. ("generate_invoice", "Can generate invoice for pickup"),
  190. )
  191. class PickupItem(TimestampedModel):
  192. pickup = models.ForeignKey(PickupOrder, on_delete=models.CASCADE, related_name="items")
  193. material = models.ForeignKey(Material, on_delete=models.PROTECT)
  194. estimated_qty = models.DecimalField(max_digits=12, decimal_places=3, null=True, blank=True)
  195. unit = models.CharField(max_length=8, choices=Material.UNIT_CHOICES, default=Material.UNIT_KG)
  196. class WeighTicket(TimestampedModel):
  197. pickup = models.OneToOneField(PickupOrder, on_delete=models.CASCADE, related_name="weigh_ticket")
  198. ticket_number = models.CharField(max_length=64, blank=True)
  199. gross_weight = models.DecimalField(max_digits=12, decimal_places=3)
  200. tare_weight = models.DecimalField(max_digits=12, decimal_places=3)
  201. net_weight = models.DecimalField(max_digits=12, decimal_places=3)
  202. unit = models.CharField(max_length=8, choices=Material.UNIT_CHOICES, default=Material.UNIT_KG)
  203. recorded_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="weigh_tickets")
  204. recorded_at = models.DateTimeField(default=timezone.now)
  205. class Meta:
  206. permissions = (
  207. ("generate_invoice", "Can generate invoice from weigh ticket"),
  208. )
  209. class WeighLine(TimestampedModel):
  210. ticket = models.ForeignKey(WeighTicket, on_delete=models.CASCADE, related_name="lines")
  211. material = models.ForeignKey(Material, on_delete=models.PROTECT)
  212. quantity = models.DecimalField(max_digits=12, decimal_places=3)
  213. unit = models.CharField(max_length=8, choices=Material.UNIT_CHOICES, default=Material.UNIT_KG)
  214. # Billing models have moved to the `billing` app
  215. class Document(TimestampedModel):
  216. organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="documents")
  217. file = models.FileField(upload_to="documents/%Y/%m/%d/")
  218. kind = models.CharField(max_length=64, blank=True)
  219. # Generic attachment to any model instance
  220. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  221. object_id = models.PositiveIntegerField()
  222. content_object = GenericForeignKey("content_type", "object_id")
  223. uploaded_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
  224. class AuditLog(TimestampedModel):
  225. organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="audit_logs")
  226. user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
  227. action = models.CharField(max_length=64)
  228. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  229. object_id = models.PositiveIntegerField()
  230. content_object = GenericForeignKey("content_type", "object_id")
  231. metadata = models.JSONField(default=dict, blank=True)
  232. class Meta:
  233. indexes = [
  234. models.Index(fields=["organization", "created_at"]),
  235. models.Index(fields=["action", "created_at"]),
  236. ]
  237. class ScrapListing(TimestampedModel):
  238. TYPE_OPEN = "open"
  239. TYPE_SEALED = "sealed"
  240. AUCTION_CHOICES = ((TYPE_OPEN, "Open"), (TYPE_SEALED, "Sealed"))
  241. STATUS_DRAFT = "draft"
  242. STATUS_OPEN = "open"
  243. STATUS_CLOSED = "closed"
  244. STATUS_AWARDED = "awarded"
  245. STATUS_CANCELED = "canceled"
  246. STATUS_CHOICES = (
  247. (STATUS_DRAFT, "Draft"),
  248. (STATUS_OPEN, "Open"),
  249. (STATUS_CLOSED, "Closed"),
  250. (STATUS_AWARDED, "Awarded"),
  251. (STATUS_CANCELED, "Canceled"),
  252. )
  253. organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="scrap_listings")
  254. customer = models.ForeignKey(Customer, on_delete=models.PROTECT, related_name="scrap_listings")
  255. site = models.ForeignKey(CustomerSite, on_delete=models.PROTECT, related_name="scrap_listings")
  256. title = models.CharField(max_length=255)
  257. description = models.TextField(blank=True)
  258. auction_type = models.CharField(max_length=16, choices=AUCTION_CHOICES, default=TYPE_OPEN)
  259. currency_code = models.CharField(max_length=8, default="USD")
  260. reserve_price = models.DecimalField(max_digits=14, decimal_places=2, null=True, blank=True)
  261. min_increment = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
  262. starts_at = models.DateTimeField(null=True, blank=True)
  263. ends_at = models.DateTimeField(null=True, blank=True)
  264. status = models.CharField(max_length=16, choices=STATUS_CHOICES, default=STATUS_DRAFT, db_index=True)
  265. is_public = models.BooleanField(default=True)
  266. created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="created_listings")
  267. def __str__(self):
  268. return f"Listing #{self.id} - {self.title}"
  269. class Meta:
  270. permissions = (
  271. ("open_listing", "Can open scrap listing"),
  272. ("close_listing", "Can close scrap listing"),
  273. ("award_listing", "Can award scrap listing"),
  274. )
  275. class ScrapListingItem(TimestampedModel):
  276. listing = models.ForeignKey(ScrapListing, on_delete=models.CASCADE, related_name="items")
  277. material = models.ForeignKey(Material, on_delete=models.PROTECT)
  278. quantity_estimate = models.DecimalField(max_digits=12, decimal_places=3)
  279. unit = models.CharField(max_length=8, choices=Material.UNIT_CHOICES, default=Material.UNIT_KG)
  280. class ScrapBid(TimestampedModel):
  281. STATUS_ACTIVE = "active"
  282. STATUS_RETRACTED = "retracted"
  283. STATUS_ACCEPTED = "accepted"
  284. STATUS_REJECTED = "rejected"
  285. STATUS_CHOICES = (
  286. (STATUS_ACTIVE, "Active"),
  287. (STATUS_RETRACTED, "Retracted"),
  288. (STATUS_ACCEPTED, "Accepted"),
  289. (STATUS_REJECTED, "Rejected"),
  290. )
  291. listing = models.ForeignKey(ScrapListing, on_delete=models.CASCADE, related_name="bids")
  292. bidder_org = models.ForeignKey(Organization, on_delete=models.PROTECT, related_name="bids")
  293. bidder_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="bids")
  294. price_total = models.DecimalField(max_digits=14, decimal_places=2)
  295. message = models.TextField(blank=True)
  296. status = models.CharField(max_length=16, choices=STATUS_CHOICES, default=STATUS_ACTIVE)
  297. class Meta:
  298. indexes = [models.Index(fields=["listing", "price_total"])]
  299. class ScrapAward(TimestampedModel):
  300. listing = models.OneToOneField(ScrapListing, on_delete=models.CASCADE, related_name="award")
  301. winning_bid = models.ForeignKey(ScrapBid, on_delete=models.PROTECT, related_name="awards")
  302. pickup = models.ForeignKey(PickupOrder, on_delete=models.SET_NULL, null=True, blank=True, related_name="awards")
  303. notes = models.TextField(blank=True)
  304. class ScrapListingInvite(TimestampedModel):
  305. """Invite a specific organization (and optionally a user) to bid on a listing.
  306. When a listing is not public, only invited orgs may place bids.
  307. """
  308. listing = models.ForeignKey(ScrapListing, on_delete=models.CASCADE, related_name="invites")
  309. invited_org = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="listing_invites")
  310. invited_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="listing_invites")
  311. class Meta:
  312. unique_together = ("listing", "invited_org")