prefix . 'aipt_blueprint_assignments'; } /** * Read a single assignment by id. * * @param int $id Assignment 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; } /** * Every assignment for one generator (store default + category + * taxonomy + legacy product/term rows), the store row always first — * fetched by its own query rather than left to an ORDER BY, so a * generator with 2000 or more category/product rows can never push the * store default (which every resolver tier needs) past the LIMIT below * — then lowest priority first within each target type. * * @param string $generator Generator key. * @return array> */ public function listForGenerator( string $generator ): array { global $wpdb; $table = self::table(); $store_row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE generator = %s AND target_type = 'store' LIMIT 1", $generator ), ARRAY_A ); $other_rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE generator = %s AND target_type != 'store' ORDER BY target_type ASC, priority ASC, id ASC LIMIT %d", $generator, self::MAX_LIST_LIMIT - 1 ), ARRAY_A ); $rows = is_array( $store_row ) ? array( $store_row ) : array(); if ( is_array( $other_rows ) ) { $rows = array_merge( $rows, $other_rows ); } return array_map( array( $this, 'mapRow' ), $rows ); } /** * Every assignment that points at the given Blueprint (any generator — * a Blueprint only ever matches its own generator in practice, but this * is a raw reference listing for delete-impact previews). * * @param int $blueprint_id Blueprint id. * @return array> */ public function listByBlueprint( int $blueprint_id ): array { global $wpdb; $table = self::table(); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE blueprint_id = %d LIMIT %d", $blueprint_id, self::MAX_LIST_LIMIT ), ARRAY_A ); return is_array( $rows ) ? array_map( array( $this, 'mapRow' ), $rows ) : array(); } /** * The current store-default row for one generator, or null when the * generator falls back to the built-in default template. * * @param string $generator Generator key. * @return array|null */ public function storeDefault( string $generator ): ?array { global $wpdb; $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE generator = %s AND target_type = 'store' AND taxonomy = '' AND target_id = 0 LIMIT 1", $generator ), ARRAY_A ); return is_array( $row ) ? $this->mapRow( $row ) : null; } /** * The current highest `priority` among a generator's assignments of one * target type — a convenience for the caller to suggest the next * priority when creating a new one. Returns 0 when none exist yet. * * @param string $generator Generator key. * @param string $target_type 'category'|'product'|'term'. * @return int */ public function maxPriority( string $generator, string $target_type ): int { global $wpdb; $table = self::table(); $value = $wpdb->get_var( $wpdb->prepare( "SELECT MAX(priority) FROM {$table} WHERE generator = %s AND target_type = %s", $generator, $target_type ) ); return null !== $value ? (int) $value : 0; } /** * Create a category/product/term assignment (never the store default — * use {@see setStoreDefault()} for that). * * A duplicate-key failure (an assignment already exists for this exact * target) is reported as `{ok:false, error:'conflict'}`, never a raw DB * error — the caller decides whether to offer "edit the existing * assignment instead". * * @param array $data { * @type string $generator Required. * @type int $blueprintId Required. * @type string $targetType 'category'|'product'|'term'. * @type string $taxonomy Default '' ('product_cat' for category, the real taxonomy for term). * @type int $targetId Required. * @type bool $includeChildren Default false. * @type int $priority Default 10. * @type int $createdBy Default current user. * } * @return array{ok: bool, id: int, error?: string} */ public function create( array $data ): array { 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( 'generator' => (string) ( $data['generator'] ?? '' ), 'blueprint_id' => (int) ( $data['blueprintId'] ?? 0 ), 'target_type' => (string) ( $data['targetType'] ?? '' ), 'taxonomy' => (string) ( $data['taxonomy'] ?? '' ), 'target_id' => (int) ( $data['targetId'] ?? 0 ), 'include_children' => ! empty( $data['includeChildren'] ) ? 1 : 0, 'priority' => (int) ( $data['priority'] ?? 10 ), 'version' => self::newVersion(), 'created_by' => $user, 'created_at' => $now, 'updated_at' => $now, ); $previous_suppress = $wpdb->suppress_errors( true ); $result = $wpdb->insert( $table, $row, array( '%s', '%d', '%s', '%s', '%d', '%d', '%d', '%d', '%d', '%s', '%s' ) ); $wpdb->suppress_errors( $previous_suppress ); if ( false !== $result ) { return array( 'ok' => true, 'id' => (int) $wpdb->insert_id ); } return array( 'ok' => false, 'id' => 0, 'error' => 'conflict' ); } /** * Version-checked update of a category/product/term assignment's * editable fields. * * @param int $id Assignment id. * @param array $data Any of: blueprintId, includeChildren (bool), priority. * @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( 'blueprintId', $data ) ) { $set['blueprint_id'] = (int) $data['blueprintId']; $set_format[] = '%d'; } if ( array_key_exists( 'includeChildren', $data ) ) { $set['include_children'] = $data['includeChildren'] ? 1 : 0; $set_format[] = '%d'; } if ( array_key_exists( 'priority', $data ) ) { $set['priority'] = (int) $data['priority']; $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, ); } /** * Race-safe set/clear of the per-generator store-default Blueprint. * * Algorithm: * - A row already exists: one conditional UPDATE (or DELETE when * $blueprint_id is null) bound to `version = $expected_version`. * Zero affected rows is reported as `{ok:false, error:'conflict'}` * with the current row attached, never silently treated as success. * - No row exists and $blueprint_id is null: nothing to do — "no * store default" IS the built-in-default state, which is simply the * absence of a row. * - No row exists and $blueprint_id is set: INSERT. A concurrent first * insert from another request racing us on the same UNIQUE * (generator, target_type='store', ...) tuple is caught via * `suppress_errors()` + a "Duplicate entry" check and reported as * the SAME conflict shape, never a raw DB error. * * @param string $generator Generator key. * @param int|null $blueprint_id New store-default Blueprint id, or null to fall back to the built-in default. * @param int|null $expected_version The version the caller last read; null only makes sense when no row exists yet. * @param int $user_id Acting user id. * @return array{ok: bool, current: array|null, error?: string} */ public function setStoreDefault( string $generator, ?int $blueprint_id, ?int $expected_version, int $user_id ): array { global $wpdb; $table = self::table(); $existing = $this->storeDefault( $generator ); if ( null !== $existing ) { $where = array( 'generator' => $generator, 'target_type' => 'store', 'version' => (int) $expected_version, ); $where_format = array( '%s', '%s', '%d' ); if ( null === $blueprint_id ) { $affected = $wpdb->delete( $table, $where, $where_format ); } else { $affected = $wpdb->update( $table, array( 'blueprint_id' => $blueprint_id, 'version' => self::newVersion(), 'updated_at' => current_time( 'mysql', true ), ), $where, array( '%d', '%d', '%s' ), $where_format ); } if ( false !== $affected && (int) $affected >= 1 ) { return array( 'ok' => true, 'current' => $this->storeDefault( $generator ) ); } return array( 'ok' => false, 'current' => $this->storeDefault( $generator ), 'error' => 'conflict' ); } if ( null === $blueprint_id ) { return array( 'ok' => true, 'current' => null ); } $now = current_time( 'mysql', true ); $previous_suppress = $wpdb->suppress_errors( true ); $result = $wpdb->insert( $table, array( 'generator' => $generator, 'blueprint_id' => $blueprint_id, 'target_type' => 'store', 'taxonomy' => '', 'target_id' => 0, 'include_children' => 0, 'priority' => 10, 'version' => self::newVersion(), 'created_by' => $user_id, 'created_at' => $now, 'updated_at' => $now, ), array( '%s', '%d', '%s', '%s', '%d', '%d', '%d', '%d', '%d', '%s', '%s' ) ); $wpdb->suppress_errors( $previous_suppress ); if ( false !== $result ) { return array( 'ok' => true, 'current' => $this->storeDefault( $generator ) ); } return array( 'ok' => false, 'current' => $this->storeDefault( $generator ), 'error' => 'conflict' ); } /** * Delete a single assignment by id. * * @param int $id Assignment 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; } /** * Delete every assignment that points at the given Blueprint. * * @param int $blueprint_id Blueprint id. * @return int Rows deleted. */ public function deleteByBlueprint( int $blueprint_id ): int { global $wpdb; $table = self::table(); $result = $wpdb->delete( $table, array( 'blueprint_id' => $blueprint_id ), array( '%d' ) ); return false !== $result ? (int) $result : 0; } /** * Delete every assignment (across every generator) pointing at one * category/product/term target — for a target that was itself deleted. * * @param string $target_type 'category'|'product'|'term'. * @param string $taxonomy '' for product, 'product_cat' for category, the real taxonomy for term. * @param int $target_id Target id. * @return int Rows deleted. */ public function deleteByTarget( string $target_type, string $taxonomy, int $target_id ): int { global $wpdb; $table = self::table(); $result = $wpdb->delete( $table, array( 'target_type' => $target_type, 'taxonomy' => $taxonomy, 'target_id' => $target_id ), array( '%s', '%s', '%d' ) ); return false !== $result ? (int) $result : 0; } /** * Map a raw database row to the canonical camelCase response shape. * * @param array $row Database row. * @return array */ private function mapRow( array $row ): array { return array( 'id' => (int) ( $row['id'] ?? 0 ), 'generator' => (string) ( $row['generator'] ?? '' ), 'blueprintId' => (int) ( $row['blueprint_id'] ?? 0 ), 'targetType' => (string) ( $row['target_type'] ?? '' ), 'taxonomy' => (string) ( $row['taxonomy'] ?? '' ), 'targetId' => (int) ( $row['target_id'] ?? 0 ), 'includeChildren' => (bool) ( (int) ( $row['include_children'] ?? 0 ) ), 'priority' => (int) ( $row['priority'] ?? 10 ), 'version' => (int) ( $row['version'] ?? 0 ), 'createdBy' => (int) ( $row['created_by'] ?? 0 ), 'createdAt' => (string) ( $row['created_at'] ?? '' ), 'updatedAt' => (string) ( $row['updated_at'] ?? '' ), ); } }