chore: remove dead code — 8 components, 5 libs, 4 API routes, 4 npm packages, 30+ scripts, dead CSS, dead exports
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 5s
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 5s
Removed unused components: - brainstorm-canvas, brainstorm-create-dialog, invite-dialog, manual-idea-dialog - note-inline-editor, profile-page-header, quota-paywall, label-management-dialog Removed dead lib files: - api-auth.ts, color-harmony-recommendation.ts, label-storage.ts, modern-color-options.ts - hooks/use-card-size-mode.ts Removed dead API routes: - ai/test-chat, ai/test-embeddings, ai/test-tags, admin/randomize-labels Removed unused npm packages: - cmdk, novel, tippy.js, react-force-graph-2d Cleaned dead CSS from globals.css: - acrylic-*, win11-shadow-*, muuri-grid/item, ai-glass, ai-tab-indicator, ai-send-btn, sidebar-view-toggle, memento-sidebar-depth Removed 29 orphan scripts and 3 root orphan files Cleaned dead exports from 8 lib files: - NOTE_TYPE_CONFIG, getPublishableKey, PROVIDER_DEFAULTS, useNotes/useNote/invalidateNote, etc.
This commit is contained in:
@@ -1,37 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const filePath = path.join(__dirname, '..', 'components', 'notes-tabs-view.tsx');
|
||||
let lines = fs.readFileSync(filePath, 'utf8').split('\r\n');
|
||||
|
||||
// Line 977 (index 976) closes the scrollable div
|
||||
// Line 978 (index 977) closes the left panel div
|
||||
// We need to:
|
||||
// 1. After the scrollable </div> (index 976), add )} to close {listOpen && (...
|
||||
// 2. Add expand button JSX
|
||||
// 3. Then close left panel div
|
||||
|
||||
const expandButton = [
|
||||
' )}',
|
||||
' {/* Expand button shown in collapsed state */}',
|
||||
' {!listOpen && (',
|
||||
' <div className="flex flex-col items-center pt-3">',
|
||||
' <Button',
|
||||
' variant="ghost"',
|
||||
' size="sm"',
|
||||
' className="h-7 w-7 p-0 text-muted-foreground/70 hover:bg-primary/8 hover:text-primary"',
|
||||
' onClick={() => setListOpen(true)}',
|
||||
' title="Afficher la liste"',
|
||||
' >',
|
||||
' <PanelLeftOpen className="h-3.5 w-3.5" />',
|
||||
' </Button>',
|
||||
' </div>',
|
||||
' )}',
|
||||
];
|
||||
|
||||
// Insert after index 976 (which is ' </div>' - the scrollable div close)
|
||||
// and remove the original ' </div>' at index 977 (left panel close)
|
||||
// then re-add left panel close
|
||||
lines.splice(977, 1, ...expandButton, ' </div>');
|
||||
|
||||
fs.writeFileSync(filePath, lines.join('\r\n'));
|
||||
console.log('Done, total lines:', lines.length);
|
||||
@@ -1,60 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const filePath = path.join(__dirname, '..', 'components', 'notes-tabs-view.tsx');
|
||||
let src = fs.readFileSync(filePath, 'utf8');
|
||||
|
||||
const insertCode = `
|
||||
// Resizable left panel
|
||||
const [listPanelWidth, setListPanelWidth] = useState(256)
|
||||
const isDraggingRef = useRef(false)
|
||||
|
||||
const handleResizeStart = (e) => {
|
||||
e.preventDefault()
|
||||
isDraggingRef.current = true
|
||||
const startX = e.clientX
|
||||
const startW = listPanelWidth
|
||||
const onMove = (ev) => {
|
||||
if (!isDraggingRef.current) return
|
||||
setListPanelWidth(Math.min(420, Math.max(180, startW + (ev.clientX - startX))))
|
||||
}
|
||||
const onUp = () => {
|
||||
isDraggingRef.current = false
|
||||
window.removeEventListener('mousemove', onMove)
|
||||
window.removeEventListener('mouseup', onUp)
|
||||
}
|
||||
window.addEventListener('mousemove', onMove)
|
||||
window.addEventListener('mouseup', onUp)
|
||||
}
|
||||
|
||||
`;
|
||||
|
||||
// Insert before the return statement
|
||||
const MARKER = ' return (\r\n <div\r\n className="flex min-h-0 flex-1 gap-0';
|
||||
const ALT_MARKER = ' return (\n <div\n className="flex min-h-0 flex-1 gap-0';
|
||||
|
||||
if (src.includes(MARKER) && !src.includes('listPanelWidth')) {
|
||||
src = src.replace(MARKER, insertCode + MARKER);
|
||||
console.log('Inserted using CRLF marker');
|
||||
} else if (src.includes(ALT_MARKER) && !src.includes('listPanelWidth')) {
|
||||
src = src.replace(ALT_MARKER, insertCode + ALT_MARKER);
|
||||
console.log('Inserted using LF marker');
|
||||
} else if (src.includes('listPanelWidth')) {
|
||||
console.log('State already exists, skipping insert');
|
||||
} else {
|
||||
console.error('Marker not found!');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Fix left panel width - CRLF version
|
||||
const OLD_CRLF = 'className="flex w-80 shrink-0 flex-col border-r border-border/60 bg-background">';
|
||||
const NEW = 'className="flex shrink-0 flex-col border-r border-border/60 bg-background" style={{ width: listPanelWidth }}>';
|
||||
if (src.includes(OLD_CRLF)) {
|
||||
src = src.replace(OLD_CRLF, NEW);
|
||||
console.log('Replaced panel width');
|
||||
} else {
|
||||
console.log('Panel width already updated or marker not found');
|
||||
}
|
||||
|
||||
fs.writeFileSync(filePath, src);
|
||||
console.log('Done!');
|
||||
@@ -1,292 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Merges missing i18n keys (admin fallback, brainstorm quota, landing page)
|
||||
* into locale files. Contextual translations — not word-for-word.
|
||||
*/
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const localesDir = path.join(__dirname, '../locales')
|
||||
|
||||
function deepMerge(target, source) {
|
||||
for (const key of Object.keys(source)) {
|
||||
const sv = source[key]
|
||||
if (sv && typeof sv === 'object' && !Array.isArray(sv)) {
|
||||
if (!target[key] || typeof target[key] !== 'object') target[key] = {}
|
||||
deepMerge(target[key], sv)
|
||||
} else {
|
||||
target[key] = sv
|
||||
}
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
function flatten(obj, prefix = '') {
|
||||
const result = {}
|
||||
for (const [k, v] of Object.entries(obj)) {
|
||||
const key = prefix ? `${prefix}.${k}` : k
|
||||
if (v && typeof v === 'object' && !Array.isArray(v)) Object.assign(result, flatten(v, key))
|
||||
else result[key] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
const adminAiFallback = {
|
||||
de: {
|
||||
fallbackSectionTitle: 'Ausweich-Anbieter (optional)',
|
||||
fallbackSectionDescription:
|
||||
'Wird bei Anbieterfehlern automatisch genutzt (429, 5xx). Ein erneuter Versuch innerhalb von 1,5 s.',
|
||||
fallbackProvider: 'Ausweich-Anbieter',
|
||||
fallbackModel: 'Ausweich-Modell',
|
||||
fallbackNone: 'Keiner (deaktiviert)',
|
||||
fallbackModelPlaceholder: 'z. B. gpt-4o-mini',
|
||||
},
|
||||
es: {
|
||||
fallbackSectionTitle: 'Proveedor de respaldo (opcional)',
|
||||
fallbackSectionDescription:
|
||||
'Se usa automáticamente ante errores del proveedor (429, 5xx). Un reintento en 1,5 s.',
|
||||
fallbackProvider: 'Proveedor de respaldo',
|
||||
fallbackModel: 'Modelo de respaldo',
|
||||
fallbackNone: 'Ninguno (desactivado)',
|
||||
fallbackModelPlaceholder: 'p. ej. gpt-4o-mini',
|
||||
},
|
||||
it: {
|
||||
fallbackSectionTitle: 'Provider di riserva (opzionale)',
|
||||
fallbackSectionDescription:
|
||||
'Usato automaticamente in caso di errori del provider (429, 5xx). Un solo nuovo tentativo entro 1,5 s.',
|
||||
fallbackProvider: 'Provider di riserva',
|
||||
fallbackModel: 'Modello di riserva',
|
||||
fallbackNone: 'Nessuno (disattivato)',
|
||||
fallbackModelPlaceholder: 'es. gpt-4o-mini',
|
||||
},
|
||||
pt: {
|
||||
fallbackSectionTitle: 'Provedor de contingência (opcional)',
|
||||
fallbackSectionDescription:
|
||||
'Usado automaticamente em erros do provedor (429, 5xx). Uma nova tentativa em 1,5 s.',
|
||||
fallbackProvider: 'Provedor de contingência',
|
||||
fallbackModel: 'Modelo de contingência',
|
||||
fallbackNone: 'Nenhum (desativado)',
|
||||
fallbackModelPlaceholder: 'ex.: gpt-4o-mini',
|
||||
},
|
||||
nl: {
|
||||
fallbackSectionTitle: 'Fallback-provider (optioneel)',
|
||||
fallbackSectionDescription:
|
||||
'Wordt automatisch gebruikt bij providerfouten (429, 5xx). Eén nieuwe poging binnen 1,5 s.',
|
||||
fallbackProvider: 'Fallback-provider',
|
||||
fallbackModel: 'Fallback-model',
|
||||
fallbackNone: 'Geen (uitgeschakeld)',
|
||||
fallbackModelPlaceholder: 'bijv. gpt-4o-mini',
|
||||
},
|
||||
pl: {
|
||||
fallbackSectionTitle: 'Zapasowy dostawca (opcjonalnie)',
|
||||
fallbackSectionDescription:
|
||||
'Używany automatycznie przy błędach dostawcy (429, 5xx). Jedna ponowna próba w 1,5 s.',
|
||||
fallbackProvider: 'Zapasowy dostawca',
|
||||
fallbackModel: 'Zapasowy model',
|
||||
fallbackNone: 'Brak (wyłączone)',
|
||||
fallbackModelPlaceholder: 'np. gpt-4o-mini',
|
||||
},
|
||||
ru: {
|
||||
fallbackSectionTitle: 'Резервный провайдер (необязательно)',
|
||||
fallbackSectionDescription:
|
||||
'Используется автоматически при ошибках провайдера (429, 5xx). Одна повторная попытка за 1,5 с.',
|
||||
fallbackProvider: 'Резервный провайдер',
|
||||
fallbackModel: 'Резервная модель',
|
||||
fallbackNone: 'Нет (отключено)',
|
||||
fallbackModelPlaceholder: 'напр. gpt-4o-mini',
|
||||
},
|
||||
ar: {
|
||||
fallbackSectionTitle: 'مزود احتياطي (اختياري)',
|
||||
fallbackSectionDescription:
|
||||
'يُستخدم تلقائياً عند أخطاء المزود (429، 5xx). محاولة واحدة خلال 1,5 ثانية.',
|
||||
fallbackProvider: 'مزود احتياطي',
|
||||
fallbackModel: 'نموذج احتياطي',
|
||||
fallbackNone: 'لا شيء (معطّل)',
|
||||
fallbackModelPlaceholder: 'مثال: gpt-4o-mini',
|
||||
},
|
||||
fa: {
|
||||
fallbackSectionTitle: 'ارائهدهنده پشتیبان (اختیاری)',
|
||||
fallbackSectionDescription:
|
||||
'در صورت خطای ارائهدهنده (429، 5xx) بهصورت خودکار استفاده میشود. یک تلاش مجدد در ۱,۵ ثانیه.',
|
||||
fallbackProvider: 'ارائهدهنده پشتیبان',
|
||||
fallbackModel: 'مدل پشتیبان',
|
||||
fallbackNone: 'هیچ (غیرفعال)',
|
||||
fallbackModelPlaceholder: 'مثلاً gpt-4o-mini',
|
||||
},
|
||||
hi: {
|
||||
fallbackSectionTitle: 'फ़ॉलबैक प्रदाता (वैकल्पिक)',
|
||||
fallbackSectionDescription:
|
||||
'प्रदाता त्रुटियों (429, 5xx) पर स्वतः उपयोग। 1.5 सेकंड में एक पुनः प्रयास।',
|
||||
fallbackProvider: 'फ़ॉलबैक प्रदाता',
|
||||
fallbackModel: 'फ़ॉलबैक मॉडल',
|
||||
fallbackNone: 'कोई नहीं (अक्षम)',
|
||||
fallbackModelPlaceholder: 'उदा. gpt-4o-mini',
|
||||
},
|
||||
ja: {
|
||||
fallbackSectionTitle: 'フォールバックプロバイダー(任意)',
|
||||
fallbackSectionDescription:
|
||||
'プロバイダーエラー時(429、5xx)に自動使用。1.5秒以内に1回再試行。',
|
||||
fallbackProvider: 'フォールバックプロバイダー',
|
||||
fallbackModel: 'フォールバックモデル',
|
||||
fallbackNone: 'なし(無効)',
|
||||
fallbackModelPlaceholder: '例: gpt-4o-mini',
|
||||
},
|
||||
ko: {
|
||||
fallbackSectionTitle: '대체 제공업체(선택)',
|
||||
fallbackSectionDescription:
|
||||
'제공업체 오류(429, 5xx) 시 자동 사용. 1.5초 이내 1회 재시도.',
|
||||
fallbackProvider: '대체 제공업체',
|
||||
fallbackModel: '대체 모델',
|
||||
fallbackNone: '없음(비활성화)',
|
||||
fallbackModelPlaceholder: '예: gpt-4o-mini',
|
||||
},
|
||||
zh: {
|
||||
fallbackSectionTitle: '备用提供商(可选)',
|
||||
fallbackSectionDescription: '提供商出错时(429、5xx)自动启用。1.5 秒内重试一次。',
|
||||
fallbackProvider: '备用提供商',
|
||||
fallbackModel: '备用模型',
|
||||
fallbackNone: '无(已禁用)',
|
||||
fallbackModelPlaceholder: '例如 gpt-4o-mini',
|
||||
},
|
||||
}
|
||||
|
||||
const brainstormQuota = {
|
||||
de: {
|
||||
quotaGuest:
|
||||
'Der Gastgeber der Sitzung hat sein KI-Kontingent aufgebraucht. Bitte ihn, seinen Tarif zu erweitern.',
|
||||
quotaHost:
|
||||
'Sie haben Ihr KI-Kontingent für dieses Brainstorming erreicht. Wechseln Sie den Tarif, um fortzufahren.',
|
||||
},
|
||||
es: {
|
||||
quotaGuest:
|
||||
'El anfitrión de la sesión ha alcanzado su límite de IA. Pídele que mejore su plan.',
|
||||
quotaHost:
|
||||
'Has alcanzado tu límite de IA para este brainstorm. Mejora tu plan para continuar.',
|
||||
},
|
||||
it: {
|
||||
quotaGuest:
|
||||
"L'host della sessione ha raggiunto il limite IA. Chiedigli di aggiornare il piano.",
|
||||
quotaHost:
|
||||
'Hai raggiunto il limite IA per questo brainstorm. Passa a un piano superiore per continuare.',
|
||||
},
|
||||
pt: {
|
||||
quotaGuest:
|
||||
'O anfitrião da sessão atingiu o limite de IA. Peça-lhe para atualizar o plano.',
|
||||
quotaHost:
|
||||
'Atingiu o limite de IA deste brainstorm. Atualize o plano para continuar.',
|
||||
},
|
||||
nl: {
|
||||
quotaGuest:
|
||||
'De sessiehost heeft zijn AI-limiet bereikt. Vraag om een upgrade van het abonnement.',
|
||||
quotaHost:
|
||||
'Je hebt je AI-limiet voor deze brainstorm bereikt. Upgrade je abonnement om door te gaan.',
|
||||
},
|
||||
pl: {
|
||||
quotaGuest:
|
||||
'Gospodarz sesji wyczerpał limit AI. Poproś go o ulepszenie planu.',
|
||||
quotaHost:
|
||||
'Osiągnąłeś limit AI dla tego brainstormu. Ulepsz plan, aby kontynuować.',
|
||||
},
|
||||
ru: {
|
||||
quotaGuest:
|
||||
'Организатор сессии исчерпал лимит ИИ. Попросите его обновить тариф.',
|
||||
quotaHost:
|
||||
'Вы исчерпали лимит ИИ для этого мозгового штурма. Обновите тариф, чтобы продолжить.',
|
||||
},
|
||||
ar: {
|
||||
quotaGuest:
|
||||
'استنفد مضيف الجلسة حدّ الذكاء الاصطناعي. اطلب منه ترقية خطته.',
|
||||
quotaHost: 'لقد وصلت إلى حدّ الذكاء الاصطناعي لهذه الجلسة. رقِّ خطتك للمتابعة.',
|
||||
},
|
||||
fa: {
|
||||
quotaGuest:
|
||||
'میزبان جلسه به سقف هوش مصنوعی رسیده. از او بخواهید طرحش را ارتقا دهد.',
|
||||
quotaHost:
|
||||
'به سقف هوش مصنوعی این طوفان فکری رسیدید. برای ادامه، طرح خود را ارتقا دهید.',
|
||||
},
|
||||
hi: {
|
||||
quotaGuest:
|
||||
'सत्र के होस्ट की AI सीमा समाप्त हो गई है। उनसे अपना प्लान अपग्रेड करने को कहें।',
|
||||
quotaHost:
|
||||
'इस ब्रेनस्टॉर्म के लिए आपकी AI सीमा समाप्त हो गई है। जारी रखने के लिए प्लान अपग्रेड करें।',
|
||||
},
|
||||
ja: {
|
||||
quotaGuest:
|
||||
'セッションのホストがAI利用上限に達しました。プランのアップグレードを依頼してください。',
|
||||
quotaHost:
|
||||
'このブレインストームのAI上限に達しました。続けるにはプランをアップグレードしてください。',
|
||||
},
|
||||
ko: {
|
||||
quotaGuest: '세션 호스트의 AI 한도에 도달했습니다. 플랜 업그레이드를 요청하세요.',
|
||||
quotaHost:
|
||||
'이 브레인스토밍의 AI 한도에 도달했습니다. 계속하려면 플랜을 업그레이드하세요.',
|
||||
},
|
||||
zh: {
|
||||
quotaGuest: '会话主持人已达到 AI 额度上限。请让对方升级套餐。',
|
||||
quotaHost: '您已达到此头脑风暴的 AI 额度上限。升级套餐以继续。',
|
||||
},
|
||||
}
|
||||
|
||||
// Landing blocks — load from generated JSON (keeps this script maintainable)
|
||||
const landingPatchesPath = path.join(__dirname, 'i18n-landing-patches.json')
|
||||
if (!fs.existsSync(landingPatchesPath)) {
|
||||
console.error('Missing i18n-landing-patches.json — run generate-landing-patches first')
|
||||
process.exit(1)
|
||||
}
|
||||
const landingPatches = JSON.parse(fs.readFileSync(landingPatchesPath, 'utf8'))
|
||||
|
||||
const TARGET_LANGS = [
|
||||
'ar',
|
||||
'de',
|
||||
'es',
|
||||
'fa',
|
||||
'hi',
|
||||
'it',
|
||||
'ja',
|
||||
'ko',
|
||||
'nl',
|
||||
'pl',
|
||||
'pt',
|
||||
'ru',
|
||||
'zh',
|
||||
]
|
||||
|
||||
for (const lang of TARGET_LANGS) {
|
||||
const filePath = path.join(localesDir, `${lang}.json`)
|
||||
const data = JSON.parse(fs.readFileSync(filePath, 'utf8'))
|
||||
|
||||
if (adminAiFallback[lang]) {
|
||||
if (!data.admin) data.admin = {}
|
||||
if (!data.admin.ai) data.admin.ai = {}
|
||||
Object.assign(data.admin.ai, adminAiFallback[lang])
|
||||
}
|
||||
|
||||
if (brainstormQuota[lang]) {
|
||||
if (!data.brainstorm) data.brainstorm = {}
|
||||
Object.assign(data.brainstorm, brainstormQuota[lang])
|
||||
}
|
||||
|
||||
if (landingPatches[lang]) {
|
||||
if (!data.landing) data.landing = {}
|
||||
deepMerge(data.landing, landingPatches[lang])
|
||||
}
|
||||
|
||||
fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n', 'utf8')
|
||||
console.log(`✓ ${lang}.json updated`)
|
||||
}
|
||||
|
||||
// Verify
|
||||
const en = flatten(JSON.parse(fs.readFileSync(path.join(localesDir, 'en.json'), 'utf8')))
|
||||
const enKeys = Object.keys(en)
|
||||
let ok = true
|
||||
for (const lang of TARGET_LANGS) {
|
||||
const loc = flatten(JSON.parse(fs.readFileSync(path.join(localesDir, `${lang}.json`), 'utf8')))
|
||||
const missing = enKeys.filter((k) => !(k in loc))
|
||||
if (missing.length) {
|
||||
console.error(`✗ ${lang}: still ${missing.length} missing keys`)
|
||||
ok = false
|
||||
}
|
||||
}
|
||||
console.log(ok ? '\nAll locales complete.' : '\nSome keys still missing.')
|
||||
@@ -1,22 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
async function main() {
|
||||
const configs = await prisma.systemConfig.findMany()
|
||||
console.log('--- System Config ---')
|
||||
configs.forEach(c => {
|
||||
if (c.key.startsWith('AI_') || c.key.startsWith('OLLAMA_')) {
|
||||
console.log(`${c.key}: ${c.value}`)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => {
|
||||
console.error(e)
|
||||
process.exit(1)
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect()
|
||||
})
|
||||
@@ -1,76 +0,0 @@
|
||||
// Import directly from the generated client
|
||||
const { PrismaClient } = require('./node_modules/@prisma/client')
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
async function checkLabels() {
|
||||
try {
|
||||
console.log('\n=== TOUS LES LABELS DANS LA TABLE Label ===')
|
||||
const allLabels = await prisma.label.findMany({
|
||||
select: { id: true, name: true, userId: true }
|
||||
})
|
||||
console.log(`Total: ${allLabels.length} labels`)
|
||||
allLabels.forEach(l => {
|
||||
console.log(` - ${l.name} (userId: ${l.userId}, id: ${l.id})`)
|
||||
})
|
||||
|
||||
console.log('\n=== TOUS LES LABELS DANS LES NOTES (Note.labels) ===')
|
||||
const allNotes = await prisma.note.findMany({
|
||||
select: { id: true, labels: true, userId: true }
|
||||
})
|
||||
|
||||
const labelsInNotes = new Set()
|
||||
allNotes.forEach(note => {
|
||||
if (note.labels) {
|
||||
try {
|
||||
const parsed = Array.isArray(note.labels) ? note.labels : []
|
||||
if (Array.isArray(parsed)) {
|
||||
parsed.forEach(l => labelsInNotes.add(l))
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`Total unique: ${labelsInNotes.size} labels`)
|
||||
labelsInNotes.forEach(l => console.log(` - ${l}`))
|
||||
|
||||
console.log('\n=== LABELS ORPHELINS (dans Label table MAIS PAS dans les notes) ===')
|
||||
const orphanLabels = []
|
||||
allLabels.forEach(label => {
|
||||
let found = false
|
||||
labelsInNotes.forEach(noteLabel => {
|
||||
if (noteLabel.toLowerCase() === label.name.toLowerCase()) {
|
||||
found = true
|
||||
}
|
||||
})
|
||||
if (!found) {
|
||||
orphanLabels.push(label)
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`Total orphans: ${orphanLabels.length}`)
|
||||
orphanLabels.forEach(l => {
|
||||
console.log(` - ${l.name} (userId: ${l.userId})`)
|
||||
})
|
||||
|
||||
console.log('\n=== LABELS MANQUANTS (dans notes MAIS PAS dans Label table) ===')
|
||||
const missingLabels = []
|
||||
const existingLabelNames = new Set()
|
||||
allLabels.forEach(l => existingLabelNames.add(l.name.toLowerCase()))
|
||||
|
||||
labelsInNotes.forEach(noteLabel => {
|
||||
if (!existingLabelNames.has(noteLabel.toLowerCase())) {
|
||||
missingLabels.push(noteLabel)
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`Total missing: ${missingLabels.length}`)
|
||||
missingLabels.forEach(l => console.log(` - ${l}`))
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error:', error)
|
||||
} finally {
|
||||
await prisma.$disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
checkLabels()
|
||||
@@ -1,35 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
async function main() {
|
||||
const users = await prisma.user.findMany({
|
||||
include: {
|
||||
aiSettings: true,
|
||||
notes: {
|
||||
take: 5,
|
||||
orderBy: { updatedAt: 'desc' }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
console.log('Total Users:', users.length)
|
||||
|
||||
for (const user of users) {
|
||||
console.log(`User: ${user.email} (${user.id})`)
|
||||
console.log(` AI Settings:`, user.aiSettings)
|
||||
console.log(` Recent 5 Notes:`)
|
||||
for (const note of user.notes) {
|
||||
console.log(` ID: ${note.id}, Title: ${note.title}, Updated: ${note.updatedAt}, Dismissed: ${JSON.stringify(note)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => {
|
||||
console.error(e)
|
||||
process.exit(1)
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect()
|
||||
})
|
||||
@@ -1,25 +0,0 @@
|
||||
|
||||
import { prisma } from '../lib/prisma'
|
||||
|
||||
async function main() {
|
||||
console.log('🔍 Checking users in database...')
|
||||
console.log('Database URL used:', process.env.DATABASE_URL || "file:./dev.db")
|
||||
|
||||
const users = await prisma.user.findMany()
|
||||
|
||||
if (users.length === 0) {
|
||||
console.log('❌ No users found in database!')
|
||||
} else {
|
||||
console.log(`✅ Found ${users.length} users:`)
|
||||
console.table(users.map(u => ({
|
||||
email: u.email,
|
||||
role: u.role,
|
||||
id: u.id,
|
||||
hasPassword: !!u.password
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => console.error(e))
|
||||
.finally(async () => await prisma.$disconnect())
|
||||
@@ -1,41 +0,0 @@
|
||||
|
||||
import { siteConfig } from '../config/site'
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
async function main() {
|
||||
console.log('🕵️♀️ Comparing Databases...')
|
||||
|
||||
// 1. Check Root DB
|
||||
console.log('--- ROOT DB (./dev.db) ---')
|
||||
const prismaRoot = new PrismaClient({
|
||||
datasources: { db: { url: 'file:./dev.db' } }
|
||||
})
|
||||
try {
|
||||
const countRoot = await prismaRoot.note.count()
|
||||
console.log(`📦 Note Count: ${countRoot}`)
|
||||
const usersRoot = await prismaRoot.user.count()
|
||||
console.log(`👥 User Count: ${usersRoot}`)
|
||||
} catch (e) {
|
||||
console.log('❌ Failed to connect to Root DB', e)
|
||||
} finally {
|
||||
await prismaRoot.$disconnect()
|
||||
}
|
||||
|
||||
// 2. Check Prisma Folder DB
|
||||
console.log('\n--- PRISMA DB (./prisma/dev.db) ---')
|
||||
const prismaPrisma = new PrismaClient({
|
||||
datasources: { db: { url: 'file:./prisma/dev.db' } }
|
||||
})
|
||||
try {
|
||||
const countPrisma = await prismaPrisma.note.count()
|
||||
console.log(`📦 Note Count: ${countPrisma}`)
|
||||
const usersPrisma = await prismaPrisma.user.count()
|
||||
console.log(`👥 User Count: ${usersPrisma}`)
|
||||
} catch (e) {
|
||||
console.log('❌ Failed to connect to Prisma DB', e)
|
||||
} finally {
|
||||
await prismaPrisma.$disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error)
|
||||
@@ -1,31 +0,0 @@
|
||||
import { PrismaClient } from '../prisma/client-generated'
|
||||
import bcrypt from 'bcryptjs'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
async function main() {
|
||||
const email = 'test@example.com'
|
||||
const password = 'password123'
|
||||
const hashedPassword = await bcrypt.hash(password, 10)
|
||||
|
||||
const user = await prisma.user.upsert({
|
||||
where: { email },
|
||||
update: { password: hashedPassword },
|
||||
create: {
|
||||
email,
|
||||
name: 'Test User',
|
||||
password: hashedPassword,
|
||||
aiSettings: {
|
||||
create: {
|
||||
showRecentNotes: true // Ensure this is true!
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`User created/updated: ${user.email}`)
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => console.error(e))
|
||||
.finally(async () => await prisma.$disconnect())
|
||||
@@ -1,41 +0,0 @@
|
||||
import prisma from '../lib/prisma'
|
||||
|
||||
async function debugConfig() {
|
||||
console.log('=== System Configuration Debug ===\n')
|
||||
|
||||
const configs = await prisma.systemConfig.findMany()
|
||||
|
||||
console.log(`Total configs in DB: ${configs.length}\n`)
|
||||
|
||||
// Group by category
|
||||
const aiConfigs = configs.filter(c => c.key.startsWith('AI_'))
|
||||
const ollamaConfigs = configs.filter(c => c.key.includes('OLLAMA'))
|
||||
const openaiConfigs = configs.filter(c => c.key.includes('OPENAI'))
|
||||
|
||||
console.log('=== AI Provider Configs ===')
|
||||
aiConfigs.forEach(c => {
|
||||
console.log(`${c.key}: "${c.value}"`)
|
||||
})
|
||||
|
||||
console.log('\n=== Ollama Configs ===')
|
||||
ollamaConfigs.forEach(c => {
|
||||
console.log(`${c.key}: "${c.value}"`)
|
||||
})
|
||||
|
||||
console.log('\n=== OpenAI Configs ===')
|
||||
openaiConfigs.forEach(c => {
|
||||
console.log(`${c.key}: "${c.value}"`)
|
||||
})
|
||||
|
||||
console.log('\n=== All Configs ===')
|
||||
configs.forEach(c => {
|
||||
console.log(`${c.key}: "${c.value}"`)
|
||||
})
|
||||
}
|
||||
|
||||
debugConfig()
|
||||
.then(() => process.exit(0))
|
||||
.catch((err) => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -1,36 +0,0 @@
|
||||
|
||||
import { getAllNotes } from '../app/actions/notes'
|
||||
import { prisma } from '../lib/prisma'
|
||||
|
||||
async function main() {
|
||||
console.log('🕵️♀️ Debugging getAllNotes...')
|
||||
|
||||
// 1. Get raw DB data for a sample note
|
||||
const rawNote = await prisma.note.findFirst({
|
||||
where: { size: { not: 'small' } }
|
||||
})
|
||||
|
||||
if (rawNote) {
|
||||
console.log('📊 Raw DB Note (should be large/medium):', {
|
||||
id: rawNote.id,
|
||||
size: rawNote.size
|
||||
})
|
||||
} else {
|
||||
console.log('⚠️ No notes with size != small found in DB directly.')
|
||||
}
|
||||
|
||||
// 2. Mock auth/session if needed (actions check session)
|
||||
// Since we can't easily mock next-auth in this script environment without setup,
|
||||
// we might need to rely on the direct DB check above or check if getAllNotes extracts userId safely.
|
||||
// getAllNotes checks `auth()`. In this script context, `auth()` will arguably return null.
|
||||
// So we can't easily run `getAllNotes` directly if it guards auth.
|
||||
|
||||
// Let's modify the plan: We will check the DB directly to confirm PERMANENCE.
|
||||
// Then we will manually simulate `parseNote` logic.
|
||||
|
||||
const notes = await prisma.note.findMany({ take: 5 })
|
||||
console.log('📋 Checking first 5 notes sizes in DB:')
|
||||
notes.forEach(n => console.log(`- ${n.id}: ${n.size}`))
|
||||
}
|
||||
|
||||
main().catch(console.error).finally(() => prisma.$disconnect())
|
||||
@@ -1,60 +0,0 @@
|
||||
import { PrismaClient } from '../prisma/client-generated'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
async function main() {
|
||||
// 1. Get a user
|
||||
const user = await prisma.user.findFirst()
|
||||
if (!user) {
|
||||
console.log('No user found in database.')
|
||||
return
|
||||
}
|
||||
console.log(`Checking for User ID: ${user.id} (${user.email})`)
|
||||
|
||||
// 2. Simulate logic from app/actions/notes.ts
|
||||
const sevenDaysAgo = new Date()
|
||||
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
|
||||
sevenDaysAgo.setHours(0, 0, 0, 0)
|
||||
|
||||
console.log(`Filtering for notes updated after: ${sevenDaysAgo.toISOString()}`)
|
||||
|
||||
// 3. Query Raw
|
||||
const allNotes = await prisma.note.findMany({
|
||||
where: { userId: user.id },
|
||||
select: { id: true, title: true, contentUpdatedAt: true, updatedAt: true, dismissedFromRecent: true, isArchived: true }
|
||||
})
|
||||
|
||||
console.log(`\nTotal Notes for User: ${allNotes.length}`)
|
||||
|
||||
// 4. Check "Recent" candidates
|
||||
const recentCandidates = allNotes.filter(n => {
|
||||
const noteDate = new Date(n.contentUpdatedAt)
|
||||
return noteDate >= sevenDaysAgo
|
||||
})
|
||||
|
||||
console.log(`Notes passing date filter: ${recentCandidates.length}`)
|
||||
recentCandidates.forEach(n => {
|
||||
console.log(` - [${n.title}] Updated: ${n.contentUpdatedAt.toISOString()} | Dismissed: ${n.dismissedFromRecent} | Archived: ${n.isArchived}`)
|
||||
})
|
||||
|
||||
// 5. Check what the actual query returns
|
||||
const actualQuery = await prisma.note.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
contentUpdatedAt: { gte: sevenDaysAgo },
|
||||
isArchived: false,
|
||||
dismissedFromRecent: false
|
||||
},
|
||||
orderBy: { contentUpdatedAt: 'desc' },
|
||||
take: 3
|
||||
})
|
||||
|
||||
console.log(`\nActual Query Returns: ${actualQuery.length} notes`)
|
||||
actualQuery.forEach(n => {
|
||||
console.log(` -> [${n.title}]`)
|
||||
})
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => console.error(e))
|
||||
.finally(async () => await prisma.$disconnect())
|
||||
@@ -1,39 +0,0 @@
|
||||
import { PrismaClient } from '../prisma/client-generated'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
async function main() {
|
||||
console.log('Updating user settings to show recent notes...')
|
||||
|
||||
const updateResult = await prisma.userAISettings.updateMany({
|
||||
data: {
|
||||
showRecentNotes: true
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`Updated ${updateResult.count} user settings.`)
|
||||
|
||||
// Verify and Create missing
|
||||
const users = await prisma.user.findMany({
|
||||
include: { aiSettings: true }
|
||||
})
|
||||
|
||||
for (const u of users) {
|
||||
if (!u.aiSettings) {
|
||||
console.log(`User ${u.id} has no settings. Creating default...`)
|
||||
await prisma.userAISettings.create({
|
||||
data: {
|
||||
userId: u.id,
|
||||
showRecentNotes: true
|
||||
}
|
||||
})
|
||||
console.log(`Created settings for ${u.id}`)
|
||||
} else {
|
||||
console.log(`User ${u.id}: showRecentNotes = ${u.aiSettings.showRecentNotes}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => console.error(e))
|
||||
.finally(async () => await prisma.$disconnect())
|
||||
@@ -1,145 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate flat i18n-overrides/*.json for keys still equal to en while fr differs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from deep_translator import GoogleTranslator
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LOCALES = ROOT / "locales"
|
||||
OUT_DIR = Path(__file__).resolve().parent / "i18n-overrides"
|
||||
|
||||
LANG_TARGETS = {
|
||||
"ja": "ja",
|
||||
"ko": "ko",
|
||||
"zh": "zh-CN",
|
||||
"hi": "hi",
|
||||
"fa": "fa",
|
||||
}
|
||||
|
||||
MISSING_11 = [
|
||||
"ai.featureLocked",
|
||||
"ai.quotaExceeded",
|
||||
"profile.tab",
|
||||
"about.tab",
|
||||
"appearance.tab",
|
||||
"usageMeter.featureReformulate",
|
||||
"usageMeter.featureChat",
|
||||
"usageMeter.featureBrainstormCreate",
|
||||
"usageMeter.featureBrainstormExpand",
|
||||
"usageMeter.featureBrainstormEnrich",
|
||||
"billing.tab",
|
||||
]
|
||||
|
||||
PERSIAN_DIGITS = "۰۱۲۳۴۵۶۷۸۹"
|
||||
|
||||
|
||||
def flatten_leaves(obj: dict, prefix: str = "") -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for k, v in obj.items():
|
||||
path = f"{prefix}.{k}" if prefix else k
|
||||
if isinstance(v, dict):
|
||||
out.update(flatten_leaves(v, path))
|
||||
elif isinstance(v, str):
|
||||
out[path] = v
|
||||
return out
|
||||
|
||||
|
||||
def to_persian_digits(text: str) -> str:
|
||||
return re.sub(r"\d", lambda m: PERSIAN_DIGITS[int(m.group())], text)
|
||||
|
||||
|
||||
def collect_override_keys(en: dict[str, str], fr: dict[str, str], loc: dict[str, str], lang: str) -> list[str]:
|
||||
fr_translated = [k for k in en if k in fr and fr[k] != en[k]]
|
||||
keys = {k for k in fr_translated if loc.get(k, en.get(k)) == en[k]}
|
||||
if lang != "fa":
|
||||
keys.update(MISSING_11)
|
||||
return sorted(keys)
|
||||
|
||||
|
||||
def translate_unique(texts: list[str], target_code: str, batch_size: int = 30) -> dict[str, str]:
|
||||
translator = GoogleTranslator(source="en", target=target_code)
|
||||
mapping: dict[str, str] = {}
|
||||
for i in range(0, len(texts), batch_size):
|
||||
batch = texts[i : i + batch_size]
|
||||
try:
|
||||
outs = translator.translate_batch(batch)
|
||||
except Exception as e:
|
||||
print(f" batch error ({e}), per-item…", flush=True)
|
||||
outs = []
|
||||
for t in batch:
|
||||
try:
|
||||
outs.append(translator.translate(t))
|
||||
except Exception:
|
||||
outs.append(t)
|
||||
time.sleep(0.2)
|
||||
if not isinstance(outs, list) or len(outs) != len(batch):
|
||||
outs = batch
|
||||
for src, dst in zip(batch, outs):
|
||||
mapping[src] = dst if isinstance(dst, str) and dst.strip() else src
|
||||
time.sleep(0.5)
|
||||
print(f" … {min(i + batch_size, len(texts))}/{len(texts)}", flush=True)
|
||||
return mapping
|
||||
|
||||
|
||||
def post_process(lang: str, key: str, en_val: str, translated: str) -> str:
|
||||
if lang == "fa" and re.search(r"\d", translated):
|
||||
translated = to_persian_digits(translated)
|
||||
# Momento note-taking: keep common product tokens
|
||||
if key.endswith(".technology.ai") or key == "about.technology.ai":
|
||||
if lang == "ja":
|
||||
return "AI"
|
||||
if lang == "zh":
|
||||
return "AI"
|
||||
if lang == "ko":
|
||||
return "AI"
|
||||
if lang == "hi":
|
||||
return "AI"
|
||||
if lang == "fa":
|
||||
return "هوش مصنوعی"
|
||||
if key == "about.technology.ui":
|
||||
ui_map = {"ja": "UI", "ko": "UI", "zh": "界面", "hi": "UI", "fa": "رابط کاربری"}
|
||||
return ui_map.get(lang, translated)
|
||||
return translated
|
||||
|
||||
|
||||
def main() -> int:
|
||||
en = flatten_leaves(json.loads((LOCALES / "en.json").read_text(encoding="utf-8")))
|
||||
fr = flatten_leaves(json.loads((LOCALES / "fr.json").read_text(encoding="utf-8")))
|
||||
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for lang, google_target in LANG_TARGETS.items():
|
||||
loc = flatten_leaves(json.loads((LOCALES / f"{lang}.json").read_text(encoding="utf-8")))
|
||||
keys = collect_override_keys(en, fr, loc, lang)
|
||||
print(f"\n=== {lang}.json — {len(keys)} override keys", flush=True)
|
||||
|
||||
text_to_keys: dict[str, list[str]] = {}
|
||||
for k in keys:
|
||||
text_to_keys.setdefault(en[k], []).append(k)
|
||||
|
||||
unique = list(text_to_keys.keys())
|
||||
trans_map = translate_unique(unique, google_target)
|
||||
|
||||
overrides: dict[str, str] = {}
|
||||
for src, key_list in text_to_keys.items():
|
||||
tr = trans_map.get(src, src)
|
||||
for k in key_list:
|
||||
overrides[k] = post_process(lang, k, en[k], tr)
|
||||
|
||||
out_path = OUT_DIR / f"{lang}.json"
|
||||
out_path.write_text(
|
||||
json.dumps(overrides, ensure_ascii=False, indent=2) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
print(f" Wrote {out_path} ({len(overrides)} keys)", flush=True)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,24 +0,0 @@
|
||||
|
||||
import { prisma } from '../lib/prisma'
|
||||
|
||||
async function main() {
|
||||
console.log('👑 Granting ADMIN access to ALL users...')
|
||||
|
||||
try {
|
||||
const result = await prisma.user.updateMany({
|
||||
data: {
|
||||
role: 'ADMIN'
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`✅ Success! Updated ${result.count} users to ADMIN role.`)
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error updating users:', error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => console.error(e))
|
||||
.finally(async () => await prisma.$disconnect())
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,35 +0,0 @@
|
||||
/**
|
||||
* Ajoute récursivement les clés présentes dans locales/en.json mais absentes
|
||||
* des autres fichiers (valeur = texte anglais, à retraduire si besoin).
|
||||
* Usage: node scripts/merge-missing-locale-keys.mjs
|
||||
*/
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const localesDir = path.join(__dirname, '..', 'locales')
|
||||
const enPath = path.join(localesDir, 'en.json')
|
||||
|
||||
function mergeMissing(target, source) {
|
||||
for (const [k, v] of Object.entries(source)) {
|
||||
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
|
||||
if (!target[k] || typeof target[k] !== 'object' || Array.isArray(target[k])) {
|
||||
target[k] = {}
|
||||
}
|
||||
mergeMissing(target[k], v)
|
||||
} else {
|
||||
if (!(k in target)) target[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const en = JSON.parse(fs.readFileSync(enPath, 'utf8'))
|
||||
for (const name of fs.readdirSync(localesDir)) {
|
||||
if (!name.endsWith('.json') || name === 'en.json') continue
|
||||
const p = path.join(localesDir, name)
|
||||
const loc = JSON.parse(fs.readFileSync(p, 'utf8'))
|
||||
mergeMissing(loc, en)
|
||||
fs.writeFileSync(p, JSON.stringify(loc, null, 2) + '\n')
|
||||
}
|
||||
console.log('merge-missing-locale-keys: OK')
|
||||
@@ -1,69 +0,0 @@
|
||||
// scripts/migrate-embeddings.ts
|
||||
// Re-indexes all notes that lack a NoteEmbedding row using pgvector format.
|
||||
// Run with: npx tsx scripts/migrate-embeddings.ts
|
||||
|
||||
const { PrismaClient } = require('../node_modules/.prisma/client')
|
||||
|
||||
const prisma = new PrismaClient({
|
||||
datasources: {
|
||||
db: {
|
||||
url: process.env.DATABASE_URL
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
async function main() {
|
||||
console.log('Fetching notes without embeddings...')
|
||||
const notes = await prisma.note.findMany({
|
||||
where: {
|
||||
trashedAt: null,
|
||||
noteEmbedding: { is: null }
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
content: true,
|
||||
title: true
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`Found ${notes.length} notes without an embedding.`)
|
||||
|
||||
if (notes.length === 0) {
|
||||
console.log('Nothing to migrate.')
|
||||
return
|
||||
}
|
||||
|
||||
let count = 0
|
||||
let failed = 0
|
||||
for (const note of notes) {
|
||||
if (!note.content) continue
|
||||
try {
|
||||
// Embedding will be generated by the indexNote method which handles pgvector format
|
||||
await prisma.$executeRawUnsafe(
|
||||
`INSERT INTO "NoteEmbedding" ("id", "noteId", "embedding", "createdAt", "updatedAt")
|
||||
VALUES (gen_random_uuid(), $1, '[0]'::vector(1536), now(), now())
|
||||
ON CONFLICT ("noteId") DO NOTHING`,
|
||||
note.id
|
||||
)
|
||||
count++
|
||||
if (count % 10 === 0) {
|
||||
console.log(`Placeholder for ${count}/${notes.length}...`)
|
||||
}
|
||||
} catch (e) {
|
||||
failed++
|
||||
console.error(`Failed for note ${note.id}:`, e.message)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Created ${count} embedding placeholders (${failed} failed).`)
|
||||
console.log('Run /api/notes/reindex to populate with real embeddings.')
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error('Migration failed:', e)
|
||||
process.exit(1)
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect()
|
||||
})
|
||||
@@ -1,387 +0,0 @@
|
||||
/**
|
||||
* One-shot migration script: SQLite → PostgreSQL
|
||||
*
|
||||
* Reads data from the SQLite backup (prisma/dev.db) via better-sqlite3,
|
||||
* connects to PostgreSQL via Prisma, and inserts all rows while converting
|
||||
* JSON string fields to native objects (for Prisma Json type).
|
||||
*
|
||||
* Usage:
|
||||
* DATABASE_URL="postgresql://keepnotes:keepnotes@localhost:5432/keepnotes" \
|
||||
* npx tsx scripts/migrate-sqlite-to-postgres.ts
|
||||
*
|
||||
* Prerequisites:
|
||||
* - PostgreSQL running and accessible via DATABASE_URL
|
||||
* - prisma migrate deploy already run (schema exists)
|
||||
* - better-sqlite3 still installed (temporary)
|
||||
*/
|
||||
|
||||
import Database from 'better-sqlite3'
|
||||
import { PrismaClient } from '../prisma/client-generated'
|
||||
import * as path from 'path'
|
||||
|
||||
const SQLITE_PATH = path.join(__dirname, '..', 'prisma', 'dev.db')
|
||||
|
||||
// Parse a JSON string field, returning null if empty/invalid
|
||||
function parseJsonField(raw: any): any {
|
||||
if (raw === null || raw === undefined) return null
|
||||
if (typeof raw !== 'string') return raw
|
||||
if (raw === '' || raw === 'null') return null
|
||||
try {
|
||||
return JSON.parse(raw)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Parse labels specifically — always return array or null
|
||||
function parseLabels(raw: any): string[] | null {
|
||||
const parsed = parseJsonField(raw)
|
||||
if (Array.isArray(parsed)) return parsed
|
||||
return null
|
||||
}
|
||||
|
||||
// Parse embedding — always return number[] or null
|
||||
function parseEmbedding(raw: any): number[] | null {
|
||||
const parsed = parseJsonField(raw)
|
||||
if (Array.isArray(parsed)) return parsed
|
||||
return null
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('╔══════════════════════════════════════════════════════════╗')
|
||||
console.log('║ SQLite → PostgreSQL Migration ║')
|
||||
console.log('╚══════════════════════════════════════════════════════════╝')
|
||||
console.log()
|
||||
|
||||
// 1. Open SQLite
|
||||
let sqlite: Database.Database
|
||||
try {
|
||||
sqlite = new Database(SQLITE_PATH, { readonly: true })
|
||||
console.log(`✓ SQLite opened: ${SQLITE_PATH}`)
|
||||
} catch (e) {
|
||||
console.error(`✗ Cannot open SQLite at ${SQLITE_PATH}: ${e}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// 2. Connect to PostgreSQL via Prisma
|
||||
const prisma = new PrismaClient()
|
||||
console.log(`✓ PostgreSQL connected via Prisma`)
|
||||
console.log()
|
||||
|
||||
// Helper to read all rows from SQLite
|
||||
function allRows(sql: string): any[] {
|
||||
return sqlite.prepare(sql).all() as any[]
|
||||
}
|
||||
|
||||
let totalInserted = 0
|
||||
|
||||
// ── User ──────────────────────────────────────────────────
|
||||
console.log('Migrating User...')
|
||||
const users = allRows('SELECT * FROM User')
|
||||
for (const u of users) {
|
||||
await prisma.user.upsert({
|
||||
where: { id: u.id },
|
||||
update: {},
|
||||
create: {
|
||||
id: u.id,
|
||||
name: u.name,
|
||||
email: u.email,
|
||||
emailVerified: u.emailVerified ? new Date(u.emailVerified) : null,
|
||||
password: u.password,
|
||||
role: u.role || 'USER',
|
||||
image: u.image,
|
||||
theme: u.theme || 'light',
|
||||
resetToken: u.resetToken,
|
||||
resetTokenExpiry: u.resetTokenExpiry ? new Date(u.resetTokenExpiry) : null,
|
||||
createdAt: u.createdAt ? new Date(u.createdAt) : new Date(),
|
||||
updatedAt: u.updatedAt ? new Date(u.updatedAt) : new Date(),
|
||||
}
|
||||
})
|
||||
}
|
||||
console.log(` → ${users.length} users`)
|
||||
totalInserted += users.length
|
||||
|
||||
// ── Account ───────────────────────────────────────────────
|
||||
console.log('Migrating Account...')
|
||||
const accounts = allRows('SELECT * FROM Account')
|
||||
for (const a of accounts) {
|
||||
await prisma.account.create({
|
||||
data: {
|
||||
userId: a.userId,
|
||||
type: a.type,
|
||||
provider: a.provider,
|
||||
providerAccountId: a.providerAccountId,
|
||||
refresh_token: a.refresh_token,
|
||||
access_token: a.access_token,
|
||||
expires_at: a.expires_at,
|
||||
token_type: a.token_type,
|
||||
scope: a.scope,
|
||||
id_token: a.id_token,
|
||||
session_state: a.session_state,
|
||||
createdAt: a.createdAt ? new Date(a.createdAt) : new Date(),
|
||||
updatedAt: a.updatedAt ? new Date(a.updatedAt) : new Date(),
|
||||
}
|
||||
}).catch(() => {}) // skip duplicates
|
||||
}
|
||||
console.log(` → ${accounts.length} accounts`)
|
||||
totalInserted += accounts.length
|
||||
|
||||
// ── Session ───────────────────────────────────────────────
|
||||
console.log('Migrating Session...')
|
||||
const sessions = allRows('SELECT * FROM Session')
|
||||
for (const s of sessions) {
|
||||
await prisma.session.create({
|
||||
data: {
|
||||
sessionToken: s.sessionToken,
|
||||
userId: s.userId,
|
||||
expires: s.expires ? new Date(s.expires) : new Date(),
|
||||
createdAt: s.createdAt ? new Date(s.createdAt) : new Date(),
|
||||
updatedAt: s.updatedAt ? new Date(s.updatedAt) : new Date(),
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
console.log(` → ${sessions.length} sessions`)
|
||||
totalInserted += sessions.length
|
||||
|
||||
// ── Notebook ──────────────────────────────────────────────
|
||||
console.log('Migrating Notebook...')
|
||||
const notebooks = allRows('SELECT * FROM Notebook')
|
||||
for (const nb of notebooks) {
|
||||
await prisma.notebook.create({
|
||||
data: {
|
||||
id: nb.id,
|
||||
name: nb.name,
|
||||
icon: nb.icon,
|
||||
color: nb.color,
|
||||
order: nb.order ?? 0,
|
||||
userId: nb.userId,
|
||||
createdAt: nb.createdAt ? new Date(nb.createdAt) : new Date(),
|
||||
updatedAt: nb.updatedAt ? new Date(nb.updatedAt) : new Date(),
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
console.log(` → ${notebooks.length} notebooks`)
|
||||
totalInserted += notebooks.length
|
||||
|
||||
// ── Label ─────────────────────────────────────────────────
|
||||
console.log('Migrating Label...')
|
||||
const labels = allRows('SELECT * FROM Label')
|
||||
for (const l of labels) {
|
||||
await prisma.label.create({
|
||||
data: {
|
||||
id: l.id,
|
||||
name: l.name,
|
||||
color: l.color || 'gray',
|
||||
notebookId: l.notebookId,
|
||||
userId: l.userId,
|
||||
createdAt: l.createdAt ? new Date(l.createdAt) : new Date(),
|
||||
updatedAt: l.updatedAt ? new Date(l.updatedAt) : new Date(),
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
console.log(` → ${labels.length} labels`)
|
||||
totalInserted += labels.length
|
||||
|
||||
// ── Note ──────────────────────────────────────────────────
|
||||
console.log('Migrating Note...')
|
||||
const notes = allRows('SELECT * FROM Note')
|
||||
let noteCount = 0
|
||||
for (const n of notes) {
|
||||
await prisma.note.create({
|
||||
data: {
|
||||
id: n.id,
|
||||
title: n.title,
|
||||
content: n.content || '',
|
||||
color: n.color || 'default',
|
||||
isPinned: n.isPinned === 1 || n.isPinned === true,
|
||||
isArchived: n.isArchived === 1 || n.isArchived === true,
|
||||
type: n.type || 'text',
|
||||
dismissedFromRecent: n.dismissedFromRecent === 1 || n.dismissedFromRecent === true,
|
||||
checkItems: parseJsonField(n.checkItems),
|
||||
labels: parseLabels(n.labels),
|
||||
images: parseJsonField(n.images),
|
||||
links: parseJsonField(n.links),
|
||||
reminder: n.reminder ? new Date(n.reminder) : null,
|
||||
isReminderDone: n.isReminderDone === 1 || n.isReminderDone === true,
|
||||
reminderRecurrence: n.reminderRecurrence,
|
||||
reminderLocation: n.reminderLocation,
|
||||
isMarkdown: n.isMarkdown === 1 || n.isMarkdown === true,
|
||||
size: n.size || 'small',
|
||||
embedding: parseEmbedding(n.embedding),
|
||||
sharedWith: parseJsonField(n.sharedWith),
|
||||
userId: n.userId,
|
||||
order: n.order ?? 0,
|
||||
notebookId: n.notebookId,
|
||||
createdAt: n.createdAt ? new Date(n.createdAt) : new Date(),
|
||||
updatedAt: n.updatedAt ? new Date(n.updatedAt) : new Date(),
|
||||
contentUpdatedAt: n.contentUpdatedAt ? new Date(n.contentUpdatedAt) : new Date(),
|
||||
autoGenerated: n.autoGenerated === 1 ? true : n.autoGenerated === 0 ? false : null,
|
||||
aiProvider: n.aiProvider,
|
||||
aiConfidence: n.aiConfidence,
|
||||
language: n.language,
|
||||
languageConfidence: n.languageConfidence,
|
||||
lastAiAnalysis: n.lastAiAnalysis ? new Date(n.lastAiAnalysis) : null,
|
||||
}
|
||||
}).catch((e) => {
|
||||
console.error(` Failed note ${n.id}: ${e.message}`)
|
||||
})
|
||||
noteCount++
|
||||
}
|
||||
console.log(` → ${noteCount} notes`)
|
||||
totalInserted += noteCount
|
||||
|
||||
// ── NoteShare ─────────────────────────────────────────────
|
||||
console.log('Migrating NoteShare...')
|
||||
const noteShares = allRows('SELECT * FROM NoteShare')
|
||||
for (const ns of noteShares) {
|
||||
await prisma.noteShare.create({
|
||||
data: {
|
||||
id: ns.id,
|
||||
noteId: ns.noteId,
|
||||
userId: ns.userId,
|
||||
sharedBy: ns.sharedBy,
|
||||
status: ns.status || 'pending',
|
||||
permission: ns.permission || 'view',
|
||||
notifiedAt: ns.notifiedAt ? new Date(ns.notifiedAt) : null,
|
||||
respondedAt: ns.respondedAt ? new Date(ns.respondedAt) : null,
|
||||
createdAt: ns.createdAt ? new Date(ns.createdAt) : new Date(),
|
||||
updatedAt: ns.updatedAt ? new Date(ns.updatedAt) : new Date(),
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
console.log(` → ${noteShares.length} note shares`)
|
||||
totalInserted += noteShares.length
|
||||
|
||||
// ── AiFeedback ────────────────────────────────────────────
|
||||
console.log('Migrating AiFeedback...')
|
||||
const aiFeedbacks = allRows('SELECT * FROM AiFeedback')
|
||||
for (const af of aiFeedbacks) {
|
||||
await prisma.aiFeedback.create({
|
||||
data: {
|
||||
id: af.id,
|
||||
noteId: af.noteId,
|
||||
userId: af.userId,
|
||||
feedbackType: af.feedbackType,
|
||||
feature: af.feature,
|
||||
originalContent: af.originalContent || '',
|
||||
correctedContent: af.correctedContent,
|
||||
metadata: parseJsonField(af.metadata),
|
||||
createdAt: af.createdAt ? new Date(af.createdAt) : new Date(),
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
console.log(` → ${aiFeedbacks.length} ai feedbacks`)
|
||||
totalInserted += aiFeedbacks.length
|
||||
|
||||
// ── MemoryEchoInsight ─────────────────────────────────────
|
||||
console.log('Migrating MemoryEchoInsight...')
|
||||
const insights = allRows('SELECT * FROM MemoryEchoInsight')
|
||||
for (const mi of insights) {
|
||||
await prisma.memoryEchoInsight.create({
|
||||
data: {
|
||||
id: mi.id,
|
||||
userId: mi.userId,
|
||||
note1Id: mi.note1Id,
|
||||
note2Id: mi.note2Id,
|
||||
similarityScore: mi.similarityScore ?? 0,
|
||||
insight: mi.insight || '',
|
||||
insightDate: mi.insightDate ? new Date(mi.insightDate) : new Date(),
|
||||
viewed: mi.viewed === 1 || mi.viewed === true,
|
||||
feedback: mi.feedback,
|
||||
dismissed: mi.dismissed === 1 || mi.dismissed === true,
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
console.log(` → ${insights.length} memory echo insights`)
|
||||
totalInserted += insights.length
|
||||
|
||||
// ── UserAISettings ────────────────────────────────────────
|
||||
console.log('Migrating UserAISettings...')
|
||||
const aiSettings = allRows('SELECT * FROM UserAISettings')
|
||||
for (const s of aiSettings) {
|
||||
await prisma.userAISettings.create({
|
||||
data: {
|
||||
userId: s.userId,
|
||||
titleSuggestions: s.titleSuggestions === 1 || s.titleSuggestions === true,
|
||||
semanticSearch: s.semanticSearch === 1 || s.semanticSearch === true,
|
||||
paragraphRefactor: s.paragraphRefactor === 1 || s.paragraphRefactor === true,
|
||||
memoryEcho: s.memoryEcho === 1 || s.memoryEcho === true,
|
||||
memoryEchoFrequency: s.memoryEchoFrequency || 'daily',
|
||||
aiProvider: s.aiProvider || 'auto',
|
||||
preferredLanguage: s.preferredLanguage || 'auto',
|
||||
fontSize: s.fontSize || 'medium',
|
||||
demoMode: s.demoMode === 1 || s.demoMode === true,
|
||||
showRecentNotes: s.showRecentNotes === 1 || s.showRecentNotes === true,
|
||||
emailNotifications: s.emailNotifications === 1 || s.emailNotifications === true,
|
||||
desktopNotifications: s.desktopNotifications === 1 || s.desktopNotifications === true,
|
||||
anonymousAnalytics: s.anonymousAnalytics === 1 || s.anonymousAnalytics === true,
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
console.log(` → ${aiSettings.length} user AI settings`)
|
||||
totalInserted += aiSettings.length
|
||||
|
||||
// ── SystemConfig ──────────────────────────────────────────
|
||||
console.log('Migrating SystemConfig...')
|
||||
const configs = allRows('SELECT * FROM SystemConfig')
|
||||
for (const c of configs) {
|
||||
await prisma.systemConfig.create({
|
||||
data: {
|
||||
key: c.key,
|
||||
value: c.value,
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
console.log(` → ${configs.length} system configs`)
|
||||
totalInserted += configs.length
|
||||
|
||||
// ── _LabelToNote (many-to-many relations) ─────────────────
|
||||
console.log('Migrating Label-Note relations...')
|
||||
let relationCount = 0
|
||||
try {
|
||||
const relations = allRows('SELECT * FROM _LabelToNote')
|
||||
for (const r of relations) {
|
||||
await prisma.note.update({
|
||||
where: { id: r.B },
|
||||
data: {
|
||||
labelRelations: { connect: { id: r.A } }
|
||||
}
|
||||
}).catch(() => {})
|
||||
relationCount++
|
||||
}
|
||||
} catch {
|
||||
// Table may not exist in older SQLite databases
|
||||
console.log(' → _LabelToNote table not found, skipping')
|
||||
}
|
||||
console.log(` → ${relationCount} label-note relations`)
|
||||
totalInserted += relationCount
|
||||
|
||||
// ── VerificationToken ─────────────────────────────────────
|
||||
console.log('Migrating VerificationToken...')
|
||||
const tokens = allRows('SELECT * FROM VerificationToken')
|
||||
for (const t of tokens) {
|
||||
await prisma.verificationToken.create({
|
||||
data: {
|
||||
identifier: t.identifier,
|
||||
token: t.token,
|
||||
expires: t.expires ? new Date(t.expires) : new Date(),
|
||||
}
|
||||
}).catch(() => {})
|
||||
}
|
||||
console.log(` → ${tokens.length} verification tokens`)
|
||||
totalInserted += tokens.length
|
||||
|
||||
// Cleanup
|
||||
sqlite.close()
|
||||
await prisma.$disconnect()
|
||||
|
||||
console.log()
|
||||
console.log('╔══════════════════════════════════════════════════════════╗')
|
||||
console.log(`║ Migration complete: ${totalInserted} total rows inserted ║`)
|
||||
console.log('╚══════════════════════════════════════════════════════════╝')
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('Migration failed:', e)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -1,35 +0,0 @@
|
||||
const { PrismaClient } = require('../prisma/client-generated');
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function promoteAdmin() {
|
||||
const email = process.argv[2];
|
||||
|
||||
try {
|
||||
let user;
|
||||
if (email) {
|
||||
user = await prisma.user.findUnique({ where: { email } });
|
||||
} else {
|
||||
console.log("Aucun email fourni, promotion du premier utilisateur trouvé...");
|
||||
user = await prisma.user.findFirst();
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
console.error("Aucun utilisateur trouvé.");
|
||||
return;
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { role: 'ADMIN' }
|
||||
});
|
||||
|
||||
console.log(`Succès : L'utilisateur ${user.email} (${user.name}) est maintenant ADMIN.`);
|
||||
|
||||
} catch (e) {
|
||||
console.error("Erreur :", e);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
promoteAdmin();
|
||||
@@ -1,67 +0,0 @@
|
||||
import { PrismaClient } from '../prisma/client-generated'
|
||||
import { getAIProvider } from '../lib/ai/factory'
|
||||
import { getSystemConfig } from '../lib/config'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
async function regenerateAllEmbeddings() {
|
||||
console.log('🔄 Starting embedding regeneration...\n')
|
||||
|
||||
// Get all notes
|
||||
const notes = await prisma.note.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
content: true
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`📝 Found ${notes.length} notes to process\n`)
|
||||
|
||||
// Get AI provider
|
||||
const config = await getSystemConfig()
|
||||
const provider = getAIProvider(config)
|
||||
|
||||
console.log(`🤖 Using AI provider...`)
|
||||
|
||||
let successCount = 0
|
||||
let errorCount = 0
|
||||
|
||||
for (const note of notes) {
|
||||
try {
|
||||
const title = note.title || '(no title)'
|
||||
process.stdout.write(`\r⏳ Processing ${successCount + 1}/${notes.length}: ${title.substring(0, 40)}...`)
|
||||
|
||||
// Generate new embedding
|
||||
const embedding = await provider.getEmbeddings(note.content)
|
||||
|
||||
if (embedding) {
|
||||
// Update note with new embedding
|
||||
await prisma.note.update({
|
||||
where: { id: note.id },
|
||||
data: {
|
||||
embedding
|
||||
}
|
||||
})
|
||||
|
||||
successCount++
|
||||
} else {
|
||||
errorCount++
|
||||
console.log(`\n❌ Failed: ${title} (no embedding generated)`)
|
||||
}
|
||||
} catch (error) {
|
||||
errorCount++
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
||||
console.log(`\n❌ Error: ${note.title || '(no title)'} - ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n\n📊 Summary:`)
|
||||
console.log(` ✅ Success: ${successCount}/${notes.length}`)
|
||||
console.log(` ❌ Errors: ${errorCount}/${notes.length}`)
|
||||
console.log('\n✨ Embeddings regenerated successfully!')
|
||||
|
||||
await prisma.$disconnect()
|
||||
}
|
||||
|
||||
regenerateAllEmbeddings().catch(console.error)
|
||||
@@ -1,47 +0,0 @@
|
||||
|
||||
import { prisma } from '../lib/prisma'
|
||||
import bcrypt from 'bcryptjs'
|
||||
|
||||
async function main() {
|
||||
const email = process.argv[2]
|
||||
const newPassword = process.argv[3]
|
||||
|
||||
if (!email || !newPassword) {
|
||||
console.error('Usage: npx tsx scripts/reset-password-auto.ts <email> <new-password>')
|
||||
console.error('Example: npx tsx scripts/reset-password-auto.ts user@example.com mynewpassword')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (newPassword.length < 6) {
|
||||
console.error('Password must be at least 6 characters')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`Resetting password for ${email}...`)
|
||||
|
||||
const hashedPassword = await bcrypt.hash(newPassword, 10)
|
||||
|
||||
try {
|
||||
const user = await prisma.user.update({
|
||||
where: { email },
|
||||
data: {
|
||||
password: hashedPassword,
|
||||
resetToken: null,
|
||||
resetTokenExpiry: null
|
||||
},
|
||||
})
|
||||
console.log(`Password successfully reset for ${user.email}`)
|
||||
} catch (error) {
|
||||
console.error('Error resetting password:', error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => {
|
||||
console.error(e)
|
||||
process.exit(1)
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect()
|
||||
})
|
||||
@@ -1,22 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
import bcrypt from 'bcryptjs'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
async function main() {
|
||||
const hashedPassword = await bcrypt.hash('password123', 10)
|
||||
const user = await prisma.user.upsert({
|
||||
where: { email: 'test@example.com' },
|
||||
update: {},
|
||||
create: {
|
||||
email: 'test@example.com',
|
||||
name: 'Test User',
|
||||
password: hashedPassword,
|
||||
},
|
||||
})
|
||||
console.log('User created:', user)
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => console.error(e))
|
||||
.finally(async () => await prisma.$disconnect())
|
||||
@@ -1,48 +0,0 @@
|
||||
import prisma from '../lib/prisma'
|
||||
|
||||
/**
|
||||
* Setup OpenAI as default AI provider in database
|
||||
* Run this to ensure OpenAI is properly configured
|
||||
*/
|
||||
async function setupOpenAI() {
|
||||
console.log('🔧 Setting up OpenAI as default AI provider...\n')
|
||||
|
||||
const configs = [
|
||||
{ key: 'AI_PROVIDER_TAGS', value: 'openai' },
|
||||
{ key: 'AI_PROVIDER_EMBEDDING', value: 'openai' },
|
||||
{ key: 'AI_MODEL_TAGS', value: 'gpt-4o-mini' },
|
||||
{ key: 'AI_MODEL_EMBEDDING', value: 'text-embedding-3-small' },
|
||||
]
|
||||
|
||||
try {
|
||||
for (const config of configs) {
|
||||
await prisma.systemConfig.upsert({
|
||||
where: { key: config.key },
|
||||
update: { value: config.value },
|
||||
create: { key: config.key, value: config.value }
|
||||
})
|
||||
console.log(`✅ Set ${config.key} = ${config.value}`)
|
||||
}
|
||||
|
||||
console.log('\n✨ OpenAI configuration complete!')
|
||||
console.log('\nNext steps:')
|
||||
console.log('1. Add your OPENAI_API_KEY in admin settings: http://localhost:3000/admin/settings')
|
||||
console.log('2. Or add it to .env.docker: OPENAI_API_KEY=sk-...')
|
||||
console.log('3. Restart the application')
|
||||
|
||||
// Verify
|
||||
const verify = await prisma.systemConfig.findMany({
|
||||
where: { key: { in: configs.map(c => c.key) } }
|
||||
})
|
||||
|
||||
console.log('\n✅ Verification:')
|
||||
verify.forEach(c => console.log(` ${c.key}: ${c.value}`))
|
||||
} catch (error) {
|
||||
console.error('❌ Error:', error)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
setupOpenAI()
|
||||
.then(() => process.exit(0))
|
||||
.catch(() => process.exit(1))
|
||||
@@ -1,163 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Synchronise locales/*.json avec locales/en.json (référence des clés).
|
||||
- Garde les chaînes déjà présentes et non vides dans la locale cible.
|
||||
- Traduit les clés manquantes (Google via deep-translator).
|
||||
Usage : depuis memento-note/ avec le venv :
|
||||
.venv-i18n/bin/python scripts/sync_locales_from_en.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from deep_translator import GoogleTranslator
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LOCALES = ROOT / "locales"
|
||||
|
||||
# Codes Google Translate pour deep-translator (source=en)
|
||||
LANG_TARGETS = {
|
||||
"fr": "fr",
|
||||
"es": "es",
|
||||
"de": "de",
|
||||
"fa": "fa",
|
||||
"it": "it",
|
||||
"pt": "pt",
|
||||
"ru": "ru",
|
||||
"zh": "zh-CN",
|
||||
"ja": "ja",
|
||||
"ko": "ko",
|
||||
"ar": "ar",
|
||||
"hi": "hi",
|
||||
"nl": "nl",
|
||||
"pl": "pl",
|
||||
}
|
||||
|
||||
|
||||
def flatten_leaves(obj: dict, prefix: str = "") -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for k, v in obj.items():
|
||||
path = f"{prefix}.{k}" if prefix else k
|
||||
if isinstance(v, dict):
|
||||
out.update(flatten_leaves(v, path))
|
||||
elif isinstance(v, str):
|
||||
out[path] = v
|
||||
else:
|
||||
raise TypeError(f"Valeur non supportée à {path}: {type(v)}")
|
||||
return out
|
||||
|
||||
|
||||
def unflatten_leaves(flat: dict[str, str]) -> dict:
|
||||
root: dict = {}
|
||||
for path, val in flat.items():
|
||||
parts = path.split(".")
|
||||
cur = root
|
||||
for p in parts[:-1]:
|
||||
cur = cur.setdefault(p, {})
|
||||
cur[parts[-1]] = val
|
||||
return root
|
||||
|
||||
|
||||
def translate_unique(texts: list[str], target_code: str, batch_size: int = 35) -> dict[str, str]:
|
||||
translator = GoogleTranslator(source="en", target=target_code)
|
||||
mapping: dict[str, str] = {}
|
||||
for i in range(0, len(texts), batch_size):
|
||||
batch = texts[i : i + batch_size]
|
||||
try:
|
||||
outs = translator.translate_batch(batch)
|
||||
except Exception as e:
|
||||
print(f" batch erreur ({e}), traduction unitaire…", flush=True)
|
||||
outs = []
|
||||
for t in batch:
|
||||
try:
|
||||
outs.append(translator.translate(t))
|
||||
except Exception:
|
||||
outs.append(t)
|
||||
time.sleep(0.15)
|
||||
if len(outs) != len(batch):
|
||||
outs = batch # fallback
|
||||
for src, dst in zip(batch, outs):
|
||||
mapping[src] = dst if isinstance(dst, str) else src
|
||||
time.sleep(0.6)
|
||||
print(f" … {min(i + batch_size, len(texts))}/{len(texts)}", flush=True)
|
||||
return mapping
|
||||
|
||||
|
||||
def merge_locale(en_flat: dict[str, str], loc_flat: dict[str, str], target_code: str) -> dict[str, str]:
|
||||
text_to_keys: dict[str, list[str]] = {}
|
||||
result: dict[str, str] = {}
|
||||
|
||||
for key, en_val in en_flat.items():
|
||||
loc_val = loc_flat.get(key)
|
||||
if isinstance(loc_val, str) and loc_val.strip():
|
||||
result[key] = loc_val
|
||||
else:
|
||||
text_to_keys.setdefault(en_val, []).append(key)
|
||||
|
||||
if not text_to_keys:
|
||||
return result
|
||||
|
||||
unique = list(text_to_keys.keys())
|
||||
print(f" {len(unique)} textes uniques à traduire ({sum(len(v) for v in text_to_keys.values())} clés)", flush=True)
|
||||
trans_map = translate_unique(unique, target_code)
|
||||
|
||||
for src, keys in text_to_keys.items():
|
||||
tr = trans_map.get(src, src)
|
||||
for k in keys:
|
||||
result[k] = tr
|
||||
return result
|
||||
|
||||
|
||||
def main() -> int:
|
||||
en_path = LOCALES / "en.json"
|
||||
if not en_path.exists():
|
||||
print("locales/en.json introuvable", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
en_obj = json.loads(en_path.read_text(encoding="utf-8"))
|
||||
en_flat = flatten_leaves(en_obj)
|
||||
print(f"Référence en.json : {len(en_flat)} clés feuilles", flush=True)
|
||||
|
||||
skip = {"en"}
|
||||
for code, google_target in LANG_TARGETS.items():
|
||||
if code in skip:
|
||||
continue
|
||||
path = LOCALES / f"{code}.json"
|
||||
if not path.exists():
|
||||
print(f"Absence de {path.name}, ignoré", flush=True)
|
||||
continue
|
||||
|
||||
loc_obj = json.loads(path.read_text(encoding="utf-8"))
|
||||
loc_flat = flatten_leaves(loc_obj)
|
||||
|
||||
before_missing = sum(1 for k in en_flat if k not in loc_flat or not str(loc_flat.get(k, "")).strip())
|
||||
if before_missing == 0:
|
||||
print(f"\n=== {code}.json — déjà complet ({len(en_flat)} clés), rien à faire", flush=True)
|
||||
continue
|
||||
|
||||
print(f"\n=== {code}.json ({google_target}) — manquantes avant: {before_missing}", flush=True)
|
||||
|
||||
merged_flat = merge_locale(en_flat, loc_flat, google_target)
|
||||
|
||||
# Couverture complète des clés en
|
||||
out_flat = dict(en_flat)
|
||||
out_flat.update(merged_flat)
|
||||
|
||||
missing_after = sum(1 for k in en_flat if k not in out_flat or not str(out_flat[k]).strip())
|
||||
if missing_after:
|
||||
print(f"ERREUR: encore {missing_after} clés vides pour {code}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
tree = unflatten_leaves(out_flat)
|
||||
path.write_text(json.dumps(tree, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(f" Écrit {path.name}", flush=True)
|
||||
|
||||
print("\nTerminé.", flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,40 +0,0 @@
|
||||
|
||||
import { prisma } from '../lib/prisma'
|
||||
|
||||
function parseNote(dbNote: any) {
|
||||
return {
|
||||
...dbNote,
|
||||
checkItems: dbNote.checkItems ? JSON.parse(dbNote.checkItems) : null,
|
||||
labels: dbNote.labels ? JSON.parse(dbNote.labels) : null,
|
||||
images: dbNote.images ? JSON.parse(dbNote.images) : null,
|
||||
links: dbNote.links ? JSON.parse(dbNote.links) : null,
|
||||
sharedWith: dbNote.sharedWith ? JSON.parse(dbNote.sharedWith) : [],
|
||||
size: dbNote.size || 'small',
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('Testing parseNote logic...')
|
||||
|
||||
const rawNote = await prisma.note.findFirst({
|
||||
where: { size: 'large' }
|
||||
})
|
||||
|
||||
if (!rawNote) {
|
||||
console.error('No large note found in DB.')
|
||||
return
|
||||
}
|
||||
|
||||
console.log('Raw Note from DB:', { id: rawNote.id, size: rawNote.size })
|
||||
|
||||
const parsed = parseNote(rawNote)
|
||||
console.log('Parsed Note:', { id: parsed.id, size: parsed.size })
|
||||
|
||||
if (parsed.size === 'large') {
|
||||
console.log('parseNote preserves size correctly.')
|
||||
} else {
|
||||
console.error('parseNote returned wrong size:', parsed.size)
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error).finally(() => prisma.$disconnect())
|
||||
@@ -1,41 +0,0 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
async function main() {
|
||||
const OLD_COLOR = '#75B2D6'
|
||||
const NEW_COLOR = '#A47148'
|
||||
|
||||
console.log(`Updating colors from ${OLD_COLOR} to ${NEW_COLOR}...`)
|
||||
|
||||
// Update Notebooks
|
||||
const updatedNotebooks = await prisma.notebook.updateMany({
|
||||
where: { color: OLD_COLOR },
|
||||
data: { color: NEW_COLOR }
|
||||
})
|
||||
console.log(`Updated ${updatedNotebooks.count} notebooks.`)
|
||||
|
||||
// Update Labels (if any use this color)
|
||||
const updatedLabels = await prisma.label.updateMany({
|
||||
where: { color: OLD_COLOR },
|
||||
data: { color: NEW_COLOR }
|
||||
})
|
||||
console.log(`Updated ${updatedLabels.count} labels.`)
|
||||
|
||||
// Update Notes (some notes might have this as a string color in metadata or field)
|
||||
// Note.color is usually "default", but let's check
|
||||
const updatedNotes = await prisma.note.updateMany({
|
||||
where: { color: OLD_COLOR },
|
||||
data: { color: NEW_COLOR }
|
||||
})
|
||||
console.log(`Updated ${updatedNotes.count} notes.`)
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => {
|
||||
console.error(e)
|
||||
process.exit(1)
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect()
|
||||
})
|
||||
@@ -1,56 +0,0 @@
|
||||
|
||||
import { prisma } from '../lib/prisma'
|
||||
import { updateSize } from '../app/actions/notes'
|
||||
|
||||
async function main() {
|
||||
console.log('🧪 Starting Note Size Persistence Verification...')
|
||||
|
||||
// 1. Create a test note
|
||||
const note = await prisma.note.create({
|
||||
data: {
|
||||
content: 'Size Test Note',
|
||||
userId: (await prisma.user.findFirst())?.id || '',
|
||||
size: 'small', // Start small
|
||||
}
|
||||
})
|
||||
console.log(`📝 Created test note (${note.id}) with size: ${note.size}`)
|
||||
|
||||
if (!note.userId) {
|
||||
console.error('❌ No user found to create note. Aborting.')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// 2. Update size to LARGE
|
||||
console.log('🔄 Updating size to LARGE...')
|
||||
// We mock the session for the action or call prisma directly if action fails (actions usually need auth context)
|
||||
// Since we're running as script, we'll use prisma update directly to simulate what the action does at DB level
|
||||
// OR we can try to invoke the action if we can mock auth.
|
||||
// Let's test the DB interaction first which is the critical "persistence" part.
|
||||
|
||||
await prisma.note.update({
|
||||
where: { id: note.id },
|
||||
data: { size: 'large' }
|
||||
})
|
||||
|
||||
// 3. Fetch back
|
||||
const updatedNote = await prisma.note.findUnique({ where: { id: note.id } })
|
||||
console.log(`🔍 Fetched note after update. Size is: ${updatedNote?.size}`)
|
||||
|
||||
if (updatedNote?.size === 'large') {
|
||||
console.log('✅ BACKEND PERSISTENCE: PASSED')
|
||||
} else {
|
||||
console.error('❌ BACKEND PERSISTENCE: FAILED (Size reverted or did not update)')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error during test:', error)
|
||||
} finally {
|
||||
// Cleanup
|
||||
await prisma.note.delete({ where: { id: note.id } })
|
||||
console.log('🧹 Cleaned up test note')
|
||||
await prisma.$disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error)
|
||||
Reference in New Issue
Block a user