๐Ÿ”” Setup push notifikasi

Dikerjakan sekali saja, sekitar 10 menit. Paling nyaman lewat laptop atau browser tablet. Setelah selesai, kamu dapat satu notifikasi per hari (default jam 08:00 WIB) walaupun aplikasi tertutup, berisi parcel dan tanggal order yang hampir jatuh tempo.

1Buat tabel

  1. Buka Supabase โ†’ SQL Editor โ†’ New query.
  2. Tekan Salin di bawah, tempel, lalu Run.
  3. Cek baris paling bawah. Kalau editor menambah tanda kurung atau kutip ekstra, hapus dulu sebelum Run.
SQL 1: tabel
create table if not exists public.push_subs (
  id bigint generated always as identity primary key,
  user_id uuid not null default auth.uid() references auth.users(id) on delete cascade,
  endpoint text not null unique,
  p256dh text not null,
  auth text not null,
  created_at timestamptz not null default now()
);
alter table public.push_subs enable row level security;
create policy "own push subs" on public.push_subs
  for all to authenticated
  using (user_id = auth.uid())
  with check (user_id = auth.uid());
create table if not exists public.push_config (
  id int primary key default 1 check (id = 1),
  vapid_public text,
  vapid_private text,
  cron_key text not null default replace(gen_random_uuid()::text, '-', '') || replace(gen_random_uuid()::text, '-', ''),
  tz text not null default 'Asia/Jakarta'
);
alter table public.push_config enable row level security;
insert into public.push_config (id) values (1) on conflict (id) do nothing;
Hanya dijalankan sekali. Kalau muncul "already exists", berarti sudah pernah dijalankan.

2Buat Edge Function

  1. Menu Edge Functions โ†’ Deploy a new function โ†’ Via Editor.
  2. Nama function harus persis: send-due-push
  3. Hapus semua isi contoh, tempel kode di bawah, lalu Deploy.
Kode function
// @ts-nocheck
// svtlogis: sends push reminders (storage deadlines + pre-order dates).
// No external libraries. Web Push encryption (RFC 8291) + VAPID (RFC 8292) use the built-in WebCrypto.

const SB = Deno.env.get("SUPABASE_URL");
const SECRET = Deno.env.get("SERVICE_KEY") || Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") || firstSecret();
const SUBJECT = "https://svtlogistrack.netlify.app";
const enc = new TextEncoder();

function firstSecret() {
  try {
    const o = JSON.parse(Deno.env.get("SUPABASE_SECRET_KEYS") || "{}");
    return Object.values(o)[0] || "";
  } catch (e) { return ""; }
}
const CORS = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type, x-cron-key",
  "Access-Control-Allow-Methods": "POST, OPTIONS",
};
const json = (o, s = 200) => new Response(JSON.stringify(o), { status: s, headers: { ...CORS, "Content-Type": "application/json" } });
const dbHeaders = () => String(SECRET).startsWith("sb_secret_")
  ? { apikey: SECRET, "Content-Type": "application/json" }
  : { apikey: SECRET, Authorization: "Bearer " + SECRET, "Content-Type": "application/json" };
const db = (path, opt = {}) => fetch(SB + "/rest/v1/" + path, { ...opt, headers: { ...dbHeaders(), ...(opt.headers || {}) } });
const rows = async (path) => { const r = await db(path); const j = await r.json(); if (!r.ok) throw new Error(j.message || ("database " + r.status)); return j; };

const b64u = (buf) => { const b = new Uint8Array(buf); let s = ""; for (const x of b) s += String.fromCharCode(x); return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); };
const unb64u = (s) => { s = String(s).replace(/-/g, "+").replace(/_/g, "/"); while (s.length % 4) s += "="; return Uint8Array.from(atob(s), (c) => c.charCodeAt(0)); };
const cat = (...a) => { const o = new Uint8Array(a.reduce((t, x) => t + x.length, 0)); let p = 0; for (const x of a) { o.set(x, p); p += x.length; } return o; };
async function hkdf(salt, ikm, info, len) {
  const k = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]);
  return new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info }, k, len * 8));
}

export async function encryptPayload(sub, text) {
  const uaPub = unb64u(sub.p256dh), auth = unb64u(sub.auth);
  const eph = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]);
  const asPub = new Uint8Array(await crypto.subtle.exportKey("raw", eph.publicKey));
  const uaKey = await crypto.subtle.importKey("raw", uaPub, { name: "ECDH", namedCurve: "P-256" }, false, []);
  const secret = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: uaKey }, eph.privateKey, 256));
  const ikm = await hkdf(auth, secret, cat(enc.encode("WebPush: info\0"), uaPub, asPub), 32);
  const salt = crypto.getRandomValues(new Uint8Array(16));
  const cek = await hkdf(salt, ikm, enc.encode("Content-Encoding: aes128gcm\0"), 16);
  const nonce = await hkdf(salt, ikm, enc.encode("Content-Encoding: nonce\0"), 12);
  const key = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
  const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, key, cat(enc.encode(text), new Uint8Array([2]))));
  return cat(salt, new Uint8Array([0, 0, 0x10, 0]), new Uint8Array([asPub.length]), asPub, ct);
}

export async function makeVapid() {
  const kp = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);
  const pub = new Uint8Array(await crypto.subtle.exportKey("raw", kp.publicKey));
  const jwk = await crypto.subtle.exportKey("jwk", kp.privateKey);
  return { publicKey: b64u(pub), privateJwk: JSON.stringify(jwk) };
}

export async function vapidAuth(cfg, endpoint) {
  const hdr = b64u(enc.encode(JSON.stringify({ typ: "JWT", alg: "ES256" })));
  const pl = b64u(enc.encode(JSON.stringify({ aud: new URL(endpoint).origin, exp: Math.floor(Date.now() / 1000) + 12 * 3600, sub: SUBJECT })));
  const key = await crypto.subtle.importKey("jwk", JSON.parse(cfg.vapid_private), { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
  const sig = new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, enc.encode(hdr + "." + pl)));
  return "vapid t=" + hdr + "." + pl + "." + b64u(sig) + ", k=" + cfg.vapid_public;
}

const daysBetween = (a, b) => Math.round((Date.parse(b + "T00:00:00Z") - Date.parse(a + "T00:00:00Z")) / 864e5);
const todayIn = (tz) => new Date().toLocaleDateString("en-CA", { timeZone: tz || "Asia/Jakarta" });

export function buildDigest(items, today, T) {
  const list = [];
  for (const it of items || []) {
    const n = daysBetween(today, it.d);
    if (!(n >= -3 && n <= T)) continue;
    list.push({ ...it, n });
  }
  list.sort((a, b) => a.n - b.n);
  if (!list.length) return null;
  const when = (n) => n < 0 ? (-n) + "d late" : n === 0 ? "Today" : n === 1 ? "Tomorrow" : "in " + n + "d";
  const what = (it) => it.t === "p" ? "storage ends" : it.k;
  const lines = list.slice(0, 4).map((x) => when(x.n) + " ยท " + x.c + " ยท " + x.i + " ยท " + what(x));
  if (list.length > 4) lines.push("+" + (list.length - 4) + " more");
  return { title: "๐Ÿ”” svtlogis: " + list.length + " need" + (list.length === 1 ? "s" : "") + " attention", body: lines.join("\n"), count: list.length };
}

async function getConfig() {
  let c = (await rows("push_config?id=eq.1&select=*"))[0];
  if (!c) {
    await db("push_config", { method: "POST", headers: { Prefer: "resolution=ignore-duplicates" }, body: JSON.stringify({ id: 1 }) });
    c = (await rows("push_config?id=eq.1&select=*"))[0];
  }
  if (!c) throw new Error("push_config table is missing. Run the first SQL step.");
  if (!c.vapid_public || !c.vapid_private) {
    const k = await makeVapid();
    await db("push_config?id=eq.1", { method: "PATCH", body: JSON.stringify({ vapid_public: k.publicKey, vapid_private: k.privateJwk }) });
    c.vapid_public = k.publicKey; c.vapid_private = k.privateJwk;
  }
  return c;
}

async function userFromToken(req) {
  const auth = req.headers.get("authorization") || "";
  if (!auth.toLowerCase().startsWith("bearer ")) return null;
  const r = await fetch(SB + "/auth/v1/user", { headers: { Authorization: auth, apikey: req.headers.get("apikey") || SECRET } });
  if (!r.ok) return null;
  const u = await r.json();
  return u && u.id ? u : null;
}

async function sendTo(subs, payload, cfg) {
  const text = JSON.stringify(payload);
  let sent = 0, failed = 0; const gone = [], errors = [];
  for (const s of subs) {
    try {
      const body = await encryptPayload(s, text);
      const r = await fetch(s.endpoint, { method: "POST", headers: { Authorization: await vapidAuth(cfg, s.endpoint), "Content-Encoding": "aes128gcm", "Content-Type": "application/octet-stream", TTL: "43200", Urgency: "high" }, body });
      if (r.status === 404 || r.status === 410) gone.push(s.endpoint);
      else if (r.ok) sent++;
      else { failed++; errors.push(r.status); }
    } catch (e) { failed++; errors.push(String(e && e.message || e)); }
  }
  for (const ep of gone) await db("push_subs?endpoint=eq." + encodeURIComponent(ep), { method: "DELETE" });
  return { sent, removed: gone.length, failed, errors };
}

async function runAll(cfg) {
  const subs = await rows("push_subs?select=user_id,endpoint,p256dh,auth");
  const by = {};
  for (const s of subs) (by[s.user_id] = by[s.user_id] || []).push(s);
  const today = todayIn(cfg.tz), out = [];
  for (const uid of Object.keys(by)) {
    const r = (await rows("tracker_rows?user_id=eq." + uid + "&kind=eq.remind&id=eq.main&deleted=eq.false&select=data"))[0];
    const d = r && r.data;
    if (!d) continue;
    const dg = buildDigest(d.items, today, d.days || 3);
    if (!dg) continue;
    out.push({ user: uid, count: dg.count, ...(await sendTo(by[uid], { title: dg.title, body: dg.body, tag: "due-" + today }, cfg)) });
  }
  return { today, results: out };
}

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response("ok", { headers: CORS });
  let body = {};
  try { body = await req.json(); } catch (e) {}
  try {
    const cfg = await getConfig();
    if (body.action === "key") return json({ publicKey: cfg.vapid_public });
    if (body.action === "run") {
      if (req.headers.get("x-cron-key") !== cfg.cron_key) return json({ error: "forbidden" }, 403);
      return json(await runAll(cfg));
    }
    if (body.action === "test") {
      const u = await userFromToken(req);
      if (!u) return json({ error: "Please sign in again." }, 401);
      const subs = await rows("push_subs?user_id=eq." + u.id + "&select=endpoint,p256dh,auth");
      if (!subs.length) return json({ error: "This device is not subscribed yet." }, 404);
      return json(await sendTo(subs, { title: "svtlogis", body: "Push notifications work on this device. ๐ŸŽ‰", tag: "test" }, cfg));
    }
    return json({ error: "unknown action" }, 400);
  } catch (e) {
    return json({ error: String(e && e.message || e) }, 500);
  }
});
Kode ini tidak memakai library luar dan tidak berisi kunci rahasia.

3Matikan "Verify JWT"

Buka function send-due-push โ†’ tab Details atau Settings โ†’ matikan Verify JWT (kadang tertulis "Verify JWT with legacy secret") โ†’ Save.

Langkah ini penting. Kalau lupa, jadwal harian akan ditolak dengan error 401.

4Pasang jadwal harian

Buka SQL Editor โ†’ New query, tempel, lalu Run.

SQL 2: jadwal
create extension if not exists pg_cron;
create extension if not exists pg_net;
select cron.schedule(
  'due-push-daily',
  '0 1 * * *',
  $$select net.http_post(
    url := 'https://wdzyvlllabhapnablffu.supabase.co/functions/v1/send-due-push',
    headers := jsonb_build_object('Content-Type', 'application/json', 'apikey', 'sb_publishable_RtD7GJUbPzSJ6O-GmaWwhA_yFoGCAWA', 'x-cron-key', (select cron_key from public.push_config where id = 1)),
    body := '{"action":"run"}'::jsonb,
    timeout_milliseconds := 30000
  )$$
);

Jam 0 1 * * * memakai waktu UTC. 01:00 UTC = 08:00 WIB. Mau 07:00 WIB? Ganti 1 jadi 0. Pengaturan ini juga membuat extension pg_cron dan pg_net (kalau minta izin, aktifkan di Database โ†’ Extensions).

5Nyalakan di aplikasi

  1. Upload versi terbaru aplikasi ke Netlify, lalu buka aplikasinya dan login ke Cloud sync.
  2. Buka menu โ˜ฐ โ†’ Reminders โ†’ nyalakan Push notifications โ†’ pilih Izinkan.
  3. Tekan Send test push. Notifikasi "Push notifications work on this device" harus muncul.
  4. Lakukan juga di HP atau tablet lain yang mau menerima notifikasi.
iPhone / iPad: aplikasi harus dipasang ke Home Screen dulu (iOS 16.4 ke atas), lalu nyalakan push dari ikon di Home Screen, bukan dari Safari.

6Coba sekarang tanpa menunggu pagi (opsional)

Jalankan SQL ini, tunggu sekitar 10 detik, lalu jalankan SQL cek di bawahnya.

SQL 3: jalankan sekarang
select net.http_post(
    url := 'https://wdzyvlllabhapnablffu.supabase.co/functions/v1/send-due-push',
    headers := jsonb_build_object('Content-Type', 'application/json', 'apikey', 'sb_publishable_RtD7GJUbPzSJ6O-GmaWwhA_yFoGCAWA', 'x-cron-key', (select cron_key from public.push_config where id = 1)),
    body := '{"action":"run"}'::jsonb,
    timeout_milliseconds := 30000
  );
SQL 4: lihat hasilnya
select status_code, content, created
from net._http_response
order by created desc
limit 3;

Kolom content berisi hasil seperti {"today":"...","results":[{"sent":1}]}. Kalau tidak ada parcel atau tanggal order yang dekat, results kosong dan tidak ada notifikasi, itu normal.

๐Ÿ” Cek function (kalau tombol test gagal)

Buka alamat ini langsung di browser (cukup diketuk, tidak perlu login):

Alamat function
https://wdzyvlllabhapnablffu.supabase.co/functions/v1/send-due-push

Lihat tulisan yang muncul, lalu cocokkan:

Di dashboard, buka Edge Functions โ†’ send-due-push โ†’ tab Logs atau Invocations untuk melihat permintaan dari aplikasi beserta kode statusnya.

Aturan notifikasinya

Kalau ada masalah

SQL 5: cek jadwal
select jobid, jobname, schedule, active from cron.job;
select status, return_message, start_time
from cron.job_run_details
order by start_time desc
limit 5;

Halaman ini tidak berisi data pribadi atau kunci rahasia.