diff --git a/app/BenefitSection.tsx b/app/BenefitSection.tsx index b418df5..374fd15 100644 --- a/app/BenefitSection.tsx +++ b/app/BenefitSection.tsx @@ -140,7 +140,7 @@ export default function BenefitSection() {
{isMounted && ( >; @@ -188,17 +189,43 @@ const MidiEditor = forwardRef( type: "application/octet-stream", }); + // First attempt to create score try { const response = await createScore(blob, songName.current); setFlatScore(response.id); setShowSheetMusic(true); } catch (error: any) { if (error.message === "402") { - message.current = - "Score limit reached. Please try again at the start of the next hour."; - setShowSheetMusic(false); - // Still set flatScore to trigger transition, but with a dummy value - setFlatScore("error-402"); + try { + const baseUrl = window.location.origin; + const cleared = await clearScores(baseUrl); + if (!cleared) throw new Error("Failed to clear scores"); + + // Wait a moment for deletion to complete + await new Promise((resolve) => setTimeout(resolve, 1000)); + + // Second attempt to create score + try { + const retryResponse = await createScore(blob, songName.current); + setFlatScore(retryResponse.id); + setShowSheetMusic(true); + } catch (retryError: any) { + if (retryError.message === "402") { + message.current = + "Score limit reached. Please try again tomorrow."; + setShowSheetMusic(false); + setFlatScore("error-402"); + } else { + throw retryError; + } + } + } catch (cronError) { + console.error("Failed to clear scores:", cronError); + message.current = + "Score limit reached. Please try again tomorrow."; + setShowSheetMusic(false); + setFlatScore("error-402"); + } } else { throw error; } diff --git a/utils/clearScores.ts b/utils/clearScores.ts new file mode 100644 index 0000000..7e80c38 --- /dev/null +++ b/utils/clearScores.ts @@ -0,0 +1,21 @@ +"use server"; + +export async function clearScores(baseUrl: string) { + try { + const response = await fetch(`${baseUrl}/api/cron`, { + method: "GET", + headers: { + Authorization: `Bearer ${process.env.CRON_SECRET}`, + }, + }); + + if (!response.ok) { + throw new Error(`Failed to clear scores: ${response.statusText}`); + } + + return true; + } catch (error) { + console.error("Error clearing scores:", error); + return false; + } +} diff --git a/vercel.json b/vercel.json index 7732e08..6c3c4ae 100644 --- a/vercel.json +++ b/vercel.json @@ -2,7 +2,7 @@ "crons": [ { "path": "/api/cron", - "schedule": "0 * * * *" + "schedule": "0 5 * * *" } ] }