prefix . 'aipt_blueprint_sources'; } /** * Read a single Source by id. * * @param int $id Source id. * @return array|null */ public function get( int $id ): ?array { global $wpdb; $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ), ARRAY_A ); return is_array( $row ) ? $this->mapRow( $row ) : null; } /** * List Sources matching optional equality filters. * * @param array $filters Optional: scopeType, scopeId, enabled, status, kind. * @param int $limit Hard cap. * @return array> */ public function list( array $filters, int $limit = 200 ): array { global $wpdb; $table = self::table(); $limit = $limit > 0 ? min( $limit, self::MAX_LIST_LIMIT ) : 200; $where = $this->buildWhere( $filters ); $where_sql = empty( $where ) ? '' : ' WHERE ' . implode( ' AND ', $where ); $rows = $wpdb->get_results( "SELECT * FROM {$table}{$where_sql} ORDER BY name ASC LIMIT " . (int) $limit, ARRAY_A ); return is_array( $rows ) ? array_map( array( $this, 'mapRow' ), $rows ) : array(); } /** * Which of the given ids exist, regardless of list()'s 500-row page cap * — used to validate a specific 'src:' reference directly instead * of checking membership in a capped, by-name-sorted page, so a store * with more than MAX_LIST_LIMIT sources can still save a structure that * references one outside that first page. * * @param int[] $ids Candidate source ids. * @return int[] The subset of $ids that exist. */ public function existingIds( array $ids ): array { global $wpdb; $ids = array_values( array_unique( array_map( 'intval', $ids ) ) ); if ( empty( $ids ) ) { return array(); } $table = self::table(); $placeholders = implode( ', ', array_fill( 0, count( $ids ), '%d' ) ); $found = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$table} WHERE id IN ({$placeholders})", $ids ) ); return is_array( $found ) ? array_map( 'intval', $found ) : array(); } /** * Every Source for one exact scope. * * @param string $scope_type 'store'|'category'|'blueprint'|'product'. * @param int $scope_id Scope target id (0 for 'store'). * @return array> */ public function listByScope( string $scope_type, int $scope_id ): array { return $this->list( array( 'scopeType' => $scope_type, 'scopeId' => $scope_id, ), self::MAX_LIST_LIMIT ); } /** * Create a new Source. * * @param array $data { * @type string $name Required. * @type string $kind 'url'|'product_url_field'. * @type string $url For kind='url'. * @type string $urlField FieldRef, for kind='product_url_field'. * @type string $scopeType 'store'|'category'|'blueprint'|'product'. * @type int $scopeId Default 0. * @type int $staleAfterDays Default 7. * @type int $createdBy Default current user. * } * @return int New Source id (0 on failure). */ public function create( array $data ): int { global $wpdb; $table = self::table(); $now = current_time( 'mysql', true ); $user = isset( $data['createdBy'] ) ? (int) $data['createdBy'] : (int) ( function_exists( 'get_current_user_id' ) ? get_current_user_id() : 0 ); $row = array( 'name' => (string) ( $data['name'] ?? '' ), 'kind' => (string) ( $data['kind'] ?? 'url' ), 'url' => (string) ( $data['url'] ?? '' ), 'url_field' => (string) ( $data['urlField'] ?? '' ), 'scope_type' => (string) ( $data['scopeType'] ?? 'store' ), 'scope_id' => (int) ( $data['scopeId'] ?? 0 ), 'enabled' => 1, 'status' => 'pending', 'content_type' => '', 'extracted' => null, 'content_hash' => '', 'content_version' => 0, 'http_status' => 0, 'error_code' => '', 'error_message' => '', 'final_url' => '', 'bytes' => 0, 'last_checked_at' => null, 'stale_after_days' => (int) ( $data['staleAfterDays'] ?? 7 ), 'version' => self::newVersion(), 'created_by' => $user, 'created_at' => $now, 'updated_at' => $now, ); $result = $wpdb->insert( $table, $row, array( '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%s', '%s', ) ); return false !== $result ? (int) $wpdb->insert_id : 0; } /** * Version-checked update of the editable fields (name, enabled, scope, * staleAfterDays). * * One conditional `UPDATE ... WHERE id = %d AND version = %d` using a * freshly computed microsecond-epoch version as the new literal value * (never a SQL-level increment — see {@see MicrosecondVersion}). * * @param int $id Source id. * @param array $data Any of: name, enabled (bool), scopeType, scopeId, staleAfterDays. * @param int $expected_version The version the caller last read. * @return array{ok: bool, version: int, current: array|null} */ public function update( int $id, array $data, int $expected_version ): array { global $wpdb; $table = self::table(); $new_version = self::newVersion(); $set = array( 'updated_at' => current_time( 'mysql', true ), 'version' => $new_version ); $set_format = array( '%s', '%d' ); if ( array_key_exists( 'name', $data ) ) { $set['name'] = (string) $data['name']; $set_format[] = '%s'; } if ( array_key_exists( 'enabled', $data ) ) { $set['enabled'] = $data['enabled'] ? 1 : 0; $set_format[] = '%d'; } if ( array_key_exists( 'scopeType', $data ) ) { $set['scope_type'] = (string) $data['scopeType']; $set_format[] = '%s'; } if ( array_key_exists( 'scopeId', $data ) ) { $set['scope_id'] = (int) $data['scopeId']; $set_format[] = '%d'; } if ( array_key_exists( 'staleAfterDays', $data ) ) { $set['stale_after_days'] = (int) $data['staleAfterDays']; $set_format[] = '%d'; } $affected = $wpdb->update( $table, $set, array( 'id' => $id, 'version' => $expected_version ), $set_format, array( '%d', '%d' ) ); $current = $this->get( $id ); if ( false !== $affected && (int) $affected >= 1 ) { return array( 'ok' => true, 'version' => $new_version, 'current' => $current ); } return array( 'ok' => false, 'version' => null !== $current ? (int) $current['version'] : $expected_version, 'current' => $current, ); } /** * Record the result of fetching/extracting this Source's URL. * * Not version-checked against a caller-supplied expectation — a fetch * is a system-driven result, not a user edit a concurrent editor could * conflict with — but it still writes a fresh `version` so an editor * mid-PUT with a stale version is correctly refused, and still bumps * `content_version` ONLY when `content_hash` actually changed, so an * unchanged re-fetch of an identical page does not invalidate every * product-side cache keyed on the old content version. * * @param int $id Source id. * @param array $fetch { * @type string $status SourceStatus. * @type string $statusMessage Default ''. * @type string $contentType Default ''. * @type array|null $extracted Default null. * @type string $contentHash Default ''. * @type int $httpStatus Default 0. * @type string $errorCode Default ''. * @type string $errorMessage Default ''. * @type string $finalUrl Default ''. * @type int $bytes Default 0. * } * @return array|null The updated row, or null when the Source no longer exists. */ public function recordFetch( int $id, array $fetch ): ?array { global $wpdb; $existing = $this->get( $id ); if ( null === $existing ) { return null; } $table = self::table(); $now = current_time( 'mysql', true ); $new_hash = (string) ( $fetch['contentHash'] ?? '' ); $content_version = $existing['contentVersion']; if ( $new_hash !== $existing['contentHash'] ) { $content_version++; } $wpdb->update( $table, array( 'status' => (string) ( $fetch['status'] ?? 'error' ), 'content_type' => (string) ( $fetch['contentType'] ?? '' ), 'extracted' => isset( $fetch['extracted'] ) && is_array( $fetch['extracted'] ) ? wp_json_encode( $fetch['extracted'] ) : null, 'content_hash' => $new_hash, 'content_version' => $content_version, 'http_status' => (int) ( $fetch['httpStatus'] ?? 0 ), 'error_code' => (string) ( $fetch['errorCode'] ?? '' ), 'error_message' => (string) ( $fetch['errorMessage'] ?? '' ), 'final_url' => (string) ( $fetch['finalUrl'] ?? '' ), 'bytes' => (int) ( $fetch['bytes'] ?? 0 ), 'last_checked_at' => $now, 'version' => self::newVersion(), 'updated_at' => $now, ), array( 'id' => $id ), array( '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%d', '%s' ), array( '%d' ) ); return $this->get( $id ); } /** * Delete a Source by id. * * Does not cascade to {@see SourceCacheStore} rows or Blueprint * references — the REST delete-impact flow owns that sequencing. * * @param int $id Source id. * @return bool */ public function delete( int $id ): bool { global $wpdb; $table = self::table(); $result = $wpdb->delete( $table, array( 'id' => $id ), array( '%d' ) ); return false !== $result && (int) $result >= 1; } /** * Build WHERE clauses for list(). * * @param array $filters Read filters. * @return array */ private function buildWhere( array $filters ): array { global $wpdb; $where = array(); if ( isset( $filters['scopeType'] ) && '' !== $filters['scopeType'] ) { $where[] = $wpdb->prepare( 'scope_type = %s', (string) $filters['scopeType'] ); } if ( isset( $filters['scopeId'] ) ) { $where[] = $wpdb->prepare( 'scope_id = %d', (int) $filters['scopeId'] ); } if ( isset( $filters['kind'] ) && '' !== $filters['kind'] ) { $where[] = $wpdb->prepare( 'kind = %s', (string) $filters['kind'] ); } if ( isset( $filters['status'] ) && '' !== $filters['status'] ) { $where[] = $wpdb->prepare( 'status = %s', (string) $filters['status'] ); } if ( array_key_exists( 'enabled', $filters ) ) { $where[] = $wpdb->prepare( 'enabled = %d', $filters['enabled'] ? 1 : 0 ); } return $where; } /** * Map a raw database row to the canonical camelCase response shape. * * @param array $row Database row. * @return array */ private function mapRow( array $row ): array { $extracted = null !== ( $row['extracted'] ?? null ) ? json_decode( (string) $row['extracted'], true ) : null; return array( 'id' => (int) ( $row['id'] ?? 0 ), 'name' => (string) ( $row['name'] ?? '' ), 'kind' => (string) ( $row['kind'] ?? 'url' ), 'url' => (string) ( $row['url'] ?? '' ), 'urlField' => (string) ( $row['url_field'] ?? '' ), 'scopeType' => (string) ( $row['scope_type'] ?? 'store' ), 'scopeId' => (int) ( $row['scope_id'] ?? 0 ), 'enabled' => (bool) ( (int) ( $row['enabled'] ?? 1 ) ), 'status' => (string) ( $row['status'] ?? 'pending' ), 'contentType' => (string) ( $row['content_type'] ?? '' ), 'extracted' => is_array( $extracted ) ? $extracted : null, 'contentHash' => (string) ( $row['content_hash'] ?? '' ), 'contentVersion' => (int) ( $row['content_version'] ?? 0 ), 'httpStatus' => (int) ( $row['http_status'] ?? 0 ), 'errorCode' => (string) ( $row['error_code'] ?? '' ), 'errorMessage' => (string) ( $row['error_message'] ?? '' ), 'finalUrl' => (string) ( $row['final_url'] ?? '' ), 'bytes' => (int) ( $row['bytes'] ?? 0 ), 'lastCheckedAt' => null !== ( $row['last_checked_at'] ?? null ) ? (string) $row['last_checked_at'] : null, 'staleAfterDays' => (int) ( $row['stale_after_days'] ?? 7 ), 'version' => (int) ( $row['version'] ?? 0 ), 'createdBy' => (int) ( $row['created_by'] ?? 0 ), 'createdAt' => (string) ( $row['created_at'] ?? '' ), 'updatedAt' => (string) ( $row['updated_at'] ?? '' ), ); } }