Jake Vanderwerf
2026-08-27 d7c8752b4d8f688a13645130d4c3237efd5ad1bf
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
<?php
 
namespace JVBase\rest\routes;
 
use JVBase\Instance;
use JVBase\managers\Approvals;
use JVBase\managers\Cache;
 
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;
 
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
 
class ApprovalRoutes extends Rest
{
    use Instance;
    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->cache = Cache::for('approvals', 'custom', $this->cacheTtl);
 
        $this->initTypes();
    }
 
    protected function initTypes():void
    {
        $this->userTypes = [];
        $this->termTypes = [];
        $this->allTypes = [];
        if ($this->hasMemberApproval) {
            $this->userTypes = Registrar::withFeature('approve_new', 'user');
            $this->allTypes = $this->userTypes;
        }
        if (Site::has('term_approval')) {
            $this->termTypes = Registrar::withFeature('approve_new', 'term');
            $this->allTypes[] = 'term';
        }
    }
 
    public function registerRoutes():void
    {
        Route::for('approvals')
            ->get([$this, 'getApprovals'])
            ->args([
                'type' => 'string',
                'status' => 'string|enum:pending,approved,rejected,expired',
            ])
            ->auth(PermissionHandler::combine(['user', 'verified']))
            ->rateLimit(30)
            ->post([$this, 'handleAction'])
            ->args([
                '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 = get_current_user_id();
        $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 = Approvals::getInstance()->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 = Approvals::getInstance()->getRequest($requestID, $type);
        if (!$request) {
            return false;
        }
        $votes = Approvals::getInstance()->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 = Approvals::getInstance()->createApproval(
            $user_id,
            $taxonomy,
            $name,
            $parent
        );
        return $result['success'];
    }
 
    public function getApprovals(WP_REST_Request $request): WP_REST_Response
    {
        $user_id = get_current_user_id();
        $type = sanitize_text_field($request->get_param('type') ?? 'all');
        $status = sanitize_text_field($request->get_param('status') ?? 'pending');
 
        $result = Approvals::getInstance()->getApprovalRequests($user_id, $type === 'all' ? null : $type);
 
        return $this->success($result);
    }
 
 
}