insert($this->table(), [ 'user_id' => $user_id, 'order_number' => $order_number, 'source_user_id' => $source_user_id > 0 ? $source_user_id : null, 'amount' => $amount, 'type' => $type, 'status' => self::STATUS_PENDING, 'created_at' => current_time('mysql'), 'note' => $note, ]); $id = $result ? (int) $wpdb->insert_id : 0; if ($id > 0) { do_action('aksrt_pay_rebate_added', $user_id, $amount, [ 'rebate_id' => $id, 'order_number' => $order_number, 'type' => $type, ]); } return $id; } /** * 结算返佣 */ public function settle(int $id): bool { global $wpdb; $row = $wpdb->get_row($wpdb->prepare( "SELECT * FROM {$this->table()} WHERE id = %d AND status = %s", $id, self::STATUS_PENDING ), ARRAY_A); if (!$row) return false; $user_id = (int) $row['user_id']; $amount = (float) $row['amount']; $result = $wpdb->update($this->table(), [ 'status' => self::STATUS_SETTLED, 'settled_at' => current_time('mysql'), ], ['id' => $id]); if ($result && class_exists('AKSRT_Credits')) { AKSRT_Credits::add($user_id, (int) $amount, 'rebate', [ 'ref_type' => 'rebate', 'ref_id' => $id, ]); } return (bool) $result; } /** * 取消返佣 */ public function cancel(int $id): bool { global $wpdb; return (bool) $wpdb->update($this->table(), [ 'status' => self::STATUS_CANCELLED, ], ['id' => $id, 'status' => self::STATUS_PENDING]); } /** * 获取返佣列表 */ public function get_list(array $args = []): array { global $wpdb; $limit = max(1, min(100, (int) ($args['limit'] ?? 20))); $offset = max(0, (int) ($args['offset'] ?? 0)); $status = sanitize_key((string) ($args['status'] ?? '')); $user_id = (int) ($args['user_id'] ?? 0); $where = []; $params = []; if ($status !== '') { $where[] = 'status = %s'; $params[] = $status; } if ($user_id > 0) { $where[] = 'user_id = %d'; $params[] = $user_id; } $where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : ''; $count_sql = "SELECT COUNT(*) FROM {$this->table()} {$where_sql}"; $total = $params ? (int) $wpdb->get_var($wpdb->prepare($count_sql, $params)) : (int) $wpdb->get_var($count_sql); $sql = "SELECT * FROM {$this->table()} {$where_sql} ORDER BY created_at DESC LIMIT %d OFFSET %d"; $params[] = $limit; $params[] = $offset; $items = $wpdb->get_results($wpdb->prepare($sql, $params), ARRAY_A); return [ 'items' => $items ?: [], 'total' => $total, 'page' => floor($offset / $limit) + 1, 'max_pages' => ceil($total / $limit), ]; } /** * 获取统计 */ public function get_stats(): array { global $wpdb; $table = $this->table(); $row = $wpdb->get_row( "SELECT COUNT(*) as total, SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending, SUM(CASE WHEN status = 'settled' THEN 1 ELSE 0 END) as settled, SUM(amount) as total_amount, SUM(CASE WHEN status = 'settled' THEN amount ELSE 0 END) as settled_amount FROM {$table}", ARRAY_A ); return [ 'total' => (int) ($row['total'] ?? 0), 'pending' => (int) ($row['pending'] ?? 0), 'settled' => (int) ($row['settled'] ?? 0), 'total_amount' => (float) ($row['total_amount'] ?? 0), 'settled_amount' => (float) ($row['settled_amount'] ?? 0), ]; } }