Jake Vanderwerf
2026-05-01 48721c85ebcfa973ee81719d2467ca80e4253dc9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<?php
 
namespace JVBase\rest\routes;
 
use JVBase\managers\CustomTable;
use JVBase\registrar\Registrar;
use JVBase\rest\PermissionHandler;
use JVBase\rest\Rest;
use JVBase\rest\Route;
use JVBase\rest\Response;
use JVBase\base\Site;
use WP_REST_Request;
use WP_REST_Response;
use Exception;
 
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
 
class ApprovalRoutes extends Rest
{
    protected array $userTypes;
    protected array $termTypes;
    protected array $allTypes;
 
    protected int $expiryDays = 7;
    protected bool $hasMemberApproval = false;
 
    public function __construct()
    {
        $this->cacheName = 'approvals';
        $this->hasMemberApproval = Site::membership() && Site::membership()->has('member_verified');
        parent::__construct();
 
        $this->initTypes();
    }
 
    protected function initTypes():void
    {
        $this->userTypes = [];
        $this->termTypes = [];
        $this->allTypes = [];
        if ($this->hasMemberApproval) {
            $this->userTypes = Registrar::getFeatured('approve_new', 'user');
            $this->allTypes = $this->userTypes;
        }
        if (Site::has('term_approval')) {
            $this->termTypes = Registrar::getFeatured('approve_new', 'term');
            $this->allTypes[] = 'term';
        }
    }
 
    public function registerRoutes():void
    {
        Route::for('approvals')
            ->get([$this, 'getApprovals'])
            ->args([
                'user' => 'integer|required',
                'type' => 'string',
                'status' => 'string|enum:pending,approved,rejected,expired',
            ])
            ->auth(PermissionHandler::combine(['user', 'verified']))
            ->rateLimit(30)
            ->post([$this, 'handleAction'])
            ->args([
                'user' => 'integer|required',
                'request_id' => 'integer|required',
                'action' => 'string|required|enum:approve,reject',
                'type' => 'string|required',
                'notes' => 'string',
            ])
            ->auth(PermissionHandler::combine(['user', 'verified']))
            ->rateLimit(3)
            ->register();
    }
 
 
    /**
     * @param WP_REST_Request $request
     *
     * @return WP_REST_Response
     */
    public function handleAction(WP_REST_Request $request):WP_REST_Response
    {
        $data = $request->get_params();
        $request_id = absint($data['request_id']);
        $user_id = absint($data['user']);
        $action = sanitize_text_field($data['action']);
        $type = sanitize_text_field($data['type']);
        $notes = sanitize_text_field($data['notes'] ?? '');
 
        if (!in_array($type, $this->allTypes)) {
            return Response::validationError(['message' => 'Invalid type']);
        }
 
        $result = $this->handleVote($type, $action, $request_id, $user_id, $notes);
 
        return $result
            ? Response::success(['message' => 'Vote recorded successfully'])
            : Response::error('Failed to record vote');
    }
 
    /**
     * Artist and Term Approvals
     */
    protected function handleVote(string $type, string $vote, int $request_id, int $user_id, string $notes = ''): bool
    {
        if (!in_array($vote, ['approve', 'reject', 'dismiss'])) {
            return false;
        }
        $result = JVB()->approvals()->markApproval($request_id, $user_id, $type, $vote, $notes);
        return $result['success'];
    }
 
 
    protected function rebuildExpiryDate()
    {
        return date('Y-m-d H:i:s', strtotime("+{$this->expiryDays} days", time()));
    }
 
 
 
    /*************
     * Artist Approvals
     ************/
    /**
     * Record an approval vote for an artist
     *
     * @param int $user_id User casting the approval vote
     * @param int $request_id The approval request ID
     * @param string $vote 'approve' or 'reject'
     * @param string $notes Optional notes for the vote
     *
     * @return bool Success status
     */
    public function voteForArtist(int $user_id, int $request_id, string $vote, string $notes = ''):bool
    {
        return $this->handleVote(jvbUserRole($user_id), $vote, $request_id, $user_id, $notes);
    }
 
 
    /**
     * Get verification details for a request
     *
     * @param int $requestID the request ID
     * @param string $type Type
     *
     * @return array|false Verification details or false if not verified
     */
    public function getVerificationDetails(int $requestID, string $type): array|false
    {
        $request = JVB()->approvals()->getRequest($requestID, $type);
        if (!$request) {
            return false;
        }
        $votes = JVB()->approvals()->getVotes($requestID, $type);
 
        // Join with user data for display names
        foreach ($votes as &$vote) {
            $user = get_userdata($vote['user_id']);
            $vote['approver_name'] = $user ? jvbGetUsername($vote['user_id']) : 'Someone';
        }
 
        return [
            'request' => $request,
            'votes' => $votes,
            'verification_date' => $request['updated_at'],
        ];
    }
 
 
 
    /**
     * Create a new term approval request
     *
     * @param int $user_id User requesting approval
     * @param string $taxonomy Taxonomy
     * @param string $name New Term Name
     * @param int $parent Parent Term ID
     * @param int $required_approvals Number of approvals required
     *
     * @return int|false Request ID or false on failure
     */
    public function createTermApprovalRequest(
        int $user_id,
        string $taxonomy,
        string $name,
        int $parent = 0,
        int $required_approvals = 3
    ): int|false {
 
        $result = JVB()->approvals()->createApproval(
            $user_id,
            $taxonomy,
            $name,
            $parent
        );
        return $result['success'];
    }
 
    protected function getTableName(string $type, string $suffix): string
    {
        return match ($type) {
            'term' => "approval_term_{$suffix}",
            default => "approval_{$type}_{$suffix}",
        };
    }
 
    public function getApprovals(WP_REST_Request $request): WP_REST_Response
    {
        $user_id = absint($request->get_param('user'));
        $type = sanitize_text_field($request->get_param('type') ?? 'all');
        $status = sanitize_text_field($request->get_param('status') ?? 'pending');
 
        if (!$this->checkUser($user_id)) {
            return $this->unauthorized();
        }
 
        $cacheKey = compact('user_id', 'type', 'status');
 
        $result = $this->cache->remember($cacheKey, function() use ($type, $status) {
            $data = [];
 
            if ($type === 'user' || $type === 'all') {
                $data['user_approvals'] = $this->getUserApprovals($status);
            }
 
            if ($type === 'term' || $type === 'all') {
                $data['term_approvals'] = $this->getTermApprovals($status);
            }
 
            return $data;
        });
 
        return $this->success($result);
    }
 
    private function getUserApprovals(string $status = 'pending'): array
    {
 
        $table = CustomTable::for($this->getTableName('artist', 'requests'));
 
        $query = $table;
 
        if ($status !== 'all') {
            $query = $query->where(['status' => $status]);
        }
 
        return $query->orderBy('created_at', 'DESC')->getResults(ARRAY_A);
    }
 
    private function getTermApprovals(string $status = 'pending'): array
    {
        $table = CustomTable::for($this->getTableName('term', 'requests'));
 
        if ($status === 'all') {
            return $table->orderBy('created_at', 'DESC')->getResults(ARRAY_A);
        }
 
        return $table
            ->where(['status' => $status])
            ->orderBy('created_at', 'DESC')
            ->getResults(ARRAY_A);
    }
}