D
Engineering

chat_histories Collection

Koleksi chat_histories — sesi percakapan per nomor. Dibuat otomatis saat pesan masuk bila belum ada yang aktif. Filter store_id + instance + nohp + end_date null + status != close.

Koleksi chat_histories menyimpan sesi percakapan per nomor WhatsApp. Dibuat otomatis oleh engine saat ada pesan masuk, bila belum ada sesi aktif untuk kombinasi store_id + instance + nohp.

Model

src/model/chatHistory.model.ts:

ts
const MoveHistorySchema = new Schema<MoveHistoryItem>(
  {
    team_id: { type: String, required: false },
    team_role: { type: String, required: false },
    date: { type: Date, default: Date.now },
  },
  { _id: false },
);

const ChatHistorySchema = new Schema<ChatHistoryCollection>(
  {
    id: { type: String, required: true, index: true },
    store_id: { type: String, required: true },
    instance: { type: String, required: true },
    nohp: { type: String, required: true },
    customer_id: { type: String, default: '' },
    status: { type: String, default: 'open' },
    chat_status: { type: String, default: 'new' },
    chat_start: { type: String },
    end_date: { type: Date, default: null },
    move_history: { type: [MoveHistorySchema], default: [], required: false },
    created_at: { type: Date, default: null },
    updated_at: { type: Date, default: null },
  },
  {
    timestamps: {
      createdAt: 'created_at',
      updatedAt: 'updated_at',
    },
  },
);

export const ChatHistoryModel = model<ChatHistoryCollection>(
  'chat_histories',
  ChatHistorySchema,
);

Field

FieldTipeWajibIndexCatatan
idString✅✅UUID — primary key logis
store_idString✅—ID store/toko (dari devices)
instanceString✅—instanceId — key ke sesi WhatsApp
nohpString✅—Nomor HP format +628... (prefix +)
customer_idString❌—ID customer (default '')
statusString❌—Status sesi: "open" / "close" (default "open")
chat_statusString❌—Status chat: "new", dll. (default "new")
chat_startString❌—ID pesan pertama (messageId dari Baileys)
end_dateDate❌—Timestamp sesi ditutup (default null = masih aktif)
move_history[MoveHistoryItem]❌—Array riwayat perpindahan team — { team_id, team_role, date }
created_atDateauto—Timestamp create (via Mongoose timestamps)
updated_atDateauto—Timestamp update (via Mongoose timestamps)
_idObjectIdauto—Mongo default

move_history subdocument

ts
interface MoveHistoryItem {
  team_id: string;
  team_role: string;
  date: Date;
}

{ _id: false } — subdocument tidak generate _id sendiri.

Cara engine memakai

src/service/chatHistory/chatHistoryService.ts:13-104 — manageChatHistory(instanceId, remoteJid, messageId) dipanggil di setiap processMessage:

Alur

  1. Format nomor: waformated = '+' + remoteJid.split('@')[0] → +628123456789
  2. Cari device: DeviceModel.findOne({ id: instanceId })
  3. Jika device tidak ada → return (tidak buat history)
  4. Ambil store_id dari device
  5. Cari existing history dengan filter:
ts
const filterHistory = {
  store_id: device.store_id,
  instance: instanceId,
  nohp: waformated,           // format +628...
  end_date: null,             // masih aktif
  status: { $ne: 'close' },   // tidak close
};

const existChatHistory = await ChatHistoryModel.findOne(filterHistory);
  1. Jika tidak ada → buat baru:
ts
const created = await ChatHistoryModel.create({
  store_id: device.store_id,
  instance: instanceId,
  customer_id: '',
  nohp: waformated,
  status: 'open',
  chat_status: 'new',
  chat_start: messageId,    // ID pesan pertama
  id: uuidv4(),
});
  1. Jika ada → skip (tidak duplikat)

Format nomor

Nomor disimpan dengan format +628... (prefix + lalu nomor tanpa @s.whatsapp.net):

ts
const waformated = '+' + remoteJid.split('@')[0];
// "628123456789@s.whatsapp.net" → "+628123456789"

Berbeda dari format di chat_inbox (yang memakai nohp tanpa prefix +). Konsistensi format penting untuk query.

Shared dengan

ServiceAkses
engine-whatsapp✅ Create (saat pesan masuk)
backend-goRead/write (update status, end_date, dll.)

Inkonsistensi yang diketahui

MasalahDetail
Tidak ada compound indexQuery filter store_id + instance + nohp + end_date + status tanpa compound index — scan penuh
move_history dikomentariCode yang mencari lastHistory.move_history dari sesi sebelumnya dikomentari — move_history default []
Banyak console.log debugchatHistoryService.ts:20-99 punya banyak [HISTORY] log — sebagian verbose

Lihat Tech Debt.

Contoh dokumen

json
{
  "_id": "65a1b2c3d4e5f6a7b8c9d0e4",
  "id": "uuid-123-456-789",
  "store_id": "store-456",
  "instance": "0c1a968c-7918-4c29-a524-0ad7c445ee7f",
  "nohp": "+628123456789",
  "customer_id": "",
  "status": "open",
  "chat_status": "new",
  "chat_start": "3EB0...",
  "end_date": null,
  "move_history": [],
  "created_at": "2024-01-15T10:30:00.000Z",
  "updated_at": "2024-01-15T10:30:00.000Z",
  "__v": 0
}

Langkah berikutnya