const DB_COLLECTION = 'plank_data' const ENV_ID = 'cloudbase-d1g56kl2q8f4f7d8a' let _db = null let _pushTimer = null let _enabled = false let _docId = null // cache doc id after first successful query const getDb = () => { if (!_enabled) return null if (!_db) { try { _db = wx.cloud.database({ env: ENV_ID }) } catch (e) { _enabled = false } } return _db } const init = () => { try { wx.cloud.init({ env: ENV_ID, traceUser: true }) _enabled = true } catch (e) { _enabled = false } } const pullAll = async () => { const db = getDb() if (!db) return null try { // First try cached doc id if (_docId) { try { const res = await db.collection(DB_COLLECTION).doc(_docId).get() if (res && res.data) return res.data } catch (e) { _docId = null // doc deleted or inaccessible } } // Query: rely on security rules to scope to current user const res = await db.collection(DB_COLLECTION).limit(1).get() if (res && res.data && res.data.length > 0) { _docId = res.data[0]._id return res.data[0] } return null } catch (e) { return null } } const pushAll = () => { if (!_enabled) return if (_pushTimer) clearTimeout(_pushTimer) _pushTimer = setTimeout(() => _doPush(), 2000) } const _doPush = async () => { const db = getDb() if (!db) return try { const storage = require('./storage') const themeMod = require('./theme') const data = { records: storage.getRecords(), settings: storage.getSettings(), streak: storage.getStreak(), customPlans: storage.getCustomPlans(), themeId: themeMod.getCurrentTheme().id, updatedAt: db.serverDate() } // Use cached doc id if available if (_docId) { try { await db.collection(DB_COLLECTION).doc(_docId).update({ data }) return } catch (e) { _docId = null // doc may have been deleted } } // Query for existing doc (relies on security rules to scope to current user) const existing = await db.collection(DB_COLLECTION).limit(1).get() if (existing && existing.data && existing.data.length > 0) { _docId = existing.data[0]._id await db.collection(DB_COLLECTION).doc(_docId).update({ data }) } else { const res = await db.collection(DB_COLLECTION).add({ data }) if (res && res._id) _docId = res._id } } catch (e) { // Silently retry on next write } } const clearAll = async () => { const db = getDb() if (!db) return try { if (_docId) { try { await db.collection(DB_COLLECTION).doc(_docId).remove() _docId = null return } catch (e) { _docId = null } } const existing = await db.collection(DB_COLLECTION).limit(1).get() if (existing && existing.data && existing.data.length > 0) { await db.collection(DB_COLLECTION).doc(existing.data[0]._id).remove() } _docId = null } catch (e) { // Nothing to clear } } module.exports = { init, pullAll, pushAll, clearAll, get enabled() { return _enabled } }