monthly money

This commit is contained in:
Thomas Demirdjian
2025-10-31 17:31:10 +01:00
parent 6f330c1df8
commit 0dd0fa5ab7
10 changed files with 299 additions and 1 deletions
+75
View File
@@ -4,6 +4,15 @@ const { refList } = require("../index");
const { getSunoTimestamps } = require("./lyrics");
const { deleteFolder } = require("../helpers/firebase");
const firestore = admin.firestore();
const buildMonthKey = (timestamp) => {
const date = timestamp.toDate();
const year = date.getUTCFullYear();
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
return `${year}-${month}`;
};
exports.onProjectUpdate = onDocumentWritten(
"projects/{projectId}",
async (projectSnap) => {
@@ -53,3 +62,69 @@ exports.onProjectUpdate = onDocumentWritten(
}
}
);
exports.onProjectViewsIncrement = onDocumentWritten(
"projects/{projectId}",
async (projectSnap) => {
try {
const { projectId } = projectSnap.params;
const beforeData = projectSnap?.data?.before?.data() || null;
const afterData = projectSnap?.data?.after?.data() || null;
if (!afterData) return null;
const beforeViews =
typeof beforeData?.views === "number" && Number.isFinite(beforeData.views)
? beforeData.views
: 0;
const afterViews =
typeof afterData?.views === "number" && Number.isFinite(afterData.views)
? afterData.views
: 0;
const delta = afterViews - beforeViews;
if (delta <= 0) return null;
const userId =
typeof afterData?.userId === "string" && afterData.userId.trim().length
? afterData.userId.trim()
: null;
const now = admin.firestore.Timestamp.now();
const monthKey = buildMonthKey(now);
const statsDocRef = firestore
.collection("projectStreamStats")
.doc(projectId)
.collection("monthly")
.doc(monthKey);
await firestore.runTransaction(async (transaction) => {
const statsSnapshot = await transaction.get(statsDocRef);
const updatePayload = {
projectId,
userId,
monthKey,
updatedAt: now,
lastStreamAt: now,
lastDelta: delta,
streams: admin.firestore.FieldValue.increment(delta),
};
const hasFirstStream =
statsSnapshot.exists && statsSnapshot.data()?.firstStreamAt;
if (!hasFirstStream) {
updatePayload.firstStreamAt = now;
}
transaction.set(statsDocRef, updatePayload, { merge: true });
});
return null;
} catch (error) {
console.log("onProjectViewsIncrement error", {
message: error?.message || String(error || ""),
});
return null;
}
}
);