# ตัวอย่างปลั๊กอิน — สมุดเยี่ยม

> สร้างปลั๊กอิน JavaScript ครบทั้งตัวทีละขั้น — ตารางข้อมูล หน้าสาธารณะในหัว/ท้ายของเว็บ ฟอร์มส่งข้อความ อีเมลแจ้งเตือน หน้าจัดการในหลังบ้าน และการตั้งค่า

ที่มา: https://anasaki.live/docs/developers/plugin-example

ตัวอย่างนี้สร้างปลั๊กอิน **สมุดเยี่ยม** (`guestbook`): ผู้เยี่ยมชมเขียนข้อความที่ `/guestbook` ผู้ดูแลได้อีเมลแจ้งเตือนและลบข้อความได้จากหลังบ้าน ใช้ API สาธารณะเท่านั้น — อ่านพื้นฐานก่อนที่ [สร้างปลั๊กอิน JavaScript](/docs/developers/js-plugins)

## 1. โครงสร้าง

```text
guestbook/
├── manifest.json
├── README.md
├── code/main.ts
└── migrations/001_create_entries.ts
```

## 2. manifest.json

```json
{
  &#34;id&#34;: &#34;guestbook&#34;,
  &#34;name&#34;: &#34;Guestbook / สมุดเยี่ยม&#34;,
  &#34;version&#34;: &#34;1.0.0&#34;,
  &#34;description&#34;: &#34;สมุดเยี่ยมให้ผู้เยี่ยมชมเขียนข้อความ / A simple guestbook&#34;,
  &#34;author&#34;: &#34;Your name&#34;,
  &#34;icon&#34;: &#34;📖&#34;,
  &#34;category&#34;: &#34;content&#34;,
  &#34;license&#34;: &#34;MIT&#34;,
  &#34;minCore&#34;: &#34;2.0.4&#34;,
  &#34;runtime&#34;: &#34;js&#34;,
  &#34;permissions&#34;: [&#34;code&#34;, &#34;settings&#34;],
  &#34;settings&#34;: [
    { &#34;key&#34;: &#34;title&#34;, &#34;type&#34;: &#34;text&#34;, &#34;default&#34;: &#34;สมุดเยี่ยม&#34;, &#34;maxLength&#34;: 100,
      &#34;label&#34;: { &#34;th&#34;: &#34;หัวข้อหน้า&#34;, &#34;en&#34;: &#34;Page title&#34; } },
    { &#34;key&#34;: &#34;notify&#34;, &#34;type&#34;: &#34;boolean&#34;, &#34;default&#34;: true,
      &#34;label&#34;: { &#34;th&#34;: &#34;ส่งอีเมลแจ้งเมื่อมีข้อความใหม่&#34;, &#34;en&#34;: &#34;Email me on new entries&#34; } }
  ],
  &#34;code&#34;: {
    &#34;entry&#34;: &#34;code/main.ts&#34;,
    &#34;scopes&#34;: [&#34;db&#34;, &#34;routes&#34;, &#34;mail&#34;, &#34;admin-pages&#34;],
    &#34;routes&#34;: [&#34;/guestbook&#34;]
  }
}
```

สิทธิ์ที่ขอ: `db` (ตารางของตัวเอง), `routes` (หน้า `/guestbook`), `mail` (แจ้งเตือน + อ่านอีเมลผู้ดูแล), `admin-pages` (หน้าจัดการ)

## 3. Migration

```ts
// migrations/001_create_entries.ts  → ตารางจริง p_guestbook_entries
export default migration({
  up(schema) {
    schema.create('entries', (t) => {
      t.id();
      t.string('name', 80);
      t.text('message');
      t.timestamps();
    });
  },
  down(schema) { schema.drop('entries'); },
});
```

## 4. โค้ด (code/main.ts)

```ts
const esc = (s: unknown) => String(s ?? '').replace(/[&<>&#34;']/g, (c) =>
  ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '&#34;': '&quot;', &#34;'&#34;: '&#39;' } as Record<string, string>)[c]);

/** application/x-www-form-urlencoded → { key: value } */
function parseForm(body: string): Record<string, string> {
  const out: Record<string, string> = {};
  for (const pair of (body || '').split('&')) {
    if (!pair) continue;
    const [k, v = ''] = pair.split('=');
    out[decodeURIComponent(k.replace(/\+/g, ' '))] = decodeURIComponent(v.replace(/\+/g, ' '));
  }
  return out;
}

// หน้าสาธารณะ — แสดงในหัว/ท้ายของเว็บ
site.route('GET /guestbook', { access: ['*'] }, () => {
  const title = String(site.settings('title') || 'สมุดเยี่ยม');
  const rows = db.table('entries').orderBy('id', 'desc').limit(50).get();
  const list = rows.map((r) => `<li><strong>${esc(r.name)}</strong><p>${esc(r.message)}</p></li>`).join('');
  return {
    page: {
      title,
      html: `<section class=&#34;gb&#34;><h1>${esc(title)}</h1>
        <form method=&#34;post&#34; action=&#34;/guestbook&#34;>
          <input name=&#34;name&#34; required maxlength=&#34;80&#34; placeholder=&#34;ชื่อ&#34;>
          <textarea name=&#34;message&#34; required maxlength=&#34;1000&#34; placeholder=&#34;ข้อความ&#34;></textarea>
          <button type=&#34;submit&#34;>ส่งข้อความ</button>
        </form>
        <ul>${list || '<li>ยังไม่มีข้อความ</li>'}</ul></section>`,
    },
  };
});

// รับฟอร์ม แล้วพากลับไปหน้าเดิม
site.route('POST /guestbook', { access: ['*'], maxBody: 8192 }, ({ request }) => {
  const f = parseForm(request.body);
  const name = (f.name || '').trim().slice(0, 80);
  const message = (f.message || '').trim().slice(0, 1000);
  if (name && message) {
    db.table('entries').insert({ name, message });
    const to = site.info().adminEmail;
    if (site.settings('notify') && to) {
      try {
        mail.send({ to, subject: 'ข้อความใหม่ในสมุดเยี่ยม', html: `<p><b>${esc(name)}</b>: ${esc(message)}</p>` });
      } catch (e) {
        log.warn('ส่งอีเมลไม่ได้', String(e));   // ยังไม่ได้ตั้ง SMTP
      }
    }
  }
  return { status: 303, headers: { Location: '/guestbook' } };
});

// action ที่หน้าจัดการเรียก
site.action('delete', {
  input: { id: 'number' },
  access: ['administrator', 'editor'],
  run: ({ input }) => {
    db.table('entries').where('id', input.id).delete();
    return { message: 'ลบแล้ว' };
  },
});

// หน้าจัดการในหลังบ้าน
site.adminPage('entries', {
  label: { th: 'สมุดเยี่ยม', en: 'Guestbook' }, icon: '📖', access: ['administrator', 'editor'],
  render: () => {
    const rows = db.table('entries').orderBy('id', 'desc').limit(200).get();
    const tr = rows.map((r) => `<tr><td>${esc(r.name)}</td><td>${esc(r.message)}</td>
      <td><button class=&#34;ak-btn&#34; onclick=&#34;del(${Number(r.id)})&#34;>ลบ</button></td></tr>`).join('');
    return {
      title: 'Guestbook',
      html: `<header class=&#34;ak-page-head&#34;><h1>สมุดเยี่ยม</h1></header>
        <div class=&#34;ak-table-wrap&#34;><table class=&#34;ak-table&#34;><thead><tr><th>ชื่อ</th><th>ข้อความ</th><th></th></tr></thead>
        <tbody>${tr}</tbody></table></div>
        <script>
          async function del(id) {
            if (!(await AK.confirm('ลบข้อความนี้?', { danger: true }))) return;
            anasaki.call('guestbook:delete', { id }).then(() => location.reload(), (e) => AK.toast(e.message, 'error'));
          }
        </script>`,
    };
  },
});
```

> [!NOTE]
> ในหน้าจัดการของปลั๊กอิน ชื่อ action ต้องมี namespace ของปลั๊กอิน (`guestbook:delete`) และ `anasaki.call` คืน Promise ที่ reject เมื่อ action ล้ม ส่วนชุดคลาส `ak-*` และ `AK.confirm` / `AK.toast` มาจาก admin UI kit ที่ระบบใส่ให้ทุกหน้า

## 5. ติดตั้งและทดสอบ

1. zip โฟลเดอร์: `cd guestbook && zip -r ../guestbook-1.0.0.zip .`
2. **ปลั๊กอิน → อัปโหลด .zip** → ตรวจสิทธิ์ 4 รายการ → **อนุมัติและติดตั้ง** → **เปิดใช้งาน** (migration รันตอนนี้)
3. เปิด `https://เว็บของคุณ/guestbook` แล้วลองส่งข้อความ
4. เมนู **สมุดเยี่ยม** ปรากฏในหลังบ้าน — ลองลบข้อความ
5. **ปลั๊กอิน → Guestbook → ตั้งค่า** เปลี่ยนหัวข้อหน้า แล้วรีเฟรช `/guestbook`
6. มีปัญหา? ดู **โค้ดของเว็บไซต์ → บันทึกการทำงาน** (log ของปลั๊กอินขึ้นต้นด้วย `guestbook:`)

## 6. ต่อยอด

- ให้ผู้ออกแบบวางรายการข้อความในหน้าใดก็ได้ด้วย `site.collection('entries', { … access: ['*'] })` แล้วเลือกแหล่งข้อมูลในชิ้น **รายการข้อมูล** ([ผูกข้อมูลกับหน้าออกแบบ](/docs/developers/designer-bindings))
- กันสแปมด้วยช่องหลอก (honeypot) และนับการส่งต่อ IP ด้วย `request.ip`
- ให้ปลั๊กอินอื่นรับรู้ข้อความใหม่: ประกาศ `&#34;hooks&#34;: { &#34;events&#34;: [&#34;guestbook.created&#34;] }` แล้ว `site.emit('guestbook.created', { id })`
- พร้อมแจกจ่าย: เขียน README ไทย/อังกฤษ เพิ่มรูปใน `screenshots/` แล้ว [เผยแพร่บน Plugin Store](/docs/store/publish-plugin)

ตัวอย่างเพิ่มเติมใน repository: `examples/js-plugins/` (`thai`, `promptpay`, `files`, `admin-crud`, `members`, `money` + `shop`) และซอร์สของปลั๊กอินทางการใน `plugins-official/`
