Skip to content
Open
Show file tree
Hide file tree
Changes from 7 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
130 changes: 130 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,130 @@
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;
const alertApiToken = process.env.ALERT_API_TOKEN;

// Authenticate request with shared secret
const providedToken = request.headers.get('x-alert-token');
if (!alertApiToken || providedToken !== alertApiToken) {
console.warn('Unauthorized alert request - invalid token');
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

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.error('TELEGRAM_ALERT_CHANNEL_ID not configured - alert not sent');
return NextResponse.json({ error: 'Alert channel/group not configured' }, { status: 500 });
}

// 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 with timeout
const telegramApiUrl = `https://api.telegram.org/bot${botToken}/sendMessage`;

const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000); // 10 second timeout

try {
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
}),
signal: controller.signal
});

clearTimeout(timeout);
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 (fetchError) {
clearTimeout(timeout);
if (fetchError instanceof Error && fetchError.name === 'AbortError') {
console.error('Telegram API request timed out');
return NextResponse.json({ error: 'Request timed out' }, { status: 504 });
}
throw fetchError; // Re-throw for outer catch
}
} 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 }
);
}
}
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