Modelli e Relazioni
I modelli Eloquent rappresentano il cuore dell'applicazione Tidiko AI, gestendo le relazioni tra le entitΓ principali e fornendo un'interfaccia elegante per l'accesso ai dati.
π’ Company (Azienda)β
Il modello Company rappresenta le aziende che utilizzano la piattaforma e gestisce le loro informazioni, abbonamenti e limiti.
class Company extends Model
{
use HasFactory, Billable, Notifiable;
protected $table = 'companies';
protected $guarded = [];
public function stripeEmail(): string|null
{
return $this->email;
}
public function stripeName(): string|null
{
return $this->name;
}
public function subscriptionPlan()
{
$sparkPlan = $this->sparkPlan();
$freePlan = SubscriptionPlan::where('name', 'FREE')->first();
if (!$sparkPlan || !$sparkPlan->id) {
return $freePlan;
}
$subscriptionPlan = SubscriptionPlan::where('sandbox_monthly_price_id', $sparkPlan->id)
->orWhere('sandbox_yearly_price_id', $sparkPlan->id)
->orWhere('production_monthly_price_id', $sparkPlan->id)
->orWhere('production_yearly_price_id', $sparkPlan->id)
->first();
return $subscriptionPlan ?? $freePlan;
}
}
Relazioni Companyβ
// Relazioni principali
public function assistants()
{
return $this->hasMany(Assistant::class, 'company_id');
}
public function agents()
{
return $this->hasMany(Agent::class, 'company_id');
}
public function users()
{
return $this->hasMany(User::class, 'company_id');
}
public function files()
{
return $this->hasMany(File::class, 'company_id');
}
public function subscriptions()
{
return $this->hasMany(Subscription::class)->orderBy('created_at', 'desc');
}
Campi Principaliβ
| Campo | Tipo | Descrizione |
|---|---|---|
name | string | Nome dell'azienda |
email | string | Email principale |
address | string | Indirizzo |
city | string | CittΓ |
province | string | Provincia |
zipcode | string | CAP |
website | string | Sito web |
vatcode | string | Codice IVA |
phone | string | Telefono |
credit_balance | int | Saldo crediti disponibili |
subscription_plan_id | int | ID del piano di abbonamento attivo |
stripe_id | string | ID Stripe |
subscription_stripe_id | string | ID abbonamento Stripe |
pm_type | string | Tipo metodo di pagamento |
pm_last_four | string | Ultime 4 cifre carta |
billing_address | string | Indirizzo di fatturazione |
billing_city | string | CittΓ di fatturazione |
billing_country | string | Paese di fatturazione |
π€ Assistant (Assistente)β
Il modello Assistant rappresenta gli assistenti AI configurati dalle aziende.
class Assistant extends Model
{
use HasFactory;
protected $table = 'assistants';
protected $guarded = [];
public function files()
{
return $this->hasMany(File::class, 'vector_store_uuid', 'vector_store_uuid');
}
public function conversations()
{
return $this->hasMany(Conversation::class, 'assistant_id');
}
public function company()
{
return $this->belongsTo(Company::class);
}
}
Campi Principali Assistantβ
| Campo | Tipo | Descrizione |
|---|---|---|
assistant_uuid | string | UUID univoco dell'assistente |
vector_store_uuid | string | UUID del vector store associato |
name | string | Nome dell'assistente |
description | text | Descrizione dell'assistente |
instructions | text | Istruzioni per l'AI |
model | string | Modello AI utilizzato (es. gpt-4o) |
file_search | int | Abilita ricerca nei file |
code_interpreter | int | Abilita interprete di codice |
response_format | string | Formato di risposta |
temperature | string | Temperatura per la generazione |
topP | string | Top-p per la generazione |
domains | string | Domini autorizzati (comma-separated) |
notification | string | Configurazione notifiche |
embedding_options | string | Opzioni di embedding |
icon | string | Icona dell'assistente |
feed_key | string | Chiave per feed |
feed_enabled | int | Abilita feed |
feed_last_update | string | Ultimo aggiornamento feed |
π― Agent (Agente)β
Il modello Agent rappresenta agenti specializzati per e-commerce e integrazioni specifiche.
class Agent extends Model
{
use HasFactory;
protected $table = 'agents';
protected $guarded = [];
public function files()
{
return $this->hasMany(File::class, 'vector_store_uuid', 'vector_store_uuid');
}
public function company()
{
return $this->belongsTo(Company::class);
}
public function getVectorStoreUuid()
{
$company = $this->company;
return $company->vector_store_uuid;
}
public function conversations()
{
return $this->hasMany(Conversation::class, 'agent_id');
}
}
Campi Principali Agentβ
| Campo | Tipo | Descrizione |
|---|---|---|
agent_uuid | string | UUID univoco dell'agente |
name | string | Nome dell'agente |
company_name | string | Nome dell'azienda per l'agente |
company_description | text | Descrizione dell'azienda |
file_search | int | Abilita ricerca nei file |
shop_seach | int | Abilita ricerca nel negozio |
language | string | Lingua dell'agente |
woo_consumer_key | string | Chiave consumer WooCommerce |
woo_consumer_secret | string | Segreto consumer WooCommerce |
website_url | string | URL del sito web |
icon | string | Icona dell'agente |
embedding_options | string | Opzioni di embedding |
domains | string | Domini autorizzati |
feed_key | string | Chiave per feed |
notification | string | Configurazione notifiche |
enable_extra_instructions | int | Abilita istruzioni extra |
extra_instructions | string | Istruzioni extra |
vector_store_uuid | string | UUID del vector store |
π¬ Conversation (Conversazione)β
Il modello Conversation gestisce le conversazioni tra utenti e assistenti/agenti.
class Conversation extends Model
{
use HasFactory;
protected $table = 'conversations';
protected $guarded = [];
public function messages()
{
return $this->hasMany(Message::class);
}
public function agent()
{
return $this->belongsTo(Agent::class, 'agent_id');
}
public function assistant()
{
return $this->belongsTo(Assistant::class, 'assistant_id');
}
}
Campi Principali Conversationβ
| Campo | Tipo | Descrizione |
|---|---|---|
conversation_uuid | string | UUID univoco della conversazione |
assistant_id | int | ID dell'assistente (nullable) |
agent_id | int | ID dell'agente (nullable) |
started_at | datetime | Data/ora di inizio |
ended_at | datetime | Data/ora di fine |
tokens_used | int | Token totali utilizzati |
input_tokens_used | int | Token di input utilizzati |
output_tokens_used | int | Token di output utilizzati |
input_cost | decimal | Costo dei token di input |
output_cost | decimal | Costo dei token di output |
domain | string | Dominio di origine |
location | json | Informazioni di geolocalizzazione |
π Message (Messaggio)β
Il modello Message rappresenta i singoli messaggi all'interno delle conversazioni.
class Message extends Model
{
use HasFactory;
protected $table = 'messages';
protected $guarded = [];
public function conversation()
{
return $this->belongsTo(Conversation::class);
}
}
Campi Principali Messageβ
| Campo | Tipo | Descrizione |
|---|---|---|
message_uuid | string | UUID univoco del messaggio |
conversation_id | int | ID della conversazione |
sender | string | Mittente (user/assistant) |
message | text | Contenuto del messaggio |
tokens_used | int | Token utilizzati per questo messaggio |
model | string | Modello AI utilizzato |
cost | decimal | Costo del messaggio |
π File (File)β
Il modello File gestisce i file caricati per il training degli assistenti.
class File extends Model
{
use HasFactory;
protected $table = 'files';
protected $guarded = [];
public function company()
{
return $this->belongsTo(Company::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Campi Principali Fileβ
| Campo | Tipo | Descrizione |
|---|---|---|
file_uuid | string | UUID univoco del file |
vector_store_uuid | string | UUID del vector store |
name | string | Nome del file |
processed_name | string | Nome processato del file |
type | string | Tipo (file/link/api) |
content_type | string | Tipo di contenuto |
size | int | Dimensione in bytes |
processed | int | Se il file Γ¨ stato processato |
refresh_enabled | int | Se il refresh Γ¨ abilitato |
refresh_interval_days | int | Intervallo di refresh in giorni |
next_refresh_at | string | Prossimo refresh |
api_request_type | string | Tipo richiesta API |
jwt_token | string | Token JWT per API |
api_request_body | string | Body richiesta API |
uploaded_at | string | Data di upload |
π³ SubscriptionPlan (Piano di Abbonamento)β
Il modello SubscriptionPlan gestisce i piani di abbonamento disponibili.
class SubscriptionPlan extends Model
{
use HasFactory;
protected $table = 'subscription_plans';
protected $guarded = [];
protected $casts = [
'is_default' => 'boolean',
'is_custom' => 'boolean',
'features' => 'array',
'monthly_price' => 'decimal:2',
'yearly_price' => 'decimal:2',
];
public function toSparkPlan(): array
{
$sparkPlan = [
'name' => $this->name,
'short_description' => $this->short_description ?? "Abbonamento {$this->name} Tidiko",
'features' => $this->generateFeatures(),
'archived' => false,
];
$isTestMode = config('app.stripe_test', false);
$monthlyPriceId = $isTestMode ? $this->sandbox_monthly_price_id : $this->production_monthly_price_id;
$yearlyPriceId = $isTestMode ? $this->sandbox_yearly_price_id : $this->production_yearly_price_id;
if ($monthlyPriceId) {
$sparkPlan['monthly_id'] = $monthlyPriceId;
}
if ($yearlyPriceId) {
$sparkPlan['yearly_id'] = $yearlyPriceId;
}
return $sparkPlan;
}
}
Campi Principali SubscriptionPlanβ
| Campo | Tipo | Descrizione |
|---|---|---|
name | string | Nome del piano |
short_description | string | Descrizione breve |
max_assistants | int | Numero massimo di assistenti |
max_products | int | Numero massimo di prodotti |
max_messages | int | Numero massimo di messaggi mensili |
max_file_uploads | int | Numero massimo di upload file |
storage_limit_mb | int | Limite di storage in MB |
monthly_price | decimal | Prezzo mensile |
yearly_price | decimal | Prezzo annuale |
is_default | boolean | Piano predefinito |
is_custom | boolean | Piano personalizzato |
features | json | Array delle funzionalitΓ incluse |
sort_order | int | Ordine di visualizzazione |
sandbox_product_id | string | ID prodotto Stripe sandbox |
sandbox_monthly_price_id | string | ID prezzo mensile sandbox |
sandbox_yearly_price_id | string | ID prezzo annuale sandbox |
production_product_id | string | ID prodotto Stripe production |
production_monthly_price_id | string | ID prezzo mensile production |
production_yearly_price_id | string | ID prezzo annuale production |
π ApiKey (Chiave API)β
Il modello ApiKey gestisce le chiavi API per l'integrazione.
class ApiKey extends Model
{
use HasFactory;
protected $table = 'api_keys';
protected $guarded = [];
public function company()
{
return $this->belongsTo(Company::class, 'company_id');
}
}
Campi Principali ApiKeyβ
| Campo | Tipo | Descrizione |
|---|---|---|
name | string | Nome della chiave API |
key | string | Chiave API crittografata |
active | int | Se la chiave Γ¨ attiva |
note | string | Note sulla chiave |
allowed_host | string | Host autorizzato |
company_id | int | ID dell'azienda proprietaria |
π€ User (Utente)β
Il modello User gestisce gli utenti del sistema.
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
'role',
'company_id',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
public function company()
{
return $this->belongsTo(Company::class);
}
}
Campi Principali Userβ
| Campo | Tipo | Descrizione |
|---|---|---|
name | string | Nome dell'utente |
email | string | Email dell'utente |
password | string | Password hashata |
role | string | Ruolo (admin/editor) |
company_id | int | ID dell'azienda |
email_verified_at | datetime | Data verifica email |
remember_token | string | Token per remember me |
terms_acceptance_id | int | ID accettazione termini |
π Notification (Notifica)β
Il modello Notification gestisce le notifiche del sistema.
class Notification extends Model
{
use HasFactory;
protected $table = 'notifications';
protected $guarded = [];
public function company()
{
return $this->belongsTo(Company::class);
}
}
Campi Principali Notificationβ
| Campo | Tipo | Descrizione |
|---|---|---|
title | string | Titolo della notifica |
message | string | Messaggio della notifica |
type | string | Tipo di notifica |
status | string | Stato (read/unread) |
url | string | URL di destinazione |
company_id | int | ID dell'azienda |
π€ ModelAI (Modello AI)β
Il modello ModelAI gestisce i modelli AI disponibili e i loro costi.
class ModelAI extends Model
{
use HasFactory;
protected $table = 'models';
}
Campi Principali ModelAIβ
| Campo | Tipo | Descrizione |
|---|---|---|
name | string | Nome del modello AI |
tokens | int | Numero di token per calcolo |
input_cost_per_tokens | string | Costo per token di input |
output_cost_per_tokens | string | Costo per token di output |
commission_rate | string | Tasso di commissione |
cache_read_cost_per_token | string | Costo per token di cache read |
π PromptTemplate (Template Prompt)β
Il modello PromptTemplate gestisce i template di prompt per assistenti e agenti.
class PromptTemplate extends Model
{
use HasFactory;
protected $table = 'prompt_templates';
protected $guarded = [];
}
Campi Principali PromptTemplateβ
| Campo | Tipo | Descrizione |
|---|---|---|
name | string | Nome del template |
description | string | Descrizione del template |
prompt | string | Contenuto del prompt |
type | string | Tipo (instruction/type/personality) |
company_id | int | ID azienda (nullable) |
user_id | int | ID utente (nullable) |
π Relazioni tra Modelliβ
Diagramma delle Relazioniβ
Relazioni Principaliβ
- Company β Assistants/Agents: Una azienda puΓ² avere assistenti e agenti multipli
- Company β Users: Una azienda puΓ² avere utenti multipli
- Company β Files: Una azienda puΓ² avere file multipli
- Company β ApiKeys: Una azienda puΓ² avere chiavi API multiple
- Company β Notifications: Una azienda puΓ² avere notifiche multiple
- Assistant/Agent β Conversations: Ogni assistente/agente puΓ² avere conversazioni multiple
- Conversation β Messages: Ogni conversazione contiene messaggi multipli
- Assistant/Agent β Files: Gli assistenti/agenti possono condividere file tramite vector_store_uuid
- User β Files: Gli utenti possono caricare file
- User β PromptTemplates: Gli utenti possono creare template di prompt
- ModelAI β Messages: I modelli AI sono utilizzati nei messaggi
- PromptTemplate β Assistant: I template di prompt sono utilizzati dagli assistenti
π Eventi e Observerβ
Model Eventsβ
class AssistantObserver
{
public function created(Assistant $assistant)
{
// Creazione automatica del vector store
$vectorStoreUuid = NodeApiService::createCollection($assistant);
$assistant->update(['vector_store_uuid' => $vectorStoreUuid]);
}
public function deleting(Assistant $assistant)
{
// Pulizia del vector store
NodeApiService::deleteAssistant($assistant);
}
}
Scopes e Query Buildersβ
class Assistant extends Model
{
public function scopeForCompany($query, $companyId)
{
return $query->where('company_id', $companyId);
}
public function scopeActive($query)
{
return $query->whereNull('deleted_at');
}
public function scopeWithFiles($query)
{
return $query->with(['files' => function($q) {
$q->where('processed', true);
}]);
}
}
π Performance e Ottimizzazioniβ
Eager Loadingβ
public function index()
{
$assistants = Assistant::with(['company', 'files', 'conversations'])
->where('company_id', auth()->user()->company_id)
->get();
return view('assistants.index', compact('assistants'));
}
Caching delle Relazioniβ
public function subscriptionPlan()
{
return Cache::remember("company_{$this->id}_subscription_plan", 3600, function() {
$sparkPlan = $this->sparkPlan();
$freePlan = SubscriptionPlan::where('name', 'FREE')->first();
if (!$sparkPlan || !$sparkPlan->id) {
return $freePlan;
}
return SubscriptionPlan::where('sandbox_monthly_price_id', $sparkPlan->id)
->orWhere('production_monthly_price_id', $sparkPlan->id)
->first() ?? $freePlan;
});
}
I modelli Eloquent forniscono una base solida e flessibile per la gestione dei dati nell'applicazione Tidiko AI, con relazioni ben definite e ottimizzazioni per le performance.