nl-607 ol-607"> 607
+  >]
608
+  recycle_core_models_ScrapListing -> django_contrib_auth_models_User
609
+  [label=" created_by (created_listings)"] [arrowhead=none, arrowtail=dot, dir=both];
610
+
611
+  recycle_core_models_ScrapListing -> recycle_core_models_TimestampedModel
612
+  [label=" abstract\ninheritance"] [arrowhead=empty, arrowtail=none, dir=both];
613
+
614
+  recycle_core_models_ScrapListingItem -> recycle_core_models_ScrapListing
615
+  [label=" listing (items)"] [arrowhead=none, arrowtail=dot, dir=both];
616
+
617
+  recycle_core_models_ScrapListingItem -> recycle_core_models_Material
618
+  [label=" material (scraplistingitem)"] [arrowhead=none, arrowtail=dot, dir=both];
619
+
620
+  recycle_core_models_ScrapListingItem -> recycle_core_models_TimestampedModel
621
+  [label=" abstract\ninheritance"] [arrowhead=empty, arrowtail=none, dir=both];
622
+
623
+  recycle_core_models_ScrapBid -> recycle_core_models_ScrapListing
624
+  [label=" listing (bids)"] [arrowhead=none, arrowtail=dot, dir=both];
625
+
626
+  recycle_core_models_ScrapBid -> orgs_models_Organization
627
+  [label=" bidder_org (bids)"] [arrowhead=none, arrowtail=dot, dir=both];
628
+  django_contrib_auth_models_User [label=<
629
+  <TABLE BGCOLOR="white" BORDER="0" CELLBORDER="0" CELLSPACING="0">
630
+  <TR><TD COLSPAN="2" CELLPADDING="4" ALIGN="CENTER" BGCOLOR="#1b563f">
631
+  <FONT FACE="Roboto" POINT-SIZE="12" COLOR="white">User</FONT>
632
+  </TD></TR>
633
+  </TABLE>
634
+  >]
635
+  recycle_core_models_ScrapBid -> django_contrib_auth_models_User
636
+  [label=" bidder_user (bids)"] [arrowhead=none, arrowtail=dot, dir=both];
637
+
638
+  recycle_core_models_ScrapBid -> recycle_core_models_TimestampedModel
639
+  [label=" abstract\ninheritance"] [arrowhead=empty, arrowtail=none, dir=both];
640
+
641
+  recycle_core_models_ScrapAward -> recycle_core_models_ScrapListing
642
+  [label=" listing (award)"] [arrowhead=none, arrowtail=none, dir=both];
643
+
644
+  recycle_core_models_ScrapAward -> recycle_core_models_ScrapBid
645
+  [label=" winning_bid (awards)"] [arrowhead=none, arrowtail=dot, dir=both];
646
+
647
+  recycle_core_models_ScrapAward -> recycle_core_models_PickupOrder
648
+  [label=" pickup (awards)"] [arrowhead=none, arrowtail=dot, dir=both];
649
+
650
+  recycle_core_models_ScrapAward -> recycle_core_models_TimestampedModel
651
+  [label=" abstract\ninheritance"] [arrowhead=empty, arrowtail=none, dir=both];
652
+
653
+  recycle_core_models_ScrapListingInvite -> recycle_core_models_ScrapListing
654
+  [label=" listing (invites)"] [arrowhead=none, arrowtail=dot, dir=both];
655
+
656
+  recycle_core_models_ScrapListingInvite -> orgs_models_Organization
657
+  [label=" invited_org (listing_invites)"] [arrowhead=none, arrowtail=dot, dir=both];
658
+  django_contrib_auth_models_User [label=<
659
+  <TABLE BGCOLOR="white" BORDER="0" CELLBORDER="0" CELLSPACING="0">
660
+  <TR><TD COLSPAN="2" CELLPADDING="4" ALIGN="CENTER" BGCOLOR="#1b563f">
661
+  <FONT FACE="Roboto" POINT-SIZE="12" COLOR="white">User</FONT>
662
+  </TD></TR>
663
+  </TABLE>
664
+  >]
665
+  recycle_core_models_ScrapListingInvite -> django_contrib_auth_models_User
666
+  [label=" invited_user (listing_invites)"] [arrowhead=none, arrowtail=dot, dir=both];
667
+
668
+  recycle_core_models_ScrapListingInvite -> recycle_core_models_TimestampedModel
669
+  [label=" abstract\ninheritance"] [arrowhead=empty, arrowtail=none, dir=both];
670
+
671
+
672
+}

BIN
erd.pdf


BIN
erd.png


+ 4 - 1
public_frontend/forms.py

@@ -4,12 +4,16 @@ from django import forms
4 4
 
5 5
 
6 6
 class PickupRequestForm(forms.Form):
7
+    class MultiFileInput(forms.ClearableFileInput):
8
+        allow_multiple_selected = True
9
+
7 10
     name = forms.CharField(max_length=255)
8 11
     email = forms.EmailField(required=False)
9 12
     phone = forms.CharField(max_length=64, required=False)
10 13
     address = forms.CharField(widget=forms.Textarea)
11 14
     preferred_at = forms.DateTimeField(required=False, widget=forms.DateTimeInput(attrs={"type": "datetime-local"}))
12 15
     materials = forms.CharField(label="Materials/Notes", widget=forms.Textarea, required=False)
16
+    photos = forms.FileField(required=False, widget=MultiFileInput, help_text="Optional: upload photos of scrap")
13 17
 
14 18
 
15 19
 class ContactForm(forms.Form):
@@ -18,4 +22,3 @@ class ContactForm(forms.Form):
18 22
     phone = forms.CharField(max_length=64, required=False)
19 23
     subject = forms.CharField(max_length=255, required=False)
20 24
     message = forms.CharField(widget=forms.Textarea)
21
-

+ 5 - 1
public_frontend/templates/public_frontend/home.html

@@ -76,7 +76,7 @@
76 76
   {# Pickup Request Section #}
77 77
   <section id="pickup-request">
78 78
     <h2 class="text-2xl font-semibold mb-3">Request a Pickup</h2>
79
-    <form method="post" action="{% url 'public_frontend:pickup_request' %}" class="bg-white rounded-lg shadow-md p-4 grid gap-4">
79
+    <form method="post" enctype="multipart/form-data" action="{% url 'public_frontend:pickup_request' %}" class="bg-white rounded-lg shadow-md p-4 grid gap-4">
80 80
       {% csrf_token %}
81 81
       <div>
82 82
         <label class="block text-sm font-medium mb-1">Name</label>
@@ -101,6 +101,10 @@
101 101
         <textarea name="materials" class="w-full border rounded px-3 py-2" rows="4">{{ pickup_form.materials.value|default:'' }}</textarea>
102 102
       </div>
103 103
       <div>
104
+        <label class="block text-sm font-medium mb-1">Photos (optional)</label>
105
+        <input type="file" name="photos" multiple accept="image/*" class="w-full border rounded px-3 py-2">
106
+      </div>
107
+      <div>
104 108
         <button class="btn-primary" type="submit">Submit Request</button>
105 109
       </div>
106 110
     </form>

+ 1 - 2
public_frontend/templates/public_frontend/materials_list.html

@@ -14,7 +14,7 @@
14 14
       {% for m in materials %}
15 15
         <tr class="border-t">
16 16
           <td class="px-4 py-2">{{ m.name }}</td>
17
-          <td class="px-4 py-2">{{ m.category.name }}</td>
17
+          <td class="px-4 py-2">{{ m.get_category_display }}</td>
18 18
           <td class="px-4 py-2">{{ m.get_default_unit_display }}</td>
19 19
         </tr>
20 20
       {% empty %}
@@ -24,4 +24,3 @@
24 24
   </table>
25 25
   </div>
26 26
 {% endblock %}
27
-

+ 5 - 2
public_frontend/templates/public_frontend/pickup_request.html

@@ -2,7 +2,7 @@
2 2
 {% block title %}Request Pickup{% endblock %}
3 3
 {% block content %}
4 4
 <h1 class="text-xl font-semibold mb-4">Request a Pickup</h1>
5
-<form method="post" class="bg-white rounded shadow p-4 grid gap-4">
5
+<form method="post" enctype="multipart/form-data" class="bg-white rounded shadow p-4 grid gap-4">
6 6
   {% csrf_token %}
7 7
   <div>
8 8
     <label class="block text-sm font-medium mb-1">Name</label>
@@ -35,9 +35,12 @@
35 35
     <textarea name="materials" class="w-full border rounded px-3 py-2" rows="4">{{ form.materials.value|default:'' }}</textarea>
36 36
   </div>
37 37
   <div>
38
+    <label class="block text-sm font-medium mb-1">Photos (optional)</label>
39
+    <input type="file" name="photos" multiple accept="image/*" class="w-full border rounded px-3 py-2">
40
+  </div>
41
+  <div>
38 42
     <button class="btn-primary" type="submit">Submit Request</button>
39 43
   </div>
40 44
 </form>
41 45
 <style>.btn-primary{background:#1d4ed8;color:white;padding:.5rem .75rem;border-radius:.375rem}</style>
42 46
 {% endblock %}
43
-

+ 20 - 17
public_frontend/views.py

@@ -12,6 +12,10 @@ from cms.models import Post, PostCategory
12 12
 
13 13
 from .forms import PickupRequestForm, ContactForm
14 14
 from .models import Lead
15
+from recycle_core.controllers.pickup_request import (
16
+    PickupRequestController,
17
+    PickupRequestData,
18
+)
15 19
 
16 20
 
17 21
 def home(request):
@@ -98,30 +102,29 @@ def service_detail(request, pk: int):
98 102
 
99 103
 def pickup_request(request):
100 104
     org = getattr(request, "org", None)
101
-    form = PickupRequestForm(request.POST or None)
105
+    form = PickupRequestForm(request.POST or None, request.FILES or None)
102 106
     if request.method == "POST":
103 107
         if not org:
104 108
             messages.error(request, "Organization context missing.")
105 109
             return redirect("public_frontend:pickup_request")
106 110
         if form.is_valid():
107
-            # Store as a Lead for staff to process; PickupOrder requires customer/site
108
-            message = (
109
-                f"Pickup Request\n"
110
-                f"Address: {form.cleaned_data.get('address')}\n"
111
-                f"Preferred: {form.cleaned_data.get('preferred_at') or ''}\n"
112
-                f"Materials: {form.cleaned_data.get('materials') or ''}"
113
-            )
114
-            Lead.objects.create(
111
+            ctrl = PickupRequestController()
112
+            data = PickupRequestData(
115 113
                 organization=org,
116
-                name=form.cleaned_data.get('name'),
117
-                email=form.cleaned_data.get('email',''),
118
-                phone=form.cleaned_data.get('phone',''),
119
-                subject='Pickup Request',
120
-                message=message,
121
-                source='pickup_request',
114
+                name=form.cleaned_data.get("name"),
115
+                email=form.cleaned_data.get("email", ""),
116
+                phone=form.cleaned_data.get("phone", ""),
117
+                address=form.cleaned_data.get("address", ""),
118
+                materials=form.cleaned_data.get("materials", ""),
119
+                preferred_at=form.cleaned_data.get("preferred_at"),
120
+                files=request.FILES.getlist("photos") if hasattr(request, "FILES") and "photos" in request.FILES else [],
122 121
             )
123
-            messages.success(request, "Thanks! Your pickup request was submitted.")
124
-            return redirect("public_frontend:home")
122
+            result = ctrl.submit(data)
123
+            if result.ok:
124
+                messages.success(request, "Thanks! Your pickup request was submitted.")
125
+                return redirect("public_frontend:home")
126
+            else:
127
+                messages.error(request, result.error or "Unable to submit your request.")
125 128
         messages.error(request, "Please correct the errors below.")
126 129
     return render(request, "public_frontend/pickup_request.html", {"form": form, "org": org})
127 130
 

+ 5 - 1
recycle_core/admin.py

@@ -39,9 +39,13 @@ class MaterialCategoryAdmin(OrgScopedAdmin):
39 39
 
40 40
 @admin.register(models.Material)
41 41
 class MaterialAdmin(OrgScopedAdmin):
42
-    list_display = ("name", "code", "category", "organization", "default_unit")
42
+    list_display = ("name", "code", "get_category_display", "organization", "default_unit")
43 43
     list_filter = ("default_unit", "category")
44 44
     search_fields = ("name", "code")
45
+    class MaterialImageInline(admin.TabularInline):
46
+        model = models.MaterialImage
47
+        extra = 1
48
+    inlines = [MaterialImageInline]
45 49
 
46 50
 
47 51
 @admin.register(models.PriceList)

+ 2 - 0
recycle_core/controllers/__init__.py

@@ -0,0 +1,2 @@
1
+from __future__ import annotations
2
+

+ 80 - 0
recycle_core/controllers/pickup_request.py

@@ -0,0 +1,80 @@
1
+from __future__ import annotations
2
+
3
+from dataclasses import dataclass
4
+from typing import Iterable, List, Optional
5
+from django.contrib.contenttypes.models import ContentType
6
+from django.utils import timezone
7
+
8
+from orgs.models import Organization
9
+from recycle_core.models import Document
10
+
11
+
12
+@dataclass
13
+class PickupRequestData:
14
+    organization: Organization
15
+    name: str
16
+    email: str = ""
17
+    phone: str = ""
18
+    address: str = ""
19
+    materials: str = ""
20
+    preferred_at: Optional[timezone.datetime] = None
21
+    files: Optional[Iterable] = None  # iterable of UploadedFile
22
+
23
+
24
+@dataclass
25
+class PickupRequestResult:
26
+    ok: bool
27
+    lead_id: Optional[int] = None
28
+    error: Optional[str] = None
29
+    document_ids: List[int] = None
30
+
31
+
32
+class PickupRequestController:
33
+    """Application layer controller for the fast-path pickup request.
34
+
35
+    - Creates a Lead scoped to an Organization
36
+    - Stores any uploaded photos/documents as Document records attached to the Lead
37
+    """
38
+
39
+    def submit(self, data: PickupRequestData) -> PickupRequestResult:
40
+        from public_frontend.models import Lead  # import locally to avoid circular imports
41
+
42
+        try:
43
+            # Prepare message body for staff
44
+            message = (
45
+                f"Pickup Request\n"
46
+                f"Address: {data.address}\n"
47
+                f"Preferred: {data.preferred_at or ''}\n"
48
+                f"Materials: {data.materials or ''}"
49
+            )
50
+
51
+            lead = Lead.objects.create(
52
+                organization=data.organization,
53
+                name=data.name,
54
+                email=data.email or "",
55
+                phone=data.phone or "",
56
+                subject="Pickup Request",
57
+                message=message,
58
+                source="pickup_request",
59
+            )
60
+
61
+            # Attach uploaded files as Documents linked to the Lead
62
+            doc_ids: List[int] = []
63
+            if data.files:
64
+                ct = ContentType.objects.get_for_model(Lead)
65
+                for idx, f in enumerate(data.files):
66
+                    doc = Document.objects.create(
67
+                        organization=data.organization,
68
+                        file=f,
69
+                        kind="pickup_request",
70
+                        content_type=ct,
71
+                        object_id=lead.id,
72
+                        uploaded_by=None,
73
+                    )
74
+                    doc_ids.append(doc.id)
75
+
76
+            return PickupRequestResult(ok=True, lead_id=lead.id, document_ids=doc_ids)
77
+
78
+        except Exception as e:
79
+            return PickupRequestResult(ok=False, error=str(e), document_ids=[])
80
+

+ 51 - 1
recycle_core/forms.py

@@ -1,4 +1,5 @@
1 1
 from django import forms
2
+from django.core.exceptions import ValidationError
2 3
 from django.contrib.auth import get_user_model
3 4
 from decimal import Decimal
4 5
 from django.utils import timezone
@@ -7,6 +8,7 @@ from django.contrib.contenttypes.models import ContentType
7 8
 from .models import (
8 9
     MaterialCategory,
9 10
     Material,
11
+    MaterialImage,
10 12
     ProvidedService,
11 13
     Customer,
12 14
     CustomerSite,
@@ -21,10 +23,58 @@ class MaterialCategoryForm(forms.ModelForm):
21 23
         fields = ["organization", "name"]
22 24
 
23 25
 
26
+class MultiFileInput(forms.ClearableFileInput):
27
+    allow_multiple_selected = True
28
+
29
+
30
+class MultiImageField(forms.Field):
31
+    widget = MultiFileInput
32
+
33
+    def __init__(self, *args, **kwargs):
34
+        kwargs.setdefault("required", False)
35
+        super().__init__(*args, **kwargs)
36
+
37
+    def to_python(self, data):
38
+        return data
39
+
40
+    def validate(self, value):
41
+        # Basic required check; skip per-file validation here
42
+        if self.required and not value:
43
+            raise ValidationError("This field is required.")
44
+
45
+
24 46
 class MaterialForm(forms.ModelForm):
47
+    images = MultiImageField(help_text="Upload one or more sample images (optional)")
48
+
25 49
     class Meta:
26 50
         model = Material
27
-        fields = ["organization", "category", "name", "code", "default_unit"]
51
+        fields = ["organization", "category", "name", "code", "default_unit", "images"]
52
+
53
+    def save(self, commit=True):
54
+        instance = super().save(commit=commit)
55
+        files = self.files.getlist("images") if hasattr(self, "files") else []
56
+        if commit and files:
57
+            # Instance has a PK; we can create images now
58
+            order_start = instance.images.count()
59
+            for i, f in enumerate(files):
60
+                MaterialImage.objects.create(material=instance, image=f, display_order=order_start + i)
61
+        else:
62
+            # Defer image saving until caller completes save
63
+            self._pending_images = files
64
+        return instance
65
+
66
+    def save_images(self, instance: Material | None = None):
67
+        """Persist any pending images after the Material has been saved."""
68
+        if not hasattr(self, "_pending_images"):
69
+            return
70
+        target = instance or getattr(self, "instance", None)
71
+        if not target or not getattr(target, "pk", None):
72
+            return
73
+        order_start = target.images.count()
74
+        for i, f in enumerate(self._pending_images or []):
75
+            MaterialImage.objects.create(material=target, image=f, display_order=order_start + i)
76
+        # Clear pending list
77
+        self._pending_images = []
28 78
 
29 79
 
30 80
 class CustomerForm(forms.ModelForm):

+ 69 - 4
recycle_core/management/commands/seed_ecoloop.py

@@ -35,6 +35,7 @@ class Command(BaseCommand):
35 35
     def add_arguments(self, parser):
36 36
         parser.add_argument("--org", default="DEMO", help="Organization code/id/name to seed (default: DEMO)")
37 37
         parser.add_argument("--bidder-org", dest="bidder_org", default="REC1", help="Bidder org code/id/name (default: REC1)")
38
+        parser.add_argument("--reset", action="store_true", help="Delete existing data for the target orgs before seeding")
38 39
 
39 40
     def handle(self, *args, **options):
40 41
         now = timezone.now()
@@ -59,6 +60,70 @@ class Command(BaseCommand):
59 60
         org = _resolve_org(org_ident, default_name=("Ecoloop " + str(org_ident)))
60 61
         bidder_org = _resolve_org(bidder_ident, default_name="Recycler Co.")
61 62
 
63
+        # Optionally reset existing demo data (scoped to the selected orgs)
64
+        if options.get("reset"):
65
+            from recycle_core.models import (
66
+                ScrapAward,
67
+                ScrapBid,
68
+                ScrapListingInvite,
69
+                ScrapListingItem,
70
+                ScrapListing,
71
+                WeighLine,
72
+                WeighTicket,
73
+                PickupItem,
74
+                PickupOrder,
75
+                InvoiceLine,
76
+                Invoice,
77
+                Payment,
78
+                Payout,
79
+                ServiceAgreement,
80
+                CustomerSite,
81
+                Customer,
82
+                PriceListItem,
83
+                PriceList,
84
+                Material,
85
+                MaterialCategory,
86
+                ProvidedService,
87
+            )
88
+
89
+            def _wipe_for(o: Organization):
90
+                # Marketplace
91
+                ScrapAward.objects.filter(listing__organization=o).delete()
92
+                ScrapBid.objects.filter(listing__organization=o).delete()
93
+                ScrapListingInvite.objects.filter(listing__organization=o).delete()
94
+                ScrapListingItem.objects.filter(listing__organization=o).delete()
95
+                ScrapListing.objects.filter(organization=o).delete()
96
+
97
+                # Operations
98
+                WeighLine.objects.filter(ticket__pickup__organization=o).delete()
99
+                WeighTicket.objects.filter(pickup__organization=o).delete()
100
+                PickupItem.objects.filter(pickup__organization=o).delete()
101
+                PickupOrder.objects.filter(organization=o).delete()
102
+
103
+                # Billing
104
+                InvoiceLine.objects.filter(invoice__organization=o).delete()
105
+                Payment.objects.filter(invoice__organization=o).delete()
106
+                Invoice.objects.filter(organization=o).delete()
107
+                Payout.objects.filter(organization=o).delete()
108
+
109
+                # Customers and agreements
110
+                ServiceAgreement.objects.filter(customer__organization=o).delete()
111
+                CustomerSite.objects.filter(customer__organization=o).delete()
112
+                Customer.objects.filter(organization=o).delete()
113
+
114
+                # Pricing
115
+                PriceListItem.objects.filter(price_list__organization=o).delete()
116
+                PriceList.objects.filter(organization=o).delete()
117
+
118
+                # Inventory and services
119
+                Material.objects.filter(organization=o).delete()
120
+                ProvidedService.objects.filter(organization=o).delete()
121
+                MaterialCategory.objects.filter(organization=o).delete()
122
+
123
+            _wipe_for(org)
124
+            _wipe_for(bidder_org)
125
+            self.stdout.write(self.style.WARNING("Existing data removed for selected orgs (reset)."))
126
+
62 127
         # Users
63 128
         manager = User.objects.filter(username="manager").first()
64 129
         if not manager:
@@ -80,10 +145,10 @@ class Command(BaseCommand):
80 145
         metals, _ = MaterialCategory.objects.get_or_create(organization=org, name="Metals")
81 146
         paper, _ = MaterialCategory.objects.get_or_create(organization=org, name="Paper")
82 147
 
83
-        pet, _ = Material.objects.get_or_create(organization=org, category=plastics, name="PET", defaults={"default_unit": Material.UNIT_KG})
84
-        hdpe, _ = Material.objects.get_or_create(organization=org, category=plastics, name="HDPE", defaults={"default_unit": Material.UNIT_KG})
85
-        can, _ = Material.objects.get_or_create(organization=org, category=metals, name="Aluminum Can", defaults={"default_unit": Material.UNIT_KG})
86
-        cardboard, _ = Material.objects.get_or_create(organization=org, category=paper, name="Cardboard", defaults={"default_unit": Material.UNIT_KG})
148
+        pet, _ = Material.objects.get_or_create(organization=org, category="Plastics", name="PET", defaults={"default_unit": Material.UNIT_KG})
149
+        hdpe, _ = Material.objects.get_or_create(organization=org, category="Plastics", name="HDPE", defaults={"default_unit": Material.UNIT_KG})
150
+        can, _ = Material.objects.get_or_create(organization=org, category="Metals", name="Aluminum Can", defaults={"default_unit": Material.UNIT_KG})
151
+        cardboard, _ = Material.objects.get_or_create(organization=org, category="Paper", name="Cardboard", defaults={"default_unit": Material.UNIT_KG})
87 152
 
88 153
         # Price list
89 154
         pl, _ = PriceList.objects.get_or_create(

+ 18 - 0
recycle_core/migrations/0006_alter_materialcategory_name.py

@@ -0,0 +1,18 @@
1
+# Generated by Django 4.2.24 on 2025-09-22 09:17
2
+
3
+from django.db import migrations, models
4
+
5
+
6
+class Migration(migrations.Migration):
7
+
8
+    dependencies = [
9
+        ('recycle_core', '0005_providedservice_is_enabled'),
10
+    ]
11
+
12
+    operations = [
13
+        migrations.AlterField(
14
+            model_name='materialcategory',
15
+            name='name',
16
+            field=models.CharField(choices=[('Plastics', 'Plastics'), ('Metals', 'Metals'), ('Paper', 'Paper'), ('Glass', 'Glass'), ('Electronics', 'Electronics'), ('Wood', 'Wood'), ('Rubber', 'Rubber'), ('Textiles', 'Textiles'), ('Organic', 'Organic'), ('Mixed', 'Mixed')], max_length=255),
17
+        ),
18
+    ]

+ 18 - 0
recycle_core/migrations/0007_alter_material_category.py

@@ -0,0 +1,18 @@
1
+# Generated by Django 4.2.24 on 2025-09-22 09:23
2
+
3
+from django.db import migrations, models
4
+
5
+
6
+class Migration(migrations.Migration):
7
+
8
+    dependencies = [
9
+        ('recycle_core', '0006_alter_materialcategory_name'),
10
+    ]
11
+
12
+    operations = [
13
+        migrations.AlterField(
14
+            model_name='material',
15
+            name='category',
16
+            field=models.CharField(choices=[('Plastics', 'Plastics'), ('Metals', 'Metals'), ('Paper', 'Paper'), ('Glass', 'Glass'), ('Electronics', 'Electronics'), ('Wood', 'Wood'), ('Rubber', 'Rubber'), ('Textiles', 'Textiles'), ('Organic', 'Organic'), ('Mixed', 'Mixed')], max_length=64),
17
+        ),
18
+    ]

+ 29 - 0
recycle_core/migrations/0008_materialimage.py

@@ -0,0 +1,29 @@
1
+# Generated by Django 4.2.24 on 2025-09-22 09:28
2
+
3
+from django.db import migrations, models
4
+import django.db.models.deletion
5
+
6
+
7
+class Migration(migrations.Migration):
8
+
9
+    dependencies = [
10
+        ('recycle_core', '0007_alter_material_category'),
11
+    ]
12
+
13
+    operations = [
14
+        migrations.CreateModel(
15
+            name='MaterialImage',
16
+            fields=[
17
+                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18
+                ('created_at', models.DateTimeField(auto_now_add=True)),
19
+                ('updated_at', models.DateTimeField(auto_now=True)),
20
+                ('image', models.ImageField(upload_to='materials/%Y/%m/')),
21
+                ('caption', models.CharField(blank=True, max_length=255)),
22
+                ('display_order', models.PositiveIntegerField(default=0)),
23
+                ('material', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='recycle_core.material')),
24
+            ],
25
+            options={
26
+                'ordering': ['display_order', 'id'],
27
+            },
28
+        ),
29
+    ]

+ 30 - 2
recycle_core/models.py

@@ -27,7 +27,20 @@ class TimestampedModel(models.Model):
27 27
 
28 28
 class MaterialCategory(TimestampedModel):
29 29
     organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="material_categories")
30
-    name = models.CharField(max_length=255)
30
+    # Limit to a curated, preset set of category names
31
+    CATEGORY_CHOICES = (
32
+        ("Plastics", "Plastics"),
33
+        ("Metals", "Metals"),
34
+        ("Paper", "Paper"),
35
+        ("Glass", "Glass"),
36
+        ("Electronics", "Electronics"),
37
+        ("Wood", "Wood"),
38
+        ("Rubber", "Rubber"),
39
+        ("Textiles", "Textiles"),
40
+        ("Organic", "Organic"),
41
+        ("Mixed", "Mixed"),
42
+    )
43
+    name = models.CharField(max_length=255, choices=CATEGORY_CHOICES)
31 44
 
32 45
     class Meta:
33 46
         unique_together = ("organization", "name")
@@ -81,7 +94,9 @@ class ProvidedService(TimestampedModel):
81 94
 
82 95
 class Material(TimestampedModel):
83 96
     organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="materials")
84
-    category = models.ForeignKey(MaterialCategory, on_delete=models.PROTECT, related_name="materials")
97
+    # Preset category choices (no FK)
98
+    CATEGORY_CHOICES = MaterialCategory.CATEGORY_CHOICES
99
+    category = models.CharField(max_length=64, choices=CATEGORY_CHOICES)
85 100
     name = models.CharField(max_length=255)
86 101
     code = models.CharField(max_length=64, blank=True)
87 102
     # unit choices keep MVP simple; conversions out of scope for now
@@ -102,6 +117,19 @@ class Material(TimestampedModel):
102 117
         return self.name
103 118
 
104 119
 
120
+class MaterialImage(TimestampedModel):
121
+    material = models.ForeignKey(Material, on_delete=models.CASCADE, related_name="images")
122
+    image = models.ImageField(upload_to="materials/%Y/%m/")
123
+    caption = models.CharField(max_length=255, blank=True)
124
+    display_order = models.PositiveIntegerField(default=0)
125
+
126
+    class Meta:
127
+        ordering = ["display_order", "id"]
128
+
129
+    def __str__(self) -> str:
130
+        return self.caption or f"MaterialImage #{self.id}"
131
+
132
+
105 133
 class PriceList(TimestampedModel):
106 134
     organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="price_lists")
107 135
     name = models.CharField(max_length=255)

+ 22 - 1
recycle_core/templates/recycle_core/material_form.html

@@ -5,7 +5,28 @@
5 5
 {% render_breadcrumbs breadcrumbs %}
6 6
 <div class="bg-white rounded shadow p-4">
7 7
   <h1 class="text-xl font-semibold mb-4">Edit Material</h1>
8
-  <form method="post">
8
+
9
+  {% if item %}
10
+  {% with imgs=item.images.all %}
11
+  {% if imgs %}
12
+  <div class="mb-4">
13
+    <h2 class="text-lg font-medium mb-2">Existing Images</h2>
14
+    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
15
+      {% for im in imgs %}
16
+        <div class="border rounded p-2 bg-white flex flex-col items-center gap-2">
17
+          <img src="{{ im.image.url }}" alt="{{ im.caption|default:'Material image' }}" class="w-28 h-28 object-cover rounded" />
18
+          {% if im.caption %}
19
+            <div class="text-xs text-gray-600 text-center">{{ im.caption }}</div>
20
+          {% endif %}
21
+        </div>
22
+      {% endfor %}
23
+    </div>
24
+  </div>
25
+  {% endif %}
26
+  {% endwith %}
27
+  {% endif %}
28
+
29
+  <form method="post" enctype="multipart/form-data">
9 30
     {% csrf_token %}
10 31
     {{ form|crispy }}
11 32
     <div class="mt-3 flex gap-2">

+ 1 - 1
recycle_core/templates/recycle_core/materials_list.html

@@ -54,7 +54,7 @@
54 54
         {% for m in materials %}
55 55
           <tr>
56 56
             <td class="px-4 py-2">{{ m.organization.name }}</td>
57
-            <td class="px-4 py-2">{{ m.category.name }}</td>
57
+            <td class="px-4 py-2">{{ m.get_category_display }}</td>
58 58
             <td class="px-4 py-2">{{ m.name }}</td>
59 59
             <td class="px-4 py-2">{{ m.code }}</td>
60 60
             <td class="px-4 py-2">{{ m.get_default_unit_display }}</td>

+ 64 - 1
recycle_core/tests.py

@@ -1,3 +1,66 @@
1 1
 from django.test import TestCase
2
+from django.core.files.uploadedfile import SimpleUploadedFile
2 3
 
3
-# Create your tests here.
4
+from orgs.models import Organization
5
+from public_frontend.models import Lead
6
+from .models import Document
7
+from .controllers.pickup_request import PickupRequestController, PickupRequestData
8
+
9
+
10
+class PickupRequestControllerTests(TestCase):
11
+    def setUp(self) -> None:
12
+        self.org = Organization.objects.create(name="Test Org", code="TEST")
13
+        self.ctrl = PickupRequestController()
14
+
15
+    def test_submit_without_files_creates_lead_only(self):
16
+        data = PickupRequestData(
17
+            organization=self.org,
18
+            name="Alice",
19
+            email="alice@example.com",
20
+            phone="+1 555 0000",
21
+            address="123 Road",
22
+            materials="PET bottles",
23
+            preferred_at=None,
24
+            files=[],
25
+        )
26
+
27
+        result = self.ctrl.submit(data)
28
+        self.assertTrue(result.ok)
29
+        self.assertIsNotNone(result.lead_id)
30
+        self.assertEqual(result.document_ids, [])
31
+
32
+        lead = Lead.objects.get(pk=result.lead_id)
33
+        self.assertEqual(lead.organization, self.org)
34
+        self.assertEqual(lead.name, "Alice")
35
+        self.assertEqual(lead.subject, "Pickup Request")
36
+        self.assertEqual(lead.source, "pickup_request")
37
+
38
+        self.assertEqual(Document.objects.filter(object_id=lead.id).count(), 0)
39
+
40
+    def test_submit_with_files_creates_documents(self):
41
+        file1 = SimpleUploadedFile("photo1.jpg", b"fakejpegdata1", content_type="image/jpeg")
42
+        file2 = SimpleUploadedFile("photo2.jpg", b"fakejpegdata2", content_type="image/jpeg")
43
+
44
+        data = PickupRequestData(
45
+            organization=self.org,
46
+            name="Bob",
47
+            email="bob@example.com",
48
+            phone="+1 555 1111",
49
+            address="456 Avenue",
50
+            materials="Aluminum cans",
51
+            preferred_at=None,
52
+            files=[file1, file2],
53
+        )
54
+
55
+        result = self.ctrl.submit(data)
56
+        self.assertTrue(result.ok)
57
+        self.assertIsNotNone(result.lead_id)
58
+        self.assertEqual(len(result.document_ids), 2)
59
+
60
+        lead = Lead.objects.get(pk=result.lead_id)
61
+        docs = Document.objects.filter(object_id=lead.id).order_by("id")
62
+        self.assertEqual(docs.count(), 2)
63
+        for d in docs:
64
+            self.assertEqual(d.organization, self.org)
65
+            self.assertEqual(d.kind, "pickup_request")
66
+            self.assertEqual(d.content_object, lead)

+ 9 - 4
recycle_core/views.py

@@ -72,7 +72,7 @@ def owner_required(view_func):
72 72
 @breadcrumbs(label="Materials", name="re_materials")
73 73
 def materials_list(request):
74 74
     # Create forms
75
-    mat_form = MaterialForm(request.POST or None)
75
+    mat_form = MaterialForm(request.POST or None, request.FILES or None)
76 76
     cat_form = MaterialCategoryForm(request.POST or None)
77 77
 
78 78
     # Restrict organization choices in forms to current org
@@ -91,6 +91,11 @@ def materials_list(request):
91 91
                 if getattr(request, "org", None) is not None:
92 92
                     obj.organization = request.org
93 93
                 obj.save()
94
+                # Save any uploaded images deferred by the form
95
+                try:
96
+                    mat_form.save_images(instance=obj)
97
+                except Exception:
98
+                    pass
94 99
                 messages.success(request, "Material created.")
95 100
                 return redirect("recycle_core:materials_list")
96 101
             else:
@@ -109,14 +114,14 @@ def materials_list(request):
109 114
     # Filters via django-filter to match list pattern
110 115
     class MaterialFilter(filters.FilterSet):
111 116
         organization = filters.ModelChoiceFilter(queryset=Organization.objects.all())
112
-        category = filters.ModelChoiceFilter(queryset=MaterialCategory.objects.all())
117
+        category = filters.ChoiceFilter(choices=Material.CATEGORY_CHOICES)
113 118
         name = filters.CharFilter(field_name="name", lookup_expr="icontains")
114 119
 
115 120
         class Meta:
116 121
             model = Material
117 122
             fields = ["organization", "category", "name"]
118 123
 
119
-    base_mats = Material.objects.select_related("organization", "category").order_by("organization_id", "name")
124
+    base_mats = Material.objects.select_related("organization").order_by("organization_id", "name")
120 125
     mat_filter = MaterialFilter(request.GET, queryset=base_mats)
121 126
     mats = mat_filter.qs
122 127
     # Scope to current organization if present
@@ -248,7 +253,7 @@ def org_user_delete(request, pk: int):
248 253
 def material_edit(request, pk: int):
249 254
     item = get_object_or_404(Material, pk=pk)
250 255
     if request.method == "POST":
251
-        form = MaterialForm(request.POST, instance=item)
256
+        form = MaterialForm(request.POST, request.FILES, instance=item)
252 257
         if form.is_valid():
253 258
             form.save()
254 259
             messages.success(request, "Material updated.")

+ 4 - 0
requirements.txt

@@ -14,4 +14,8 @@ django-browser-reload
14 14
 django-allauth[socialaccount]
15 15
 django-markdownfield
16 16
 django-mptt
17
+django-extensions
18
+# Choose one of these for graph_models rendering
19
+# pygraphviz is preferred; alternatively install pydotplus and graphviz
20
+pygraphviz
17 21
 django-npm

BIN
seq.png


+ 59 - 0
seq.txt

@@ -0,0 +1,59 @@
1
+@startuml
2
+title Request Pickup (Fast Path)
3
+actor "Factory Officer" as FO
4
+participant "Public Site (FE)" as Web
5
+participant "Backend (Django)" as API
6
+actor "Staff (Web Admin)" as Staff
7
+actor Driver
8
+participant "Weigh Station" as Scale
9
+participant Billing
10
+
11
+FO -> Web: Open "Sell Scrap" (Request Pickup)
12
+Web --> FO: Show form (materials, qty, photos, address, time)
13
+FO -> Web: Submit form (+photos)
14
+Web -> API: POST /pickup-request
15
+API -> API: Create Lead (org, details)
16
+API --> Staff: Notify (inbox/email)
17
+Staff -> API: Create/attach Customer + Site
18
+Staff -> API: Create PickupOrder (status=requested)
19
+Staff -> API: Schedule + Assign Driver
20
+API --> FO: Confirmation (schedule)
21
+Driver -> FO: Arrive and collect
22
+Driver -> Scale: Weigh materials
23
+Scale -> API: Record WeighTicket + lines
24
+API -> Billing: Generate Invoice or Payout
25
+Billing --> FO: Invoice/Payout issued
26
+FO -> Billing: Pay / Receive funds
27
+API -> API: Mark Pickup completed
28
+@enduml
29
+
30
+@startuml
31
+title Get Bids (Marketplace Path)
32
+actor "Factory Officer" as FO
33
+participant "Public Site (FE)" as Web
34
+participant "Backend (Django)" as API
35
+actor "Staff (Web Admin)" as Staff
36
+actor "Recycler(s)" as Rec
37
+actor Driver
38
+participant "Weigh Station" as Scale
39
+participant Billing
40
+
41
+FO -> Web: "Sell Scrap" → Get Bids
42
+Web --> FO: Listing form (title, materials, qty, photos, reserve, ends)
43
+FO -> Web: Submit request
44
+Web -> API: POST listing-request
45
+API -> API: Create Draft ScrapListing (or Lead: listing_request)
46
+Staff -> API: Review + Publish (public or invite-only)
47
+API --> Rec: Listing visible / invites sent
48
+Rec -> API: Place Bid(s)
49
+Staff -> API: Close listing at end time
50
+Staff -> API: Award winning bid
51
+API -> API: Create PickupOrder from award
52
+Driver -> FO: Collect materials
53
+Driver -> Scale: Weigh materials
54
+Scale -> API: Record WeighTicket + lines
55
+API -> Billing: Generate Invoice or Payout
56
+Billing --> FO: Invoice/Payout issued
57
+API -> API: Mark Pickup completed
58
+@enduml
59
+

BIN
seq_001.png


tum/whitesports - Gogs: Simplico Git Service

Нет описания

class-wp-plugin-install-list-table.php 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. <?php
  2. /**
  3. * List Table API: WP_Plugin_Install_List_Table class
  4. *
  5. * @package WordPress
  6. * @subpackage Administration
  7. * @since 3.1.0
  8. */
  9. /**
  10. * Core class used to implement displaying plugins to install in a list table.
  11. *
  12. * @since 3.1.0
  13. * @access private
  14. *
  15. * @see WP_List_Table
  16. */
  17. class WP_Plugin_Install_List_Table extends WP_List_Table {
  18. public $order = 'ASC';
  19. public $orderby = null;
  20. public $groups = array();
  21. private $error;
  22. /**
  23. * @return bool
  24. */
  25. public function ajax_user_can() {
  26. return current_user_can( 'install_plugins' );
  27. }
  28. /**
  29. * Return the list of known plugins.
  30. *
  31. * Uses the transient data from the updates API to determine the known
  32. * installed plugins.
  33. *
  34. * @since 4.9.0
  35. * @access protected
  36. *
  37. * @return array
  38. */
  39. protected function get_installed_plugins() {
  40. $plugins = array();
  41. $plugin_info = get_site_transient( 'update_plugins' );
  42. if ( isset( $plugin_info->no_update ) ) {
  43. foreach ( $plugin_info->no_update as $plugin ) {
  44. if ( isset( $plugin->slug ) ) {
  45. $plugin->upgrade = false;
  46. $plugins[ $plugin->slug ] = $plugin;
  47. }
  48. }
  49. }
  50. if ( isset( $plugin_info->response ) ) {
  51. foreach ( $plugin_info->response as $plugin ) {
  52. if ( isset( $plugin->slug ) ) {
  53. $plugin->upgrade = true;
  54. $plugins[ $plugin->slug ] = $plugin;
  55. }
  56. }
  57. }
  58. return $plugins;
  59. }
  60. /**
  61. * Return a list of slugs of installed plugins, if known.
  62. *
  63. * Uses the transient data from the updates API to determine the slugs of
  64. * known installed plugins. This might be better elsewhere, perhaps even
  65. * within get_plugins().
  66. *
  67. * @since 4.0.0
  68. *
  69. * @return array
  70. */
  71. protected function get_installed_plugin_slugs() {
  72. return array_keys( $this->get_installed_plugins() );
  73. }
  74. /**
  75. * @global array $tabs
  76. * @global string $tab
  77. * @global int $paged
  78. * @global string $type
  79. * @global string $term
  80. */
  81. public function prepare_items() {
  82. include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
  83. global $tabs, $tab, $paged, $type, $term;
  84. wp_reset_vars( array( 'tab' ) );
  85. $paged = $this->get_pagenum();
  86. $per_page = 36;
  87. // These are the tabs which are shown on the page.
  88. $tabs = array();
  89. if ( 'search' === $tab ) {
  90. $tabs['search'] = __( 'Search Results' );
  91. }
  92. if ( 'beta' === $tab || false !== strpos( get_bloginfo( 'version' ), '-' ) ) {
  93. $tabs['beta'] = _x( 'Beta Testing', 'Plugin Installer' );
  94. }
  95. $tabs['featured'] = _x( 'Featured', 'Plugin Installer' );
  96. $tabs['popular'] = _x( 'Popular', 'Plugin Installer' );
  97. $tabs['recommended'] = _x( 'Recommended', 'Plugin Installer' );
  98. $tabs['favorites'] = _x( 'Favorites', 'Plugin Installer' );
  99. if ( current_user_can( 'upload_plugins' ) ) {
  100. // No longer a real tab. Here for filter compatibility.
  101. // Gets skipped in get_views().
  102. $tabs['upload'] = __( 'Upload Plugin' );
  103. }
  104. $nonmenu_tabs = array( 'plugin-information' ); // Valid actions to perform which do not have a Menu item.
  105. /**
  106. * Filters the tabs shown on the Add Plugins screen.
  107. *
  108. * @since 2.7.0
  109. *
  110. * @param string[] $tabs The tabs shown on the Add Plugins screen. Defaults include
  111. * 'featured', 'popular', 'recommended', 'favorites', and 'upload'.
  112. */
  113. $tabs = apply_filters( 'install_plugins_tabs', $tabs );
  114. /**
  115. * Filters tabs not associated with a menu item on the Add Plugins screen.
  116. *
  117. * @since 2.7.0
  118. *
  119. * @param string[] $nonmenu_tabs The tabs that don't have a menu item on the Add Plugins screen.
  120. */
  121. $nonmenu_tabs = apply_filters( 'install_plugins_nonmenu_tabs', $nonmenu_tabs );
  122. // If a non-valid menu tab has been selected, And it's not a non-menu action.
  123. if ( empty( $tab ) || ( ! isset( $tabs[ $tab ] ) && ! in_array( $tab, (array) $nonmenu_tabs, true ) ) ) {
  124. $tab = key( $tabs );
  125. }
  126. $installed_plugins = $this->get_installed_plugins();
  127. $args = array(
  128. 'page' => $paged,
  129. 'per_page' => $per_page,
  130. // Send the locale to the API so it can provide context-sensitive results.
  131. 'locale' => get_user_locale(),
  132. );
  133. switch ( $tab ) {
  134. case 'search':
  135. $type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term';
  136. $term = isset( $_REQUEST['s'] ) ? wp_unslash( $_REQUEST['s'] ) : '';
  137. switch ( $type ) {
  138. case 'tag':
  139. $args['tag'] = sanitize_title_with_dashes( $term );
  140. break;
  141. case 'term':
  142. $args['search'] = $term;
  143. break;
  144. case 'author':
  145. $args['author'] = $term;
  146. break;
  147. }
  148. break;
  149. case 'featured':
  150. case 'popular':
  151. case 'new':
  152. case 'beta':
  153. $args['browse'] = $tab;
  154. break;
  155. case 'recommended':
  156. $args['browse'] = $tab;
  157. // Include the list of installed plugins so we can get relevant results.
  158. $args['installed_plugins'] = array_keys( $installed_plugins );
  159. break;
  160. case 'favorites':
  161. $action = 'save_wporg_username_' . get_current_user_id();
  162. if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), $action ) ) {
  163. $user = isset( $_GET['user'] ) ? wp_unslash( $_GET['user'] ) : get_user_option( 'wporg_favorites' );
  164. // If the save url parameter is passed with a falsey value, don't save the favorite user.
  165. if ( ! isset( $_GET['save'] ) || $_GET['save'] ) {
  166. update_user_meta( get_current_user_id(), 'wporg_favorites', $user );
  167. }
  168. } else {
  169. $user = get_user_option( 'wporg_favorites' );
  170. }
  171. if ( $user ) {
  172. $args['user'] = $user;
  173. } else {
  174. $args = false;
  175. }
  176. add_action( 'install_plugins_favorites', 'install_plugins_favorites_form', 9, 0 );
  177. break;
  178. default:
  179. $args = false;
  180. break;
  181. }
  182. /**
  183. * Filters API request arguments for each Add Plugins screen tab.
  184. *
  185. * The dynamic portion of the hook name, `$tab`, refers to the plugin install tabs.
  186. *
  187. * Possible hook names include:
  188. *
  189. * - `install_plugins_table_api_args_favorites`
  190. * - `install_plugins_table_api_args_featured`
  191. * - `install_plugins_table_api_args_popular`
  192. * - `install_plugins_table_api_args_recommended`
  193. * - `install_plugins_table_api_args_upload`
  194. *
  195. * @since 3.7.0
  196. *
  197. * @param array|false $args Plugin install API arguments.
  198. */
  199. $args = apply_filters( "install_plugins_table_api_args_{$tab}", $args );
  200. if ( ! $args ) {
  201. return;
  202. }
  203. $api = plugins_api( 'query_plugins', $args );
  204. if ( is_wp_error( $api ) ) {
  205. $this->error = $api;
  206. return;
  207. }
  208. $this->items = $api->plugins;
  209. if ( $this->orderby ) {
  210. uasort( $this->items, array( $this, 'order_callback' ) );
  211. }
  212. $this->set_pagination_args(
  213. array(
  214. 'total_items' => $api->info['results'],
  215. 'per_page' => $args['per_page'],
  216. )
  217. );
  218. if ( isset( $api->info['groups'] ) ) {
  219. $this->groups = $api->info['groups'];
  220. }
  221. if ( $installed_plugins ) {
  222. $js_plugins = array_fill_keys(
  223. array( 'all', 'search', 'active', 'inactive', 'recently_activated', 'mustuse', 'dropins' ),
  224. array()
  225. );
  226. $js_plugins['all'] = array_values( wp_list_pluck( $installed_plugins, 'plugin' ) );
  227. $upgrade_plugins = wp_filter_object_list( $installed_plugins, array( 'upgrade' => true ), 'and', 'plugin' );
  228. if ( $upgrade_plugins ) {
  229. $js_plugins['upgrade'] = array_values( $upgrade_plugins );
  230. }
  231. wp_localize_script(
  232. 'updates',
  233. '_wpUpdatesItemCounts',
  234. array(
  235. 'plugins' => $js_plugins,
  236. 'totals' => wp_get_update_data(),
  237. )
  238. );
  239. }
  240. }
  241. /**
  242. */
  243. public function no_items() {
  244. if ( isset( $this->error ) ) { ?>
  245. <div class="inline error"><p><?php echo $this->error->get_error_message(); ?></p>
  246. <p class="hide-if-no-js"><button class="button try-again"><?php _e( 'Try Again' ); ?></button></p>
  247. </div>
  248. <?php } else { ?>
  249. <div class="no-plugin-results"><?php _e( 'No plugins found. Try a different search.' ); ?></div>
  250. <?php
  251. }
  252. }
  253. /**
  254. * @global array $tabs
  255. * @global string $tab
  256. *
  257. * @return array
  258. */
  259. protected function get_views() {
  260. global $tabs, $tab;
  261. $display_tabs = array();
  262. foreach ( (array) $tabs as $action => $text ) {
  263. $current_link_attributes = ( $action === $tab ) ? ' class="current" aria-current="page"' : '';
  264. $href = self_admin_url( 'plugin-install.php?tab=' . $action );
  265. $display_tabs[ 'plugin-install-' . $action ] = "<a href='$href'$current_link_attributes>$text</a>";
  266. }
  267. // No longer a real tab.
  268. unset( $display_tabs['plugin-install-upload'] );
  269. return $display_tabs;
  270. }
  271. /**
  272. * Override parent views so we can use the filter bar display.
  273. */
  274. public function views() {
  275. $views = $this->get_views();
  276. /** This filter is documented in wp-admin/inclues/class-wp-list-table.php */
  277. $views = apply_filters( "views_{$this->screen->id}", $views );
  278. $this->screen->render_screen_reader_content( 'heading_views' );
  279. ?>
  280. <div class="wp-filter">
  281. <ul class="filter-links">
  282. <?php
  283. if ( ! empty( $views ) ) {
  284. foreach ( $views as $class => $view ) {
  285. $views[ $class ] = "\t<li class='$class'>$view";
  286. }
  287. echo implode( " </li>\n", $views ) . "</li>\n";
  288. }
  289. ?>
  290. </ul>
  291. <?php install_search_form(); ?>
  292. </div>
  293. <?php
  294. }
  295. /**
  296. * Displays the plugin install table.
  297. *
  298. * Overrides the parent display() method to provide a different container.
  299. *
  300. * @since 4.0.0
  301. */
  302. public function display() {
  303. $singular = $this->_args['singular'];
  304. $data_attr = '';
  305. if ( $singular ) {
  306. $data_attr = " data-wp-lists='list:$singular'";
  307. }
  308. $this->display_tablenav( 'top' );
  309. ?>
  310. <div class="wp-list-table <?php echo implode( ' ', $this->get_table_classes() ); ?>">
  311. <?php
  312. $this->screen->render_screen_reader_content( 'heading_list' );
  313. ?>
  314. <div id="the-list"<?php echo $data_attr; ?>>
  315. <?php $this->display_rows_or_placeholder(); ?>
  316. </div>
  317. </div>
  318. <?php
  319. $this->display_tablenav( 'bottom' );
  320. }
  321. /**
  322. * @global string $tab
  323. *
  324. * @param string $which
  325. */
  326. protected function display_tablenav( $which ) {
  327. if ( 'featured' === $GLOBALS['tab'] ) {
  328. return;
  329. }
  330. if ( 'top' === $which ) {
  331. wp_referer_field();
  332. ?>
  333. <div class="tablenav top">
  334. <div class="alignleft actions">
  335. <?php
  336. /**
  337. * Fires before the Plugin Install table header pagination is displayed.
  338. *
  339. * @since 2.7.0
  340. */
  341. do_action( 'install_plugins_table_header' );
  342. ?>
  343. </div>
  344. <?php $this->pagination( $which ); ?>
  345. <br class="clear" />
  346. </div>
  347. <?php } else { ?>
  348. <div class="tablenav bottom">
  349. <?php $this->pagination( $which ); ?>
  350. <br class="clear" />
  351. </div>
  352. <?php
  353. }
  354. }
  355. /**
  356. * @return array
  357. */
  358. protected function get_table_classes() {
  359. return array( 'widefat', $this->_args['plural'] );
  360. }
  361. /**
  362. * @return array
  363. */
  364. public function get_columns() {
  365. return array();
  366. }
  367. /**
  368. * @param object $plugin_a
  369. * @param object $plugin_b
  370. * @return int
  371. */
  372. private function order_callback( $plugin_a, $plugin_b ) {
  373. $orderby = $this->orderby;
  374. if ( ! isset( $plugin_a->$orderby, $plugin_b->$orderby ) ) {
  375. return 0;
  376. }
  377. $a = $plugin_a->$orderby;
  378. $b = $plugin_b->$orderby;
  379. if ( $a === $b ) {
  380. return 0;
  381. }
  382. if ( 'DESC' === $this->order ) {
  383. return ( $a < $b ) ? 1 : -1;
  384. } else {
  385. return ( $a < $b ) ? -1 : 1;
  386. }
  387. }
  388. public function display_rows() {
  389. $plugins_allowedtags = array(
  390. 'a' => array(
  391. 'href' => array(),
  392. 'title' => array(),
  393. 'target' => array(),
  394. ),
  395. 'abbr' => array( 'title' => array() ),
  396. 'acronym' => array( 'title' => array() ),
  397. 'code' => array(),
  398. 'pre' => array(),
  399. 'em' => array(),
  400. 'strong' => array(),
  401. 'ul' => array(),
  402. 'ol' => array(),
  403. 'li' => array(),
  404. 'p' => array(),
  405. 'br' => array(),
  406. );
  407. $plugins_group_titles = array(
  408. 'Performance' => _x( 'Performance', 'Plugin installer group title' ),
  409. 'Social' => _x( 'Social', 'Plugin installer group title' ),
  410. 'Tools' => _x( 'Tools', 'Plugin installer group title' ),
  411. );
  412. $group = null;
  413. foreach ( (array) $this->items as $plugin ) {
  414. if ( is_object( $plugin ) ) {
  415. $plugin = (array) $plugin;
  416. }
  417. // Display the group heading if there is one.
  418. if ( isset( $plugin['group'] ) && $plugin['group'] !== $group ) {
  419. if ( isset( $this->groups[ $plugin['group'] ] ) ) {
  420. $group_name = $this->groups[ $plugin['group'] ];
  421. if ( isset( $plugins_group_titles[ $group_name ] ) ) {
  422. $group_name = $plugins_group_titles[ $group_name ];
  423. }
  424. } else {
  425. $group_name = $plugin['group'];
  426. }
  427. // Starting a new group, close off the divs of the last one.
  428. if ( ! empty( $group ) ) {
  429. echo '</div></div>';
  430. }
  431. echo '<div class="plugin-group"><h3>' . esc_html( $group_name ) . '</h3>';
  432. // Needs an extra wrapping div for nth-child selectors to work.
  433. echo '<div class="plugin-items">';
  434. $group = $plugin['group'];
  435. }
  436. $title = wp_kses( $plugin['name'], $plugins_allowedtags );
  437. // Remove any HTML from the description.
  438. $description = strip_tags( $plugin['short_description'] );
  439. $version = wp_kses( $plugin['version'], $plugins_allowedtags );
  440. $name = strip_tags( $title . ' ' . $version );
  441. $author = wp_kses( $plugin['author'], $plugins_allowedtags );
  442. if ( ! empty( $author ) ) {
  443. /* translators: %s: Plugin author. */
  444. $author = ' <cite>' . sprintf( __( 'By %s' ), $author ) . '</cite>';
  445. }
  446. $requires_php = isset( $plugin['requires_php'] ) ? $plugin['requires_php'] : null;
  447. $requires_wp = isset( $plugin['requires'] ) ? $plugin['requires'] : null;
  448. $compatible_php = is_php_version_compatible( $requires_php );
  449. $compatible_wp = is_wp_version_compatible( $requires_wp );
  450. $tested_wp = ( empty( $plugin['tested'] ) || version_compare( get_bloginfo( 'version' ), $plugin['tested'], '<=' ) );
  451. $action_links = array();
  452. if ( current_user_can( 'install_plugins' ) || current_user_can( 'update_plugins' ) ) {
  453. $status = install_plugin_install_status( $plugin );
  454. switch ( $status['status'] ) {
  455. case 'install':
  456. if ( $status['url'] ) {
  457. if ( $compatible_php && $compatible_wp ) {
  458. $action_links[] = sprintf(
  459. '<a class="install-now button" data-slug="%s" href="%s" aria-label="%s" data-name="%s">%s</a>',
  460. esc_attr( $plugin['slug'] ),
  461. esc_url( $status['url'] ),
  462. /* translators: %s: Plugin name and version. */
  463. esc_attr( sprintf( _x( 'Install %s now', 'plugin' ), $name ) ),
  464. esc_attr( $name ),
  465. __( 'Install Now' )
  466. );
  467. } else {
  468. $action_links[] = sprintf(
  469. '<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
  470. _x( 'Cannot Install', 'plugin' )
  471. );
  472. }
  473. }
  474. break;
  475. case 'update_available':
  476. if ( $status['url'] ) {
  477. if ( $compatible_php && $compatible_wp ) {
  478. $action_links[] = sprintf(
  479. '<a class="update-now button aria-button-if-js" data-plugin="%s" data-slug="%s" href="%s" aria-label="%s" data-name="%s">%s</a>',
  480. esc_attr( $status['file'] ),
  481. esc_attr( $plugin['slug'] ),
  482. esc_url( $status['url'] ),
  483. /* translators: %s: Plugin name and version. */
  484. esc_attr( sprintf( _x( 'Update %s now', 'plugin' ), $name ) ),
  485. esc_attr( $name ),
  486. __( 'Update Now' )
  487. );
  488. } else {
  489. $action_links[] = sprintf(
  490. '<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
  491. _x( 'Cannot Update', 'plugin' )
  492. );
  493. }
  494. }
  495. break;
  496. case 'latest_installed':
  497. case 'newer_installed':
  498. if ( is_plugin_active( $status['file'] ) ) {
  499. $action_links[] = sprintf(
  500. '<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
  501. _x( 'Active', 'plugin' )
  502. );
  503. } elseif ( current_user_can( 'activate_plugin', $status['file'] ) ) {
  504. $button_text = __( 'Activate' );
  505. /* translators: %s: Plugin name. */
  506. $button_label = _x( 'Activate %s', 'plugin' );
  507. $activate_url = add_query_arg(
  508. array(
  509. '_wpnonce' => wp_create_nonce( 'activate-plugin_' . $status['file'] ),
  510. 'action' => 'activate',
  511. 'plugin' => $status['file'],
  512. ),
  513. network_admin_url( 'plugins.php' )
  514. );
  515. if ( is_network_admin() ) {
  516. $button_text = __( 'Network Activate' );
  517. /* translators: %s: Plugin name. */
  518. $button_label = _x( 'Network Activate %s', 'plugin' );
  519. $activate_url = add_query_arg( array( 'networkwide' => 1 ), $activate_url );
  520. }
  521. $action_links[] = sprintf(
  522. '<a href="%1$s" class="button activate-now" aria-label="%2$s">%3$s</a>',
  523. esc_url( $activate_url ),
  524. esc_attr( sprintf( $button_label, $plugin['name'] ) ),
  525. $button_text
  526. );
  527. } else {
  528. $action_links[] = sprintf(
  529. '<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
  530. _x( 'Installed', 'plugin' )
  531. );
  532. }
  533. break;
  534. }
  535. }
  536. $details_link = self_admin_url(
  537. 'plugin-install.php?tab=plugin-information&amp;plugin=' . $plugin['slug'] .
  538. '&amp;TB_iframe=true&amp;width=600&amp;height=550'
  539. );
  540. $action_links[] = sprintf(
  541. '<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>',
  542. esc_url( $details_link ),
  543. /* translators: %s: Plugin name and version. */
  544. esc_attr( sprintf( __( 'More information about %s' ), $name ) ),
  545. esc_attr( $name ),
  546. __( 'More Details' )
  547. );
  548. if ( ! empty( $plugin['icons']['svg'] ) ) {
  549. $plugin_icon_url = $plugin['icons']['svg'];
  550. } elseif ( ! empty( $plugin['icons']['2x'] ) ) {
  551. $plugin_icon_url = $plugin['icons']['2x'];
  552. } elseif ( ! empty( $plugin['icons']['1x'] ) ) {
  553. $plugin_icon_url = $plugin['icons']['1x'];
  554. } else {
  555. $plugin_icon_url = $plugin['icons']['default'];
  556. }
  557. /**
  558. * Filters the install action links for a plugin.
  559. *
  560. * @since 2.7.0
  561. *
  562. * @param string[] $action_links An array of plugin action links. Defaults are links to Details and Install Now.
  563. * @param array $plugin The plugin currently being listed.
  564. */
  565. $action_links = apply_filters( 'plugin_install_action_links', $action_links, $plugin );
  566. $last_updated_timestamp = strtotime( $plugin['last_updated'] );
  567. ?>
  568. <div class="plugin-card plugin-card-<?php echo sanitize_html_class( $plugin['slug'] ); ?>">
  569. <?php
  570. if ( ! $compatible_php || ! $compatible_wp ) {
  571. echo '<div class="notice inline notice-error notice-alt"><p>';
  572. if ( ! $compatible_php && ! $compatible_wp ) {
  573. _e( 'This plugin doesn&#8217;t work with your versions of WordPress and PHP.' );
  574. if ( current_user_can( 'update_core' ) && current_user_can( 'update_php' ) ) {
  575. printf(
  576. /* translators: 1: URL to WordPress Updates screen, 2: URL to Update PHP page. */
  577. ' ' . __( '<a href="%1$s">Please update WordPress</a>, and then <a href="%2$s">learn more about updating PHP</a>.' ),
  578. self_admin_url( 'update-core.php' ),
  579. esc_url( wp_get_update_php_url() )
  580. );
  581. wp_update_php_annotation( '</p><p><em>', '</em>' );
  582. } elseif ( current_user_can( 'update_core' ) ) {
  583. printf(
  584. /* translators: %s: URL to WordPress Updates screen. */
  585. ' ' . __( '<a href="%s">Please update WordPress</a>.' ),
  586. self_admin_url( 'update-core.php' )
  587. );
  588. } elseif ( current_user_can( 'update_php' ) ) {
  589. printf(
  590. /* translators: %s: URL to Update PHP page. */
  591. ' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ),
  592. esc_url( wp_get_update_php_url() )
  593. );
  594. wp_update_php_annotation( '</p><p><em>', '</em>' );
  595. }
  596. } elseif ( ! $compatible_wp ) {
  597. _e( 'This plugin doesn&#8217;t work with your version of WordPress.' );
  598. if ( current_user_can( 'update_core' ) ) {
  599. printf(
  600. /* translators: %s: URL to WordPress Updates screen. */
  601. ' ' . __( '<a href="%s">Please update WordPress</a>.' ),
  602. self_admin_url( 'update-core.php' )
  603. );
  604. }
  605. } elseif ( ! $compatible_php ) {
  606. _e( 'This plugin doesn&#8217;t work with your version of PHP.' );
  607. if ( current_user_can( 'update_php' ) ) {
  608. printf(
  609. /* translators: %s: URL to Update PHP page. */
  610. ' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ),
  611. esc_url( wp_get_update_php_url() )
  612. );
  613. wp_update_php_annotation( '</p><p><em>', '</em>' );
  614. }
  615. }
  616. echo '</p></div>';
  617. }
  618. ?>
  619. <div class="plugin-card-top">
  620. <div class="name column-name">
  621. <h3>
  622. <a href="<?php echo esc_url( $details_link ); ?>" class="thickbox open-plugin-details-modal">
  623. <?php echo $title; ?>
  624. <img src="<?php echo esc_url( $plugin_icon_url ); ?>" class="plugin-icon" alt="" />
  625. </a>
  626. </h3>
  627. </div>
  628. <div class="action-links">
  629. <?php
  630. if ( $action_links ) {
  631. echo '<ul class="plugin-action-buttons"><li>' . implode( '</li><li>', $action_links ) . '</li></ul>';
  632. }
  633. ?>
  634. </div>
  635. <div class="desc column-description">
  636. <p><?php echo $description; ?></p>
  637. <p class="authors"><?php echo $author; ?></p>
  638. </div>
  639. </div>
  640. <div class="plugin-card-bottom">
  641. <div class="vers column-rating">
  642. <?php
  643. wp_star_rating(
  644. array(
  645. 'rating' => $plugin['rating'],
  646. 'type' => 'percent',
  647. 'number' => $plugin['num_ratings'],
  648. )
  649. );
  650. ?>
  651. <span class="num-ratings" aria-hidden="true">(<?php echo number_format_i18n( $plugin['num_ratings'] ); ?>)</span>
  652. </div>
  653. <div class="column-updated">
  654. <strong><?php _e( 'Last Updated:' ); ?></strong>
  655. <?php
  656. /* translators: %s: Human-readable time difference. */
  657. printf( __( '%s ago' ), human_time_diff( $last_updated_timestamp ) );
  658. ?>
  659. </div>
  660. <div class="column-downloaded">
  661. <?php
  662. if ( $plugin['active_installs'] >= 1000000 ) {
  663. $active_installs_millions = floor( $plugin['active_installs'] / 1000000 );
  664. $active_installs_text = sprintf(
  665. /* translators: %s: Number of millions. */
  666. _nx( '%s+ Million', '%s+ Million', $active_installs_millions, 'Active plugin installations' ),
  667. number_format_i18n( $active_installs_millions )
  668. );
  669. } elseif ( 0 === $plugin['active_installs'] ) {
  670. $active_installs_text = _x( 'Less Than 10', 'Active plugin installations' );
  671. } else {
  672. $active_installs_text = number_format_i18n( $plugin['active_installs'] ) . '+';
  673. }
  674. /* translators: %s: Number of installations. */
  675. printf( __( '%s Active Installations' ), $active_installs_text );
  676. ?>
  677. </div>
  678. <div class="column-compatibility">
  679. <?php
  680. if ( ! $tested_wp ) {
  681. echo '<span class="compatibility-untested">' . __( 'Untested with your version of WordPress' ) . '</span>';
  682. } elseif ( ! $compatible_wp ) {
  683. echo '<span class="compatibility-incompatible">' . __( '<strong>Incompatible</strong> with your version of WordPress' ) . '</span>';
  684. } else {
  685. echo '<span class="compatibility-compatible">' . __( '<strong>Compatible</strong> with your version of WordPress' ) . '</span>';
  686. }
  687. ?>
  688. </div>
  689. </div>
  690. </div>
  691. <?php
  692. }
  693. // Close off the group divs of the last one.
  694. if ( ! empty( $group ) ) {
  695. echo '</div></div>';
  696. }
  697. }
  698. }