wpdb = $wpdb; $this->sessions = $sessions; $this->candidates = $candidates; $this->events = $events; $this->settings = $settings; $this->clock = $clock; } /** * Builds an error. * * @param string $code Short code. * @param string $message Message. * @param int $status HTTP status. * @return WP_Error */ private function error( string $code, string $message, int $status = 400 ): WP_Error { return new WP_Error( 'interviewnea_' . $code, $message, array( 'status' => $status ) ); } /** * Runs a callback in a transaction holding the session row lock. * * @param int $session_id Session id. * @param callable $callback Receives the locked session row; returns data or WP_Error. * @return mixed|WP_Error */ private function with_lock( int $session_id, callable $callback ) { if ( false === $this->wpdb->query( 'START TRANSACTION' ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching return $this->error( 'database', __( 'The queue is temporarily unavailable.', 'interviewnea' ), 503 ); } try { $session = $this->sessions->find( $session_id, true ); if ( ! $session ) { $this->wpdb->query( 'ROLLBACK' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching return $this->error( 'session_missing', __( 'Interview session was not found.', 'interviewnea' ), 404 ); } $result = $callback( $session ); if ( is_wp_error( $result ) ) { $this->wpdb->query( 'ROLLBACK' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching return $result; } if ( false === $this->wpdb->query( 'COMMIT' ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $this->wpdb->query( 'ROLLBACK' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching return $this->error( 'database', __( 'The queue could not be saved.', 'interviewnea' ), 503 ); } return $result; } catch ( Throwable $e ) { $this->wpdb->query( 'ROLLBACK' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( '[InterviewNea] ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Only when WP_DEBUG is on. } return $this->error( 'database', __( 'The queue is temporarily unavailable.', 'interviewnea' ), 503 ); } } /** * Tells whether a database write failed. * * @param bool $ok Result of the write. * @param string $message Message for the error. * @return WP_Error|null */ private function write_failed( bool $ok, string $message ): ?WP_Error { return $ok ? null : $this->error( 'database', $message, 503 ); } /** * Cut-off for "online": candidates seen before this are offline. * * @return string UTC DATETIME. */ private function online_cutoff(): string { return gmdate( 'Y-m-d H:i:s', $this->clock->time() - Rules::ONLINE_SECONDS ); } // ------------------------------------------------------------------------------------------- // Candidate-facing operations. // ------------------------------------------------------------------------------------------- /** * Session id behind a token, or 0. * * @since 0.1.0 * * @param string $token Plain token. * @return int */ public function token_session( string $token ): int { $candidate = $this->candidates->by_token( $token ); return $candidate ? (int) $candidate->session_id : 0; } /** * Verifies a candidate against the application records and puts them in the queue. * * @since 0.1.0 * * @param int $session_id Session id. * @param string $name Name as typed. * @param string $email Email as typed. * @param string $phone Phone as typed. * @return array{token:string,state:array}|WP_Error */ public function check_in( int $session_id, string $name, string $email, string $phone ) { return $this->with_lock( $session_id, function ( $session ) use ( $name, $email, $phone ) { if ( ! SessionWindow::allowed( $session, $this->clock->site_now(), wp_timezone() ) ) { return $this->not_open_error( $session ); } $candidate = $this->candidates->by_identity( (int) $session->id, $email, $phone ); if ( $candidate && $this->settings->get( 'strict_name_match' ) && Identity::name( $name ) !== $candidate->name_normalized ) { $candidate = null; } if ( ! $candidate ) { return $this->error( 'verification_failed', __( 'We could not verify your application details. Check your email and phone number or contact the recruitment team.', 'interviewnea' ), 403 ); } if ( 'completed' === $candidate->status ) { return $this->error( 'already_complete', __( 'This interview has already been marked completed. Contact the recruitment team if this is unexpected.', 'interviewnea' ), 409 ); } if ( 'no_show' === $candidate->status ) { return $this->error( 'no_show', __( 'Please contact the recruitment team to request another interview opportunity.', 'interviewnea' ), 409 ); } $now = $this->clock->mysql_now(); $data = array(); if ( in_array( $candidate->status, array( 'invited', 'skipped' ), true ) ) { $data['status'] = 'queued'; $data['queued_at'] = $now; $bounds = SessionWindow::bounds( $session, wp_timezone() ); if ( 'skipped' === $candidate->status || ( $bounds && $this->clock->site_now() > $bounds[0] ) ) { $data['queue_order'] = $this->candidates->max_order( (int) $session->id ) + 1; } } elseif ( 'queued' === $candidate->status && $this->offline_too_long( $candidate ) && $this->session_started( $session ) ) { $data['queue_order'] = $this->candidates->max_order( (int) $session->id ) + 1; } // The last check-in wins: it replaces the token, so an older browser has to verify again. $token = bin2hex( random_bytes( 32 ) ); $data['token_hash'] = hash( 'sha256', $token ); $data['last_seen_at'] = $now; if ( ! $candidate->checkin_at ) { $data['checkin_at'] = $now; } $failed = $this->write_failed( $this->candidates->update( (int) $candidate->id, $data ), __( 'Check-in could not be saved. Please retry.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $this->events->log( (int) $session->id, (int) $candidate->id, 'check_in', 'Status: ' . ( $data['status'] ?? $candidate->status ) ); $tick = $this->tick_locked( (int) $session->id ); if ( is_wp_error( $tick ) ) { return $tick; } return array( 'token' => $token, 'state' => $this->public_payload( (int) $session->id, (int) $candidate->id ), ); } ); } /** * Heartbeat and current state of a candidate. Cheap unless a transition is due. * * @since 0.1.0 * * @param string $token Plain token. * @return array|WP_Error */ public function state( string $token ) { $candidate = $this->candidates->by_token( $token ); if ( ! $candidate ) { return $this->unauthorized(); } $session = $this->sessions->find( (int) $candidate->session_id ); if ( ! $session ) { return $this->unauthorized(); } if ( $this->needs_lock( $session, $candidate ) ) { return $this->with_lock( (int) $session->id, function ( $locked ) use ( $candidate ) { $fresh = $this->candidates->find( (int) $candidate->id ); if ( ! $fresh ) { return $this->unauthorized(); } $changes = array( 'last_seen_at' => $this->clock->mysql_now() ); if ( 'queued' === $fresh->status && $this->offline_too_long( $fresh ) && $this->session_started( $locked ) ) { $changes['queue_order'] = $this->candidates->max_order( (int) $locked->id ) + 1; $this->events->log( (int) $locked->id, (int) $fresh->id, 'returned_late', 'Moved to queue end after extended disconnection' ); } $failed = $this->write_failed( $this->candidates->update( (int) $fresh->id, $changes ), __( 'Could not update queue presence.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $tick = $this->tick_locked( (int) $locked->id ); if ( is_wp_error( $tick ) ) { return $tick; } return $this->public_payload( (int) $locked->id, (int) $fresh->id ); } ); } $this->candidates->touch( (int) $candidate->id, $this->clock->mysql_now() ); return $this->public_payload( (int) $session->id, (int) $candidate->id ); } /** * Moves a skipped candidate to the end of the queue. * * @since 0.1.0 * * @param string $token Plain token. * @return array|WP_Error */ public function requeue( string $token ) { $session_id = $this->token_session( $token ); if ( ! $session_id ) { return $this->unauthorized(); } return $this->with_lock( $session_id, function ( $session ) use ( $token ) { $candidate = $this->candidate_for_token( $token, (int) $session->id ); if ( is_wp_error( $candidate ) ) { return $candidate; } if ( 'skipped' !== $candidate->status || ! SessionWindow::allowed( $session, $this->clock->site_now(), wp_timezone() ) ) { return $this->error( 'not_available', __( 'Self-service rejoin is not available. Please contact the recruitment team.', 'interviewnea' ), 409 ); } $now = $this->clock->mysql_now(); $failed = $this->write_failed( $this->candidates->update( (int) $candidate->id, array( 'status' => 'queued', 'queue_order' => $this->candidates->max_order( (int) $session->id ) + 1, 'queued_at' => $now, 'last_seen_at' => $now, 'called_until' => null, ) ), __( 'Rejoin failed. Please retry.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $this->events->log( (int) $session->id, (int) $candidate->id, 'requeued', 'Candidate requested rejoin at queue end' ); return $this->public_payload( (int) $session->id, (int) $candidate->id ); } ); } /** * Releases the Meet link to the candidate whose turn it is. * * @since 0.1.0 * * @param string $token Plain token. * @return array{meet_url:string,state:array}|WP_Error */ public function join( string $token ) { $session_id = $this->token_session( $token ); if ( ! $session_id ) { return $this->unauthorized(); } return $this->with_lock( $session_id, function ( $session ) use ( $token ) { $candidate = $this->candidate_for_token( $token, (int) $session->id ); if ( is_wp_error( $candidate ) ) { return $candidate; } $tick = $this->tick_locked( (int) $session->id ); if ( is_wp_error( $tick ) ) { return $tick; } $candidate = $this->candidates->find( (int) $candidate->id ); $session = $this->sessions->find( (int) $session->id ); if ( ! $candidate || ! $session || (int) $session->current_candidate_id !== (int) $candidate->id || ! in_array( $candidate->status, array( 'called', 'join_requested', 'interviewing' ), true ) ) { return $this->error( 'not_called', __( 'Your interview is not currently being called. Please wait for your turn.', 'interviewnea' ), 403 ); } if ( 'called' === $candidate->status ) { $failed = $this->write_failed( $this->candidates->update( (int) $candidate->id, array( 'status' => 'join_requested', 'join_requested_at' => $this->clock->mysql_now(), 'called_until' => null, ) ), __( 'Could not open the interview.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $this->events->log( (int) $session->id, (int) $candidate->id, 'meet_link_opened', 'Candidate opened Meet link; host admission not yet confirmed' ); } return array( 'meet_url' => esc_url_raw( $session->meet_url ), 'state' => $this->public_payload( (int) $session->id, (int) $candidate->id ), ); } ); } // ------------------------------------------------------------------------------------------- // Staff operations. // ------------------------------------------------------------------------------------------- /** * Calls the next online candidate. * * @since 0.1.0 * * @param int $session_id Session id. * @return array|WP_Error */ public function call_next( int $session_id ) { return $this->with_lock( $session_id, function ( $session ) { if ( 'paused' === $session->status ) { return $this->error( 'paused', __( 'Resume the session before calling the next candidate.', 'interviewnea' ), 409 ); } if ( ! SessionWindow::interview_allowed( $session, $this->clock->site_now(), wp_timezone() ) ) { return $this->error( 'outside_window', __( 'Interviews can only be called during the scheduled start and end time.', 'interviewnea' ), 409 ); } $tick = $this->tick_locked( (int) $session->id ); if ( is_wp_error( $tick ) ) { return $tick; } $current = $this->call_next_locked( (int) $session->id ); if ( is_wp_error( $current ) ) { return $current; } return array( 'called_id' => $current ? (int) $current->id : 0, 'message' => $current ? __( 'Candidate called.', 'interviewnea' ) : __( 'No online, ready candidate is available.', 'interviewnea' ), ); } ); } /** * Completes the confirmed interview and calls the next candidate. * * @since 0.1.0 * * @param int $session_id Session id. * @return array|WP_Error */ public function complete_and_next( int $session_id ) { return $this->with_lock( $session_id, function ( $session ) { if ( ! (int) $session->current_candidate_id ) { return $this->error( 'no_current', __( 'There is no active interview.', 'interviewnea' ), 409 ); } $current = $this->candidates->find( (int) $session->current_candidate_id ); if ( ! $current || 'interviewing' !== $current->status ) { return $this->error( 'not_active', __( 'First confirm Joined after verifying the candidate in Google Meet.', 'interviewnea' ), 409 ); } $failed = $this->write_failed( $this->candidates->update( (int) $current->id, array( 'status' => 'completed', 'completed_at' => $this->clock->mysql_now(), 'called_until' => null, ) ), __( 'Unable to complete interview.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $failed = $this->write_failed( $this->sessions->update( (int) $session->id, array( 'current_candidate_id' => 0 ) ), __( 'Unable to release queue.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $this->events->log( (int) $session->id, (int) $current->id, 'completed', 'Completed by interviewer', get_current_user_id() ); $next = $this->call_next_locked( (int) $session->id ); if ( is_wp_error( $next ) ) { return $next; } return array( 'completed_id' => (int) $current->id, 'called_id' => $next ? (int) $next->id : 0, ); } ); } /** * Applies a staff action to one candidate. * * @since 0.1.0 * * @param int $session_id Session id. * @param int $candidate_id Candidate id. * @param string $action One of Rules::candidate_actions(). * @return array|WP_Error */ public function candidate_action( int $session_id, int $candidate_id, string $action ) { return $this->with_lock( $session_id, function ( $session ) use ( $candidate_id, $action ) { $candidate = $this->candidates->find( $candidate_id ); if ( ! $candidate || (int) $candidate->session_id !== (int) $session->id ) { return $this->error( 'candidate_missing', __( 'Candidate not found in this session.', 'interviewnea' ), 404 ); } $is_current = (int) $session->current_candidate_id === $candidate_id; if ( ! CandidateLifecycle::allows_admin_action( $candidate->status, $action, $is_current, $session->status ) ) { return $this->error( 'invalid_transition', __( 'Action not allowed for this candidate status.', 'interviewnea' ), 409 ); } $now = $this->clock->mysql_now(); switch ( $action ) { case 'confirm_join': $data = array( 'status' => 'interviewing', 'joined_at' => $now, 'called_until' => null, ); break; case 'skip': $data = array( 'status' => 'skipped', 'called_until' => null, ); break; case 'late': $data = array( 'status' => 'skipped', 'late_at' => $now, 'called_until' => null, ); break; case 'no_show': $data = array( 'status' => 'no_show', 'called_until' => null, ); break; default: // requeue. $data = array( 'status' => 'queued', 'queue_order' => $this->candidates->max_order( (int) $session->id ) + 1, 'queued_at' => $now, 'last_seen_at' => null, 'called_until' => null, ); break; } $failed = $this->write_failed( $this->candidates->update( $candidate_id, $data ), __( 'Unable to update candidate status.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $releases_slot = $is_current && 'confirm_join' !== $action; if ( $releases_slot ) { $failed = $this->write_failed( $this->sessions->update( (int) $session->id, array( 'current_candidate_id' => 0 ) ), __( 'Could not release interview slot.', 'interviewnea' ) ); if ( $failed ) { return $failed; } } $labels = array( 'confirm_join' => __( 'Host verified candidate inside Google Meet', 'interviewnea' ), 'skip' => __( 'Temporarily bypassed; candidate may rejoin', 'interviewnea' ), 'late' => __( 'Marked late; standby rejoin is allowed', 'interviewnea' ), 'no_show' => __( 'Marked absent; admin must requeue to reverse', 'interviewnea' ), 'requeue' => __( 'Restored to queue end by admin', 'interviewnea' ), ); $this->events->log( (int) $session->id, $candidate_id, $action, $labels[ $action ], get_current_user_id() ); $next = $releases_slot ? $this->call_next_locked( (int) $session->id ) : null; if ( is_wp_error( $next ) ) { return $next; } return array( 'ok' => true, 'message' => $labels[ $action ], 'called_id' => $next ? (int) $next->id : 0, ); } ); } /** * Start, pause, resume or close a session. * * @since 0.1.0 * * @param int $session_id Session id. * @param string $action One of Rules::session_actions(). * @param int $duration_minutes Pause length. * @param string $reason Pause reason. * @return array|WP_Error */ public function session_action( int $session_id, string $action, int $duration_minutes = 0, string $reason = '' ) { return $this->with_lock( $session_id, function ( $session ) use ( $action, $duration_minutes, $reason ) { $transitions = array( 'start' => array( 'scheduled' => 'active' ), 'pause' => array( 'active' => 'paused' ), 'resume' => array( 'paused' => 'active' ), 'close' => array( 'scheduled' => 'completed', 'active' => 'completed', 'paused' => 'completed', ), ); if ( ! isset( $transitions[ $action ][ $session->status ] ) ) { return $this->error( 'invalid_transition', __( 'This session status change is not allowed.', 'interviewnea' ), 409 ); } if ( 'pause' === $action && (int) $session->current_candidate_id ) { return $this->error( 'active_candidate', __( 'Complete or skip the current interview before pausing.', 'interviewnea' ), 409 ); } if ( 'close' === $action && (int) $session->current_candidate_id ) { return $this->error( 'active_candidate', __( 'Complete or skip the active candidate before closing the session.', 'interviewnea' ), 409 ); } $status = $transitions[ $action ][ $session->status ]; $update = array( 'status' => $status ); if ( 'pause' === $action ) { $minutes = max( 1, min( Rules::MAX_PAUSE_MINUTES, $duration_minutes ) ); $update['pause_until'] = gmdate( 'Y-m-d H:i:s', $this->clock->time() + $minutes * 60 ); $update['pause_reason'] = Helpers::truncate( sanitize_text_field( $reason ), 120 ); } if ( 'resume' === $action ) { $update['pause_until'] = null; $update['pause_reason'] = ''; } $failed = $this->write_failed( $this->sessions->update( (int) $session->id, $update ), __( 'Unable to update the session.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $detail = 'New status: ' . $status; if ( 'pause' === $action ) { $detail .= '. Resumes at ' . $update['pause_until'] . ' UTC'; if ( '' !== $update['pause_reason'] ) { $detail .= ' (' . $update['pause_reason'] . ')'; } } $this->events->log( (int) $session->id, 0, 'session_' . $action, $detail, get_current_user_id() ); return array( 'status' => $status ); } ); } /** * Live view for the staff dashboard: the session, its candidates and who is online. * * @since 0.1.0 * * @param int $session_id Session id. * @return array|WP_Error */ public function live_state( int $session_id ) { $session = $this->sessions->find( $session_id ); if ( ! $session ) { return $this->error( 'session_missing', __( 'Interview session was not found.', 'interviewnea' ), 404 ); } if ( $this->call_expired( $session ) ) { $ticked = $this->with_lock( $session_id, function () use ( $session_id ) { return $this->tick_locked( $session_id ); } ); if ( is_wp_error( $ticked ) ) { return $ticked; } $session = $this->sessions->find( $session_id ); } $cutoff = Helpers::timestamp( $this->online_cutoff() ); $rows = array(); foreach ( $this->candidates->for_session( $session_id ) as $record ) { $rows[] = array( 'id' => (int) $record->id, 'name' => $record->full_name, 'email' => $record->email, 'phone' => $record->phone, 'status' => $record->status, 'queue_order' => (int) $record->queue_order, 'online' => Helpers::timestamp( $record->last_seen_at ) >= $cutoff && $cutoff > 0, 'checked_in' => (bool) $record->checkin_at, 'join_requested_at' => Helpers::iso( $record->join_requested_at ), 'joined_at' => Helpers::iso( $record->joined_at ), 'report_time' => $record->report_time ? substr( $record->report_time, 0, 5 ) : null, 'late' => (bool) $record->late_at, 'reminder_status' => $record->reminder_status, 'join_reminder_status' => $record->join_reminder_status, 'checkin_at' => Helpers::iso( $record->checkin_at ), 'called_until' => Helpers::iso( $record->called_until ), ); } return array( 'session' => $this->session_summary( $session ), 'candidates' => $rows, 'server_time' => gmdate( 'c', $this->clock->time() ), ); } // ------------------------------------------------------------------------------------------- // Candidate record changes that must be serialised with the queue. // ------------------------------------------------------------------------------------------- /** * Adds a candidate at the end of the queue. * * @since 0.1.0 * * @param int $session_id Session id. * @param array $fields name, email, phone, report_time (already validated). * @return array{ok:bool,id:int}|WP_Error */ public function create_candidate( int $session_id, array $fields ) { return $this->with_lock( $session_id, function ( $session ) use ( $fields ) { if ( $this->candidates->by_email( (int) $session->id, $fields['email'] ) ) { return $this->error( 'duplicate', __( 'A candidate with this email already exists in this session.', 'interviewnea' ), 409 ); } $id = $this->candidates->insert( array( 'session_id' => (int) $session->id, 'full_name' => $fields['name'], 'name_normalized' => Identity::name( $fields['name'] ), 'email' => Identity::email( $fields['email'] ), 'email_key' => Identity::email_key( $fields['email'] ), 'phone' => $fields['phone'], 'phone_normalized' => Identity::phone( $fields['phone'] ), 'queue_order' => $this->candidates->max_order( (int) $session->id ) + 1, 'report_time' => $fields['report_time'], 'status' => 'invited', ) ); if ( ! $id ) { return $this->error( 'database', __( 'Unable to create candidate.', 'interviewnea' ), 503 ); } $this->events->log( (int) $session->id, $id, 'candidate_added', 'Candidate added by admin', get_current_user_id() ); return array( 'ok' => true, 'id' => $id, ); } ); } /** * Edits a candidate who is not in an active call. * * @since 0.1.0 * * @param int $session_id Session id. * @param int $candidate_id Candidate id. * @param array $fields name, email, phone, report_time (already validated). * @return array{ok:bool}|WP_Error */ public function update_candidate( int $session_id, int $candidate_id, array $fields ) { return $this->with_lock( $session_id, function ( $session ) use ( $candidate_id, $fields ) { $candidate = $this->candidates->find( $candidate_id ); if ( ! $candidate || (int) $candidate->session_id !== (int) $session->id ) { return $this->error( 'candidate_missing', __( 'Candidate not found.', 'interviewnea' ), 404 ); } if ( ! CandidateLifecycle::can_modify( $candidate->status, (int) $session->current_candidate_id === $candidate_id ) ) { return $this->error( 'locked', __( 'Finish or skip this call before editing.', 'interviewnea' ), 409 ); } $duplicate = $this->candidates->by_email( (int) $session->id, $fields['email'] ); if ( $duplicate && (int) $duplicate->id !== $candidate_id ) { return $this->error( 'duplicate', __( 'This email belongs to another candidate in this session.', 'interviewnea' ), 409 ); } $new_name = Identity::name( $fields['name'] ); $new_key = Identity::email_key( $fields['email'] ); $new_phone = Identity::phone( $fields['phone'] ); $new_time = (string) $fields['report_time']; $identity_changed = $new_name !== $candidate->name_normalized || $new_key !== $candidate->email_key || $new_phone !== $candidate->phone_normalized; $reminder_changed = $new_key !== $candidate->email_key || $new_time !== (string) $candidate->report_time; $data = array( 'full_name' => $fields['name'], 'name_normalized' => Identity::name( $fields['name'] ), 'email' => Identity::email( $fields['email'] ), 'email_key' => Identity::email_key( $fields['email'] ), 'phone' => $fields['phone'], 'phone_normalized' => Identity::phone( $fields['phone'] ), 'report_time' => $fields['report_time'], ); if ( $identity_changed ) { $data['token_hash'] = ''; // The old browser must verify again. $data['last_seen_at'] = null; } if ( $reminder_changed ) { foreach ( array( 'reminder_status', 'join_reminder_status' ) as $column ) { if ( ! in_array( $candidate->$column, array( 'accepted', 'processing' ), true ) ) { $data[ $column ] = 'pending'; } } } $failed = $this->write_failed( $this->candidates->update( $candidate_id, $data ), __( 'Unable to save candidate.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $this->events->log( (int) $session->id, $candidate_id, 'candidate_edited', $identity_changed ? 'Identity updated; old token revoked' : 'Candidate details updated', get_current_user_id() ); return array( 'ok' => true ); } ); } /** * Deletes a candidate who is not in an active call, with their personal logs. * * @since 0.1.0 * * @param int $session_id Session id. * @param int $candidate_id Candidate id. * @return array{ok:bool}|WP_Error */ public function delete_candidate( int $session_id, int $candidate_id ) { return $this->with_lock( $session_id, function ( $session ) use ( $candidate_id ) { $candidate = $this->candidates->find( $candidate_id ); if ( ! $candidate || (int) $candidate->session_id !== (int) $session->id ) { return $this->error( 'candidate_missing', __( 'Candidate not found.', 'interviewnea' ), 404 ); } if ( ! CandidateLifecycle::can_modify( $candidate->status, (int) $session->current_candidate_id === $candidate_id ) ) { return $this->error( 'locked', __( 'Finish or skip this call before deleting.', 'interviewnea' ), 409 ); } $failed = $this->write_failed( $this->candidates->delete( $candidate_id ), __( 'Could not delete candidate.', 'interviewnea' ) ); if ( $failed ) { return $failed; } // The deletion event carries no personal data. $this->events->log( (int) $session->id, 0, 'candidate_deleted', 'Candidate and associated personal logs removed; ID ' . $candidate_id, get_current_user_id() ); return array( 'ok' => true ); } ); } // ------------------------------------------------------------------------------------------- // Internals (callers hold the session lock unless stated). // ------------------------------------------------------------------------------------------- /** * The 401 returned for a missing, replaced or revoked token. * * @return WP_Error */ private function unauthorized(): WP_Error { return $this->error( 'unauthorized', __( 'Your check-in session has expired. Please verify your details again.', 'interviewnea' ), 401 ); } /** * Re-reads the candidate for a token and checks that it belongs to the session. * * @param string $token Token. * @param int $session_id Session id. * @return object|WP_Error */ private function candidate_for_token( string $token, int $session_id ) { $candidate = $this->candidates->by_token( $token ); if ( ! $candidate || (int) $candidate->session_id !== $session_id ) { return $this->unauthorized(); } return $candidate; } /** * Error for check-in outside the window. * * @param object $session Session. * @return WP_Error */ private function not_open_error( $session ): WP_Error { if ( 'completed' === $session->status ) { return $this->error( 'closed', __( 'This interview session has closed.', 'interviewnea' ), 403 ); } return $this->error( 'not_open', __( 'Check-in is only available during your scheduled interview window. Please check the date and time shown above.', 'interviewnea' ), 403 ); } /** * Whether the candidate was away longer than the reconnection grace. * * @param object $candidate Candidate. * @return bool */ private function offline_too_long( $candidate ): bool { $seen = Helpers::timestamp( $candidate->last_seen_at ); return $seen > 0 && $seen < $this->clock->time() - Rules::RECONNECT_SECONDS; } /** * Whether the session start time has passed. * * @param object $session Session. * @return bool */ private function session_started( $session ): bool { $bounds = SessionWindow::bounds( $session, wp_timezone() ); return $bounds && $this->clock->site_now() >= $bounds[0]; } /** * Whether the session's current call has run out. * * @param object $session Session. * @return bool */ private function call_expired( $session ): bool { if ( ! (int) $session->current_candidate_id || in_array( $session->status, array( 'paused', 'completed' ), true ) ) { return false; } $current = $this->candidates->find( (int) $session->current_candidate_id ); if ( ! $current ) { return true; // Dangling pointer: repaired by the tick. } return 'called' === $current->status && $current->called_until && Helpers::timestamp( $current->called_until ) <= $this->clock->time(); } /** * Whether a state request must take the session lock. * * @param object $session Session. * @param object $candidate Candidate. * @return bool */ private function needs_lock( $session, $candidate ): bool { if ( 'queued' === $candidate->status && $this->offline_too_long( $candidate ) && $this->session_started( $session ) ) { return true; } return $this->call_expired( $session ); } /** * Expires a call that ran out and calls the next candidate. Requires the session lock. * * @param int $session_id Session id. * @return WP_Error|null */ private function tick_locked( int $session_id ): ?WP_Error { $session = $this->sessions->find( $session_id ); if ( ! $session || ! (int) $session->current_candidate_id || in_array( $session->status, array( 'paused', 'completed' ), true ) ) { return null; } $current = $this->candidates->find( (int) $session->current_candidate_id ); if ( ! $current ) { return $this->write_failed( $this->sessions->update( $session_id, array( 'current_candidate_id' => 0 ) ), __( 'Could not repair queue state.', 'interviewnea' ) ); } if ( 'called' === $current->status && $current->called_until && Helpers::timestamp( $current->called_until ) <= $this->clock->time() ) { $failed = $this->write_failed( $this->candidates->update( (int) $current->id, array( 'status' => 'skipped', 'called_until' => null, ) ), __( 'Could not expire the call.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $failed = $this->write_failed( $this->sessions->update( $session_id, array( 'current_candidate_id' => 0 ) ), __( 'Could not release the expired call.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $this->events->log( $session_id, (int) $current->id, 'call_expired', 'Join window timed out' ); $next = $this->call_next_locked( $session_id ); if ( is_wp_error( $next ) ) { return $next; } } return null; } /** * Calls the first online queued candidate if the slot is free. Requires the session lock. * * @param int $session_id Session id. * @return object|WP_Error|null The candidate holding the slot, or null. */ private function call_next_locked( int $session_id ) { $session = $this->sessions->find( $session_id ); if ( ! $session ) { return null; } if ( (int) $session->current_candidate_id ) { return $this->candidates->find( (int) $session->current_candidate_id ); } if ( ! SessionWindow::interview_allowed( $session, $this->clock->site_now(), wp_timezone() ) ) { return null; } $next = $this->candidates->ready_next( $session_id, $this->online_cutoff() ); if ( ! $next ) { return null; } $failed = $this->write_failed( $this->candidates->update( (int) $next->id, array( 'status' => 'called', 'called_at' => $this->clock->mysql_now(), 'called_until' => gmdate( 'Y-m-d H:i:s', $this->clock->time() + Rules::CALL_SECONDS ), ) ), __( 'Unable to advance the candidate.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $data = array( 'current_candidate_id' => (int) $next->id ); if ( 'scheduled' === $session->status ) { $data['status'] = 'active'; } $failed = $this->write_failed( $this->sessions->update( $session_id, $data ), __( 'Unable to advance the queue.', 'interviewnea' ) ); if ( $failed ) { return $failed; } $this->events->log( $session_id, (int) $next->id, 'called', 'Join window: ' . Rules::CALL_SECONDS . ' seconds', get_current_user_id() ); return $this->candidates->find( (int) $next->id ); } /** * Short description of a session for API responses. * * @param object $session Session. * @return array */ private function session_summary( $session ): array { return array( 'id' => (int) $session->id, 'title' => $session->title, 'status' => $session->status, 'date' => $session->session_date, 'start' => substr( $session->start_time, 0, 5 ), 'end' => substr( $session->end_time, 0, 5 ), 'current_candidate_id' => (int) $session->current_candidate_id, 'pause_until' => Helpers::iso( $session->pause_until ), 'pause_reason' => '' !== (string) $session->pause_reason ? $session->pause_reason : null, ); } /** * What the waiting-room page needs to render. * * @param int $session_id Session id. * @param int $candidate_id Candidate id. * @return array */ private function public_payload( int $session_id, int $candidate_id ): array { $session = $this->sessions->find( $session_id ); $candidate = $this->candidates->find( $candidate_id ); $ahead = 'queued' === $candidate->status ? $this->candidates->ahead( $candidate, $this->online_cutoff() ) : 0; $active = (int) $session->current_candidate_id && (int) $session->current_candidate_id !== (int) $candidate->id; $position = 'queued' === $candidate->status ? $ahead + ( $active ? 1 : 0 ) + 1 : null; $pause_min = 0; $pause_iso = null; if ( 'paused' === $session->status && ! empty( $session->pause_until ) ) { $pause_min = (int) ceil( max( 0, Helpers::timestamp( $session->pause_until ) - $this->clock->time() ) / 60 ); $pause_iso = Helpers::iso( $session->pause_until ); } $bounds = SessionWindow::bounds( $session, wp_timezone() ); return array( 'candidate_name' => $candidate->full_name, 'status' => $candidate->status, 'session_status' => $session->status, 'session_window_over' => $bounds && $this->clock->site_now() > $bounds[1], 'position' => $position, 'people_ahead' => null === $position ? null : $position - 1, 'estimate_minutes' => null === $position ? null : ( $position - 1 ) * Rules::MINUTES_PER_TURN + $pause_min, 'can_join' => in_array( $candidate->status, array( 'called', 'join_requested', 'interviewing' ), true ) && (int) $session->current_candidate_id === (int) $candidate->id, 'can_rejoin' => 'skipped' === $candidate->status && SessionWindow::allowed( $session, $this->clock->site_now(), wp_timezone() ), 'call_expires_at' => 'called' === $candidate->status ? Helpers::iso( $candidate->called_until ) : null, 'pause_until' => $pause_iso, 'pause_reason' => '' !== (string) $session->pause_reason ? $session->pause_reason : null, 'server_time' => gmdate( 'c', $this->clock->time() ), 'poll_seconds' => Rules::POLL_SECONDS, ); } }