Re:Turn

Zero-friction circular container borrowing & incentive system.

|

System Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│                           Re:Turn System                                │
│                                                                         │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────────────────┐  │
│  │   LINE App    │    │  NFC + Raspi │    │   Raspi Display           │  │
│  │  (User Phone) │    │  (Borrow/Ret)│    │   (Leaderboard + CO2)     │  │
│  │               │    │              │    │                           │  │
│  │ Borrow LIFF ──┼────┤ NFC tag scan │    │ Flask SSE ← return_core   │  │
│  │ Dashboard ────┼──┐ │ return POST  │    │ UI polls GAS getStats     │  │
│  └───────────────┘  │ └──────┬───────┘    └────────────┬─────────────┘  │
│                     │        │                         │                 │
│                     │ LIFF   │ HTTP POST               │ HTTP GET        │
│                     │ SDK v2 │                         │                 │
│                     ▼        ▼                         ▼                 │
│  ┌──────────────────────────────────────────────────────────────────┐  │
│  │                   Google Apps Script (GAS)                        │  │
│  │  ┌─────────────┐  ┌──────────────┐  ┌────────────────────────┐   │  │
│  │  │ doPost()    │  │ doGet()      │  │ sendLineMessage()      │   │  │
│  │  │ • borrow    │  │ • getStats   │  │ LINE Messaging API     │   │  │
│  │  │ • return    │  │ • getDashboard│  │ Push notifications    │   │  │
│  │  │ • updateName│  │              │  │                        │   │  │
│  │  │ • getDashboard│ │              │  │                        │   │  │
│  │  └──────┬──────┘  └──────┬───────┘  └────────────┬───────────┘   │  │
│  └─────────┼────────────────┼───────────────────────┼───────────────┘  │
│            │                │                       │                   │
│            ▼                ▼                       ▼                   │
│  ┌──────────────────────────────────────────────────────────────────┐  │
│  │                     Google Sheets (Database)                      │  │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐                       │  │
│  │  │  Users   │  │   Logs   │  │ Mapping  │                       │  │
│  │  └──────────┘  └──────────┘  └──────────┘                       │  │
│  └──────────────────────────────────────────────────────────────────┘  │
│                                                                         │
│  ┌──────────────────────────────────────────────────────────────────┐  │
│  │                    LIFF Frontends (Browser)                       │  │
│  │  GitHub Pages → liff.line.me/2008626930-pLAvndnp                  │  │
│  │  ┌────────────┐  ┌──────────┐  ┌──────────┐                     │  │
│  │  │ index.html │  │ style.css│  │  app.js  │                     │  │
│  │  └────────────┘  └──────────┘  └──────────┘                     │  │
│  └──────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────┘

Data Flow

BORROW:  NFC/Raspi → GAS doPost(action=borrow)     → Sheets(Logs+Users) → LINE Push(user)
RETURN:  NFC/Raspi → GAS doPost(action=return)     → Sheets(Logs)      → LINE Push(user)
DASHBOARD: User opens LIFF → GAS doGet/getDashboard → Sheets(Users+Logs) → LIFF renders
LEADERBOARD: Raspi display → GAS doGet(getStats)   → Sheets(Users)     → Raspi renders

Component Index

1a. Borrow LIFF (Student Borrow Screen)

Repo: return-sfc/return-liff-frontend  ·  LIFF ID: 2008626930-AddPwDy7

return-liff-frontend/
├── index.html         # Full app (inline CSS + JS): splash → borrow → success + leaderboard
├── nfc-simulator.html # Dev tool: simulates NFC tap for testing GAS return endpoint
├── sfc_logo.png       # Keio SFC logo
└── megloo_logo.png    # Megloo project logo
FeatureDetail
EntryQR code with ?id=C-001 parameter
SplashGreen fullscreen "Re:Turn" + welcome message, 1.8s fade-out
GAS CallPOST borrow with userId + containerId
Success ViewCO2 counter animation (36g/borrow, cumulative; = 1 paper container avoided, Megloo LCA), eco metaphor text
LeaderboardDark card with slam-in animation + confetti + shake effect
Name Edit8-char uppercase modal, saves to localStorage + GAS updateName
LIFF AuthFull LIFF init → ID token → login flow; localhost bypass for dev

Flow: QR scan → LIFF opens → splash fades → student sees container ID → taps "はい" → GAS borrow → confetti + leaderboard slam-in

1b. Dashboard LIFF (User Status Dashboard)

Repo: return-sfc/return-incentive-collection-system  ·  LIFF ID: 2008626930-pLAvndnp

return-incentive-collection-system/
├── index.html                     # App shell: Profile + Current Borrowing + Task Center
├── style.css                      # Light/fresh theme, CSS variables, mobile-first
├── app.js                         # LIFF init, GAS fetch, render logic, points = usageCount × 10
└── line-entry/
    ├── rich-menu-preview.html     # Canvas PNG generator for Rich Menu (2500×843)
    └── rich-menu-config.json      # Single full-width button tap area
FeatureDetail
EntryLINE Rich Menu button → LIFF URL
Profile CardAvatar + display name + masked user ID
StatsPoints (= usageCount × 10) + Total Uses
Current BorrowingList of unreturned containers with borrow time, or "All cleared!"
Task CenterPlaceholder: "Intensive Collection" map/lock-acquire (coming soon)

2. GAS Backend (API Server)

WhatActionMethodCalled ByDescription
BorrowborrowPOSTNFC/RaspiRecord borrow, update user count, push LINE confirmation
ReturnreturnPOSTNFC/RaspiRecord return via NFC→containerId lookup, push LINE confirmation
Update NameupdateNamePOSTLIFF FrontendUpdate user display name in Users sheet
DashboardgetDashboardPOST/GETLIFF FrontendReturn userName, usageCount, currently borrowed items
StatsgetStatsGETRaspi DashboardReturn totalBorrows + top 5 leaderboard

Deploy: Google Apps Script → ***HIDDEN***  ·  Code: Google Apps Script Editor (***HIDDEN***)

3. Google Sheets (Database)

Spreadsheet ID: ***HIDDEN***    📊 Open Sheets

SheetColumnsPurpose
UsersuserId, score, userName, lastActiveUser registry & global stats
LogsrecordId, containerId, userId, borrowTimestamp, returnTimestamp, status, notesAll borrow/return transactions
MappingnfcId, containerIdNFC tag → container ID lookup

Status values in Logs: BORROWED, RETURNED, ERROR_CLOSED, ERROR_RETURN

4. NFC + Raspberry Pi Station (Return & Leaderboard)

Repo: return-sfc/return_system (private)  ·  GitFront mirror: gitfront.io

ProcessFileRole
NFC Daemonreturn_core.pyContinuous NFC tag scanning, local Flask trigger, async GAS POST
Flask Serverapp.pyWeb UI server + SSE push + leaderboard display

Design: Two-process — NFC daemon (bare-metal, 20ms scan) + Flask/SSE server. SSE pushes to browser in <200ms from tag tap.

5. LINE Bot (Push Notifications)

WhatTriggerMessage
Borrow ConfirmAfter handleBorrowUser rank + borrow count + return deadline
Return ConfirmAfter handleReturnReturn acknowledgement
NFC Miss WarningERROR_CLOSED detectedWarns previous borrower about failed NFC scan

Channel: LINE Developers Console  ·  Implementation: sendLineMessage() in GAS

API Contracts

getDashboard

Request: GET ?action=getDashboard&userId=<userId>&userName=<displayName> Response: { status: "success", data: { userName: string, usageCount: number, borrowedItems: [{ containerId, borrowTime }] } }

getStats

Request: GET ?action=getStats Response: { status: "success", totalBorrows: number, leaderboard: [{ rank, name, score }] }

borrow

Request: POST { action: "borrow", userId: string, containerId: string } Response: { status: "success", action: "borrow", borrowCount: number, isNewUser: boolean, userRank: number, leaderboard: [{ rank, name, score }] }

return

Request: POST { action: "return", nfcId: string } Response: { status: "success", action: "return", type: "normal_return" | "unborrowed_return", userId?: string }

updateName

Request: POST { action: "updateName", userId: string, userName: string } Response: { status: "success", action: "updateName" }

Repo Map

RepoWhatGitHub
Dashboard LIFFUser status dashboardreturn-sfc/return-incentive-collection-system
Borrow LIFFStudent borrow screenreturn-sfc/return-liff-frontend
Raspi StationNFC daemon + Flask SSE + leaderboardreturn-sfc/return_system (private)
LandscapeArchitecture overview (this page)return-sfc/return-system-landscape
GAS BackendGoogle Apps Script API server***HIDDEN***

GAS Code Reference

Full GAS backend code (as of 2026-06-22). When editing, copy from here → paste into Google Apps Script Editor → Deploy as Web App.

Click to expand — Full GAS Code
// ====== Configuration ======
const SPREADSHEET_ID = '***HIDDEN***';
const LINE_CHANNEL_ACCESS_TOKEN = '***HIDDEN***';
const LOGS_SHEET_NAME = 'Logs';
const USERS_SHEET_NAME = 'Users';
const MAPPING_SHEET_NAME = 'Mapping';

// ====== POST Router ======
function doPost(e) {
  try {
    const params = JSON.parse(e.postData.contents);
    const action = params.action;
    let result = {};
    if (action === 'borrow') {
      result = handleBorrow(params.userId, params.containerId);
    } else if (action === 'return') {
      const containerId = getContainerIdByNfc(params.nfcId);
      if (!containerId) {
        return ContentService.createTextOutput(
          JSON.stringify({ status: 'error', message: 'NFC unregistered' })
        ).setMimeType(ContentService.MimeType.JSON);
      }
      result = handleReturn(containerId);
    } else if (action === 'updateName') {
      result = updateUserName(params.userId, params.userName);
    } else if (action === 'getDashboard') {
      result = getDashboard(params.userId, params.userName);
    } else {
      throw new Error("Unknown action type");
    }
    return ContentService.createTextOutput(JSON.stringify(result))
      .setMimeType(ContentService.MimeType.JSON);
  } catch (error) {
    return ContentService.createTextOutput(
      JSON.stringify({ status: 'error', message: error.toString() })
    ).setMimeType(ContentService.MimeType.JSON);
  }
}

// ====== GET Router ======
function doGet(e) {
  if (e.parameter && e.parameter.action === 'getStats') {
    return getGlobalStats();
  } else if (e.parameter && e.parameter.action === 'getDashboard') {
    const result = getDashboard(e.parameter.userId, e.parameter.userName);
    return ContentService.createTextOutput(JSON.stringify(result))
      .setMimeType(ContentService.MimeType.JSON);
  }
}

// ====== Global Stats (for Raspi leaderboard) ======
function getGlobalStats() {
  const ss = SpreadsheetApp.openById(SPREADSHEET_ID);
  const usersSheet = ss.getSheetByName(USERS_SHEET_NAME);
  const data = usersSheet.getDataRange().getValues();
  let totalBorrows = 0;
  let users = [];
  for (let i = 1; i < data.length; i++) {
    if (!data[i][0]) continue;
    let score = Number(data[i][1]) || 0;
    totalBorrows += score;
    users.push({
      name: data[i][2] || "ECO PLAYER",
      score: score,
      lastActive: new Date(data[i][3]).getTime() || 0
    });
  }
  users.sort((a, b) =>
    b.score !== a.score ? b.score - a.score : a.lastActive - b.lastActive
  );
  let top5 = users.slice(0, 5).map((u, i) => ({
    rank: i + 1, name: u.name, score: u.score
  }));
  return ContentService.createTextOutput(JSON.stringify({
    status: 'success',
    totalBorrows: totalBorrows,
    leaderboard: top5
  })).setMimeType(ContentService.MimeType.JSON);
}

// ... (handleBorrow, handleReturn, updateUserCount, etc.)
// Full code available in the README source or GAS Editor

Key Design Decisions

DecisionRationale
Points = usageCount × 10Simple, transparent — no server-side score needed
No Transaction History in LIFFRemoved until LINE API supports reliable historical data
GET for DashboardAvoids CORS preflight overhead in LINE WebView
GAS batch writes (setValues)Single I/O for multi-cell updates, ~3× faster than per-cell
Ghost occupancy detection (ERROR_CLOSED)Detects NFC scan failures on return, warns previous borrower
EN + JP bilingual messagesUser base is Japanese university students; English fallback for international
No emoji in titlesClean, professional dashboard aesthetic per user preference