Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,22 @@
│ ├── telegram-ecash-escrow # NextJS App
├── packages
│ ├── api # Shared API config & models
├── docs # 📚 Technical documentation
└── ...
```

## Documentation

Comprehensive technical documentation is available in the [`docs`](./docs) folder:

- **Feature Implementation**: Complete guides for new features
- **Backend Changes**: API specifications and implementation guides
- **Bug Fixes**: Detailed bug fix documentation with examples
- **Testing Plans**: Test scenarios and procedures
- **Critical Issues**: Active issues requiring immediate attention

See [`docs/README.md`](./docs/README.md) for the complete documentation index.

## Development

You can run all apps at once:
Expand Down
108 changes: 108 additions & 0 deletions apps/telegram-ecash-escrow/src/app/api/alerts/telegram/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { NextRequest, NextResponse } from 'next/server';

/**
* Send critical alerts to Telegram channel or group
* POST /api/alerts/telegram
*
* Works with both:
* - Telegram Channels (one-way broadcast)
* - Telegram Groups (team discussion)
*
* Body: {
* message: string,
* severity: 'critical' | 'error' | 'warning' | 'info',
* service: string,
* details?: any
* }
*/
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { message, severity = 'error', service, details } = body;

// Get Telegram configuration from environment
const botToken = process.env.BOT_TOKEN;
const alertChannelId = process.env.TELEGRAM_ALERT_CHANNEL_ID;

if (!botToken) {
console.error('BOT_TOKEN not configured in environment variables');
return NextResponse.json({ error: 'Telegram bot token not configured' }, { status: 500 });
}

if (!alertChannelId) {
console.warn('TELEGRAM_ALERT_CHANNEL_ID not configured - alert not sent');
return NextResponse.json({ warning: 'Alert channel/group not configured', messageSent: false }, { status: 200 });
}

// Format the message with severity emoji
const severityEmojis = {
critical: '🚨',
error: '❌',
warning: '⚠️',
info: 'ℹ️'
};

const emoji = severityEmojis[severity as keyof typeof severityEmojis] || '❌';

// Build the alert message
let alertMessage = `${emoji} *${severity.toUpperCase()}*: ${service}\n\n`;
alertMessage += `${message}\n\n`;

if (details) {
alertMessage += `*Details:*\n\`\`\`\n${JSON.stringify(details, null, 2)}\n\`\`\`\n\n`;
}

alertMessage += `*Time:* ${new Date().toISOString()}\n`;
alertMessage += `*Environment:* ${process.env.NODE_ENV || 'unknown'}`;

// Send to Telegram using Bot API
const telegramApiUrl = `https://api.telegram.org/bot${botToken}/sendMessage`;

const telegramResponse = await fetch(telegramApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: alertChannelId,
text: alertMessage,
parse_mode: 'Markdown',
disable_web_page_preview: true
})
});

const telegramData = await telegramResponse.json();

if (!telegramResponse.ok) {
console.error('Failed to send Telegram alert:', telegramData);
return NextResponse.json(
{
error: 'Failed to send Telegram alert',
details: telegramData
},
{ status: 500 }
);
}

console.log('Telegram alert sent successfully:', {
service,
severity,
messageId: telegramData.result?.message_id
});

return NextResponse.json({
success: true,
messageSent: true,
messageId: telegramData.result?.message_id
});
} catch (error) {
console.error('Error sending Telegram alert:', error);
return NextResponse.json(
{
error: 'Internal server error',
message: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { NextRequest, NextResponse } from 'next/server';

/**
* Helper endpoint to get Telegram chat IDs for setup
* GET /api/telegram/get-chat-ids
*
* This is a temporary endpoint to help you find your group/channel ID
* Remove this file after you've configured TELEGRAM_ALERT_CHANNEL_ID
*/
export async function GET(request: NextRequest) {
const botToken = process.env.BOT_TOKEN;

if (!botToken) {
return NextResponse.json(
{
error: 'BOT_TOKEN not configured',
message: 'Please set BOT_TOKEN in your .env file'
},
{ status: 500 }
);
}

try {
// Get recent updates from Telegram
const response = await fetch(`https://api.telegram.org/bot${botToken}/getUpdates`, { cache: 'no-store' });

if (!response.ok) {
throw new Error(`Telegram API returned ${response.status}`);
}

const data = await response.json();

if (!data.ok) {
return NextResponse.json(
{
error: 'Telegram API error',
details: data
},
{ status: 500 }
);
}

// Extract chat information from updates
const chats = new Map();

data.result.forEach((update: any) => {
const chat = update.message?.chat || update.my_chat_member?.chat;
if (chat) {
chats.set(chat.id, {
id: chat.id,
title: chat.title || chat.first_name || 'Unknown',
type: chat.type,
username: chat.username
});
}
});

const chatList = Array.from(chats.values());

// Separate by type
const groups = chatList.filter(c => c.type === 'group' || c.type === 'supergroup');
const channels = chatList.filter(c => c.type === 'channel');
const privateChats = chatList.filter(c => c.type === 'private');

return NextResponse.json({
success: true,
message: 'Chat IDs found! Copy the ID you need and add it to TELEGRAM_ALERT_CHANNEL_ID in your .env file',
groups: groups.length > 0 ? groups : undefined,
channels: channels.length > 0 ? channels : undefined,
privateChats: privateChats.length > 0 ? privateChats : undefined,
allChats: chatList,
instructions: {
step1: 'Find your group/channel in the list above',
step2: 'Copy the "id" value (should be negative, e.g., -123456789)',
step3: 'Add to .env: TELEGRAM_ALERT_CHANNEL_ID="-123456789"',
step4: 'Restart your app',
step5: 'DELETE THIS FILE (src/app/api/telegram/get-chat-ids/route.ts) for security'
},
troubleshooting: {
noChatsSeen: "If you don't see your group/channel:",
solution1: '1. Make sure your bot is added to the group/channel',
solution2: '2. Make sure bot is an admin in the group/channel',
solution3: '3. Send a message in the group (e.g., "test")',
solution4: '4. Refresh this page'
}
});
} catch (error) {
console.error('Error fetching Telegram updates:', error);
return NextResponse.json(
{
error: 'Failed to fetch updates',
message: error instanceof Error ? error.message : 'Unknown error',
details: 'Make sure BOT_TOKEN is correct in .env'
},
{ status: 500 }
);
}
}
10 changes: 10 additions & 0 deletions apps/telegram-ecash-escrow/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
OfferOrderField,
OrderDirection,
TimelineQueryItem,
fiatCurrencyApi,
getNewPostAvailable,
getOfferFilterConfig,
offerApi,
Expand All @@ -25,6 +26,8 @@ import FilterComponent from '../components/FilterOffer/FilterComponent';
import MobileLayout from '../components/layout/MobileLayout';
import { isShowAmountOrSortFilter } from '../store/util';

const { useGetAllFiatRateQuery } = fiatCurrencyApi;

const WrapHome = styled.div``;

const HomePage = styled.div`
Expand Down Expand Up @@ -82,6 +85,13 @@ export default function Home() {
const [visible, setVisible] = useState(true);
const dispatch = useLixiSliceDispatch();

// Prefetch fiat rates in the background for better modal performance
// This will cache the data so PlaceAnOrderModal can use it immediately
useGetAllFiatRateQuery(undefined, {
pollingInterval: 0,
refetchOnMountOrArgChange: true
});

const isShowSortIcon = isShowAmountOrSortFilter(offerFilterConfig);

const {
Expand Down
Loading