Jake Vanderwerf
4 days ago 747d741293e064a979d7bf6c143ef969ea6d7629
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
<?php
namespace JVBase\rest\routes;
 
use JVBase\base\Site;
use JVBase\importers\JaneAppClientImporter;
use JVBase\importers\JaneAppSalesImporter;
use JVBase\managers\CustomTable;
use JVBase\rest\Rest;
use JVBase\rest\Route;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
 
if (!defined('ABSPATH')) {
    exit;
}
 
/**
 * REST API routes for referral system
 */
class ReferralRoutes extends Rest
{
    public function __construct()
    {
        $this->cacheName = 'referrals';
        $this->cacheTtl = (int)HOUR_IN_SECONDS;
        parent::__construct();
 
        add_filter(BASE.'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
    }
 
    public function registerRoutes(): void
    {
        // Main referrals endpoint - list and manage referrals
        Route::for('referrals')
            ->get([$this, 'getReferrals'])
            ->args([
                'user' => 'integer',
                'status' => 'string|enum:all,pending,consulted,treated,unused,registered,completed|default:all',
                'date_start' => 'string',
                'date_end' => 'string',
                'limit' => 'integer|default:50',
                'offset' => 'integer|default:0',
                'search' => 'string'
            ])
            ->rateLimit()
            ->post([$this, 'handleAction'])
            ->args([
                'action' => 'string|required|enum:invite,consulted,treated,remove,resend'
            ])
            ->auth('user')
            ->rateLimit(10)
            ->register();
 
        // Referral code endpoint
        Route::for('referrals/code')
            ->get([$this, 'getCode'])
            ->args(['user' => 'integer'])
            ->auth('user')
            ->rateLimit(30)
            ->post([$this, 'validateCode'])
            ->args(['code' => 'string|required'])
            ->auth('public')
            ->rateLimit(10)
            ->register();
 
        // Stats endpoint
        Route::for('referrals/stats')
            ->get([$this, 'getStats'])
            ->args(['user' => 'integer'])
            ->auth('user')
            ->rateLimit(30)
            ->register();
 
        // Settings endpoint (admin only)
        Route::for('referrals/settings')
            ->get([$this, 'getSettings'])
            ->post([$this, 'updateSettings'])
            ->auth('admin')
            ->rateLimit(10)
            ->register();
 
        // CSV Upload endpoints (admin only)
        Route::for('referrals/upload-clients')
            ->post([$this, 'handleClientUpload'])
            ->auth('admin')
            ->rateLimit(3)
            ->register();
 
        Route::for('referrals/upload-sales')
            ->post([$this, 'handleSalesUpload'])
            ->auth('admin')
            ->rateLimit(3)
            ->register();
    }
 
    /**
     * GET /referrals
     * Get referrals with optional filters
     * - User gets their own referrals
     * - Admin with no user param gets all referrals
     */
    public function getReferrals(WP_REST_Request $request): WP_REST_Response
    {
        $user_id = $request->get_param('user');
 
        // Determine scope: admin without user param gets all referrals
        if (!$user_id) {
            $current_user_id = get_current_user_id();
            if (current_user_can('manage_options')) {
                return $this->getAllReferrals($request);
            }
            $user_id = $current_user_id;
        }
 
        // Build cache key
        $args = [
            'status' => $request->get_param('status') ?? 'all',
            'limit' => $request->get_param('limit') ?? 50,
            'offset' => $request->get_param('offset') ?? 0,
            'date_start' => $request->get_param('date_start'),
            'date_end' => $request->get_param('date_end'),
        ];
        $cache_key = "user_{$user_id}_" . $this->cache->generateKey($args);
 
        // Check 304 Not Modified
        $cache_check = $this->checkHeaders($request, $cache_key);
        if ($cache_check instanceof WP_REST_Response) {
            return $cache_check;
        }
 
        // Get referrals from manager
        $referrals = JVB()->referrals()->getUserReferrals($user_id, $args);
 
        $data = [
            'items' => $referrals,
            'total' => count($referrals)
        ];
 
        $response = $this->success($data);
        return $this->addCacheHeaders($response);
    }
 
    /**
     * POST /referrals
     * Handle various referral actions based on 'action' parameter
     */
    public function handleAction(WP_REST_Request $request): WP_REST_Response
    {
        $action = $request->get_param('action');
 
        return match($action) {
            'invite' => $this->actionInvite($request),
            'consulted' => $this->actionUpdateStatus($request, 'consulted'),
            'treated' => $this->actionUpdateStatus($request, 'treated'),
            'remove' => $this->actionRemove($request),
            'resend' => $this->actionResend($request),
            default => $this->error('Invalid action', 'invalid_action', 400)
        };
    }
 
    /**
     * Action: Send batch referral invitations
     */
    protected function actionInvite(WP_REST_Request $request): WP_REST_Response
    {
        $user = absint($request->get_param('user'));
        if (!$user || !get_userdata($user)) {
            return $this->error('Invalid user', 'invalid_user', 400);
        }
 
        //Additional check to not send too many emails in an hour
        $user = absint($request->get_param('user'));
        $transient_key = "referral_invite_limit_{$user}";
        $recent_invites = get_transient($transient_key) ?: 0;
 
        if ($recent_invites >= 20) { // Max 5 batch invites per hour
            return $this->error('Too many invitations sent. Please try again later.', 'rate_limit', 429);
        }
        set_transient($transient_key, $recent_invites + 1, HOUR_IN_SECONDS);
 
        $subject = sanitize_text_field($request->get_param('subject'));
        $message = sanitize_textarea_field($request->get_param('message'));
        $invitations = $request->get_param('invite');
 
        // Validate and sanitize invitations
        $sanitized_invitations = [];
        foreach ($invitations as $invite) {
            if (isset($invite['name'], $invite['email'])) {
                $sanitized_invitations[] = [
                    'name' => sanitize_text_field($invite['name']),
                    'email' => sanitize_email($invite['email'])
                ];
            }
        }
 
        if (empty($sanitized_invitations)) {
            return $this->error('No valid invitations provided', 'no_invitations', 400);
        }
 
        $operationID = sanitize_text_field($request->get_param('id'));
        JVB()->queue()->queueOperation(
            'referral_invite',
            $user,
            [
                'subject' => $subject,
                'message' => $message,
                'invitations' => $sanitized_invitations
            ],
            ['operation_id' => $operationID]
        );
 
        return $this->queued($operationID, 'Referral invitations queued');
    }
 
    /**
     * Action: Update referral status (admin only)
     */
    protected function actionUpdateStatus(WP_REST_Request $request, string $status): WP_REST_Response
    {
        if (!current_user_can('manage_options')) {
            return $this->forbidden('Admin permission required');
        }
 
        $referral_id = $request->get_param('referral_id');
        if (!$referral_id) {
            return $this->error('referral_id required', 'missing_id', 400);
        }
 
        $result = JVB()->referrals()->updateStatus($referral_id, $status);
 
        if (is_wp_error($result)) {
            $code = $result->get_error_code();
            return $code === 'not_found'
                ? $this->notFound($result->get_error_message())
                : $this->error($result->get_error_message(), $code, 500);
        }
 
        $this->cache->flush();
        return $this->success(['message' => "Referral marked as {$status}"]);
    }
 
    /**
     * Action: Remove referral
     */
    protected function actionRemove(WP_REST_Request $request): WP_REST_Response
    {
        $referral_id = $request->get_param('referral_id');
        if (!$referral_id) {
            return $this->error('referral_id required', 'missing_id', 400);
        }
 
        $result = JVB()->referrals()->removeReferral($referral_id, get_current_user_id());
 
        if (is_wp_error($result)) {
            $code = $result->get_error_code();
            $status = match($code) {
                'not_found'      => 404,
                'unauthorized'   => 403,
                'invalid_status' => 400,
                default          => 500
            };
            return $this->error($result->get_error_message(), $code, $status);
        }
 
        $this->cache->flush();
        return $this->success(['message' => 'Referral removed']);
    }
 
    /**
     * Action: Resend invitation
     */
    protected function actionResend(WP_REST_Request $request): WP_REST_Response
    {
        $referral_id = $request->get_param('referral_id');
        if (!$referral_id) {
            return $this->error('referral_id required', 'missing_id', 400);
        }
 
        $result = JVB()->referrals()->resendInvitation($referral_id, get_current_user_id());
 
        if (is_wp_error($result)) {
            $code = $result->get_error_code();
            $status = match($code) {
                'not_found'  => 404,
                'rate_limit' => 429,
                default      => 500
            };
            return $this->error($result->get_error_message(), $code, $status);
        }
 
        return $this->success(['message' => 'Invitation resent']);
    }
 
    /**
     * GET /referrals/code
     * Get user's referral code
     */
    public function getCode(WP_REST_Request $request): WP_REST_Response
    {
        $user_id = $request->get_param('user') ?? get_current_user_id();
 
        // Check permission
        if ($user_id != get_current_user_id() && !current_user_can('manage_options')) {
            return $this->forbidden('Unauthorized');
        }
 
        $code = JVB()->referrals()->getUserReferralCode($user_id);
 
        if (is_wp_error($code)) {
            return $this->error($code->get_error_message(), 'code_error', 400);
        }
 
        return $this->success([
            'code' => $code,
            'share_url' => home_url('/?ref=' . $code)
        ]);
    }
 
    /**
     * POST /referrals/code
     * Validate a referral code
     */
    public function validateCode(WP_REST_Request $request): WP_REST_Response
    {
        $code = strtoupper(sanitize_text_field($request->get_param('code')));
 
        if (empty($code)) {
            return $this->error('Code required', 'missing_code', 400);
        }
 
        $referrer = JVB()->referrals()->getUserByReferralCode($code);
 
        if (!$referrer) {
            return $this->error('Invalid referral code', 'invalid_code', 404);
        }
 
        // Check self-referral
        if (is_user_logged_in() && get_current_user_id() === $referrer->ID) {
            return $this->error('Cannot use your own referral code', 'self_referral', 400);
        }
 
        return $this->success([
            'valid' => true,
            'code' => $code,
            'referrer_name' => $referrer->display_name
        ]);
    }
 
    /**
     * GET /referrals/stats
     * Get user's referral statistics
     */
    public function getStats(WP_REST_Request $request): WP_REST_Response
    {
        $user_id = $request->get_param('user') ?? get_current_user_id();
        $cache_key = "stats_{$user_id}";
 
        // Check 304 Not Modified
        $cache_check = $this->checkHeaders($request, $cache_key);
        if ($cache_check instanceof WP_REST_Response) {
            return $cache_check;
        }
 
        $stats = JVB()->referrals()->getUserStats($user_id);
 
        $response = $this->success(['items' => [$stats]]);
        return $this->addCacheHeaders($response);
    }
 
    /**
     * GET /referrals/settings
     */
    public function getSettings(WP_REST_Request $request): WP_REST_Response
    {
        $settings = JVB()->referrals()->getRewardSettings();
        return $this->success(['settings' => $settings]);
    }
 
    /**
     * POST /referrals/settings
     */
    public function updateSettings(WP_REST_Request $request): WP_REST_Response
    {
        $settings = [
            'referrer_reward_type' => $request->get_param('referrer_reward_type') ?? 'fixed',
            'referrer_reward_amount' => floatval($request->get_param('referrer_reward_amount') ?? 25),
            'referrer_reward_applies_to' => $request->get_param('referrer_reward_applies_to') ?? 'per_user',
            'referee_reward_type' => $request->get_param('referee_reward_type') ?? 'percentage',
            'referee_reward_amount' => floatval($request->get_param('referee_reward_amount') ?? 20),
            'referee_reward_applies_to' => $request->get_param('referee_reward_applies_to') ?? 'first_order'
        ];
 
        update_option(BASE . 'referral_settings', $settings);
        $this->cache->flush();
 
        return $this->success([
            'message' => 'Settings updated',
            'settings' => $settings
        ]);
    }
 
    /**
     * Helper: Get all referrals (admin only)
     */
    protected function getAllReferrals(WP_REST_Request $request): WP_REST_Response
    {
        $items = JVB()->referrals()->getAllReferrals([
            'status'     => $request->get_param('status') ?? 'all',
            'search'     => $request->get_param('search'),
            'date_start' => $request->get_param('date_start'),
            'date_end'   => $request->get_param('date_end'),
            'limit'      => $request->get_param('limit') ?? 50,
            'offset'     => $request->get_param('offset') ?? 0,
        ]);
 
        return $this->success(['items' => $items, 'total' => count($items)]);
    }
 
 
    /**
     * Process queued referral operations
     */
    public function processOperation(WP_Error|array $result, object $operation, array $data): array|WP_Error
    {
        if ($operation->type !== 'referral_invite') {
            return $result;
        }
 
        $result = JVB()->referrals()->sendBatchReferralInvitations(
            $operation->user_id,
            $data['invitations'],
            $data['subject'],
            $data['message']
        );
 
        if ($result['success']) {
            $this->cache->flush();
        }
 
        return [
            'success' => true,
            'message' => sprintf(
                'Sent invitations. Success: %d. Failed: %d.',
                count($result['result']['success']),
                count($result['result']['failed'])
            ),
            'details' => [
                'successful' => $result['result']['success'],
                'failed' => $result['result']['failed'],
                'total' => count($data['invitations'])
            ]
        ];
    }
 
    /**
     * Handle client CSV upload
     */
    public function handleClientUpload(WP_REST_Request $request): WP_REST_Response
    {
        if (empty($_FILES['file'])) {
            return $this->error('No file uploaded', 'no_file', 400);
        }
 
        $file = $_FILES['file'];
 
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return $this->error('File upload error: ' . $file['error'], 'upload_error', 400);
        }
 
        // Validate file type
        $allowed_types = ['text/csv', 'application/vnd.ms-excel', 'text/plain'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);
 
        if (!in_array($mime_type, $allowed_types) && !in_array($file['type'], $allowed_types)) {
            return $this->error('File must be a CSV', 'invalid_file_type', 400);
        }
 
        // Validate file size (10MB max)
        if ($file['size'] > 10 * 1024 * 1024) {
            return $this->error('File size exceeds 10MB limit', 'file_too_large', 400);
        }
 
        // Import using JaneAppClientImporter
        $importer = new JaneAppClientImporter();
        $default_role = get_option(BASE . 'referral_role', Site::getDefaultReferralRole());
 
        $options = [
            'update_existing' => true,
            'send_welcome_email' => false,
            'create_users' => true,
            'default_role' => $default_role
        ];
 
        $result = $importer->importFromCSV($file['tmp_name'], $options);
 
        if (is_wp_error($result)) {
            return $this->error($result->get_error_message(), 'import_failed', 500);
        }
 
        $this->cache->flush();
 
        return $this->success([
            'message' => sprintf(
                'Import complete: %d created, %d updated, %d skipped',
                $result['created'],
                $result['updated'],
                $result['skipped']
            ),
            'stats' => $result,
            'skipped_details' => $result['skipped_details'] ?? []
        ]);
    }
 
    /**
     * Handle sales CSV upload
     */
    public function handleSalesUpload(WP_REST_Request $request): WP_REST_Response
    {
        if (empty($_FILES['file'])) {
            return $this->error('No file uploaded', 'no_file', 400);
        }
 
        $file = $_FILES['file'];
 
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return $this->error('File upload error: ' . $file['error'], 'upload_error', 400);
        }
 
        // Validate file type
        $allowed_types = ['text/csv', 'application/vnd.ms-excel', 'text/plain'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);
 
        if (!in_array($mime_type, $allowed_types) && !in_array($file['type'], $allowed_types)) {
            return $this->error('File must be a CSV', 'invalid_file_type', 400);
        }
 
        // Validate file size (10MB max)
        if ($file['size'] > 10 * 1024 * 1024) {
            return $this->error('File size exceeds 10MB limit', 'file_too_large', 400);
        }
 
        // Import using JaneAppSalesImporter
        $importer = new JaneAppSalesImporter();
        $result = $importer->importFromCSV($file['tmp_name'], ['skip_existing' => true]);
 
        if (is_wp_error($result)) {
            return $this->error($result->get_error_message(), 'import_failed', 500);
        }
 
        $this->cache->flush();
 
        return $this->success([
            'message' => 'Sales imported successfully',
            'stats' => $result
        ]);
    }
}