After changing about commission dispatch1

This commit is contained in:
Your Name 2026-07-30 16:32:13 +02:00
parent b7a360109e
commit 88f567e3ed
18 changed files with 183 additions and 79 deletions

View File

@ -28,5 +28,5 @@ COPY --from=builder /app/src/db/schema.sql ./dist/db/
EXPOSE 4000 EXPOSE 4000
# Run migrations then start the server (migrate may fail if DB not ready; index.js will retry on first request) # Migrate on boot (retry briefly if Postgres is still starting). Do not hide migrate stderr.
CMD ["sh", "-c", "node dist/db/migrate.js 2>/dev/null || true && node dist/index.js"] CMD ["sh", "-c", "i=0; until node dist/db/migrate.js; do i=$((i+1)); if [ \"$i\" -ge 5 ]; then echo 'Migration failed after retries — starting API anyway'; break; fi; echo \"Migration attempt $i failed, retrying in 3s...\"; sleep 3; done; node dist/index.js"]

View File

@ -17,11 +17,7 @@ export async function getMyReferralInfo(req: AuthRequest, res: Response): Promis
export async function getMyReferralDashboard(req: AuthRequest, res: Response): Promise<void> { export async function getMyReferralDashboard(req: AuthRequest, res: Response): Promise<void> {
try { try {
const maxDepth = req.query.maxDepth ? Number(req.query.maxDepth) : 5; const dashboard = await referralService.getUserReferralDashboard(req.user!.userId);
const dashboard = await referralService.getUserReferralDashboard(
req.user!.userId,
Number.isFinite(maxDepth) ? maxDepth : 5
);
res.json(dashboard); res.json(dashboard);
} catch (e) { } catch (e) {
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed' }); res.status(500).json({ error: e instanceof Error ? e.message : 'Failed' });

View File

@ -2424,18 +2424,26 @@ END $$;
DO $$ DO $$
DECLARE r record; DECLARE r record;
BEGIN BEGIN
-- Recreate commission_source check to allow 'prediction' -- Recreate commission_source check to allow 'prediction' (idempotent)
FOR r IN IF NOT EXISTS (
SELECT conname FROM pg_constraint SELECT 1 FROM pg_constraint
WHERE conrelid = 'public.referral_commission_payouts'::regclass WHERE conrelid = 'public.referral_commission_payouts'::regclass
AND contype = 'c' AND contype = 'c'
AND pg_get_constraintdef(oid) LIKE '%prediction%'
AND pg_get_constraintdef(oid) LIKE '%commission_source%' AND pg_get_constraintdef(oid) LIKE '%commission_source%'
LOOP ) THEN
EXECUTE format('ALTER TABLE referral_commission_payouts DROP CONSTRAINT %I', r.conname); FOR r IN
END LOOP; SELECT conname FROM pg_constraint
ALTER TABLE referral_commission_payouts WHERE conrelid = 'public.referral_commission_payouts'::regclass
ADD CONSTRAINT referral_commission_payouts_commission_source_check AND contype = 'c'
CHECK (commission_source IN ('deposit', 'withdrawal', 'prediction')); AND pg_get_constraintdef(oid) LIKE '%commission_source%'
LOOP
EXECUTE format('ALTER TABLE referral_commission_payouts DROP CONSTRAINT %I', r.conname);
END LOOP;
ALTER TABLE referral_commission_payouts
ADD CONSTRAINT referral_commission_payouts_commission_source_check
CHECK (commission_source IN ('deposit', 'withdrawal', 'prediction'));
END IF;
END $$; END $$;
CREATE UNIQUE INDEX IF NOT EXISTS idx_referral_payouts_prediction_unique CREATE UNIQUE INDEX IF NOT EXISTS idx_referral_payouts_prediction_unique

View File

@ -524,6 +524,7 @@ export type ReferralNetworkRow = {
referral_code: string | null; referral_code: string | null;
first_name: string | null; first_name: string | null;
last_name: string | null; last_name: string | null;
email_encrypted: string | null;
created_at: Date; created_at: Date;
first_deposit_at: Date | null; first_deposit_at: Date | null;
email_verified: boolean; email_verified: boolean;
@ -547,6 +548,7 @@ export async function getReferralDownline(
u.referral_code, u.referral_code,
u.first_name, u.first_name,
u.last_name, u.last_name,
u.email_encrypted,
u.created_at, u.created_at,
u.first_deposit_at, u.first_deposit_at,
u.email_verified, u.email_verified,
@ -560,6 +562,7 @@ export async function getReferralDownline(
u.referral_code, u.referral_code,
u.first_name, u.first_name,
u.last_name, u.last_name,
u.email_encrypted,
u.created_at, u.created_at,
u.first_deposit_at, u.first_deposit_at,
u.email_verified, u.email_verified,
@ -574,6 +577,7 @@ export async function getReferralDownline(
d.referral_code, d.referral_code,
d.first_name, d.first_name,
d.last_name, d.last_name,
d.email_encrypted,
d.created_at, d.created_at,
d.first_deposit_at, d.first_deposit_at,
d.email_verified, d.email_verified,

View File

@ -22,6 +22,7 @@ import { notifyReferralSlack } from './referralNotificationService';
import { computeCommissionableWithdrawalBase } from './referralWithdrawalCommissionService'; import { computeCommissionableWithdrawalBase } from './referralWithdrawalCommissionService';
import { formatCountryCode, getCountryNameMap } from '../utils/countryFormat'; import { formatCountryCode, getCountryNameMap } from '../utils/countryFormat';
import { buildReferralRegisterLink } from '../utils/publicWebUrl'; import { buildReferralRegisterLink } from '../utils/publicWebUrl';
import { decrypt } from '../utils/crypto';
import { maybeAutoSuspendForSybilFraud } from './fraudAutoBlockService'; import { maybeAutoSuspendForSybilFraud } from './fraudAutoBlockService';
export class ReferralError extends Error { export class ReferralError extends Error {
@ -792,6 +793,7 @@ function mapReferralNetworkMember(
parentUserId: string; parentUserId: string;
levelNumber: number; levelNumber: number;
displayName: string; displayName: string;
email: string | null;
referralCode: string | null; referralCode: string | null;
countryOfResidence: string | null; countryOfResidence: string | null;
countryName: string | null; countryName: string | null;
@ -809,6 +811,15 @@ function mapReferralNetworkMember(
if (!row.email_verified) status = 'unverified'; if (!row.email_verified) status = 'unverified';
else if (row.first_deposit_at) status = 'active'; else if (row.first_deposit_at) status = 'active';
let email: string | null = null;
if (row.email_encrypted) {
try {
email = decrypt(row.email_encrypted);
} catch {
email = null;
}
}
return { return {
userId: row.user_id, userId: row.user_id,
parentUserId: row.parent_user_id, parentUserId: row.parent_user_id,
@ -818,6 +829,7 @@ function mapReferralNetworkMember(
row.last_name, row.last_name,
row.user_id row.user_id
), ),
email,
referralCode: row.referral_code, referralCode: row.referral_code,
countryOfResidence: row.country_of_residence, countryOfResidence: row.country_of_residence,
countryName: row.country_of_residence countryName: row.country_of_residence
@ -835,10 +847,7 @@ function mapReferralNetworkMember(
}; };
} }
export async function getUserReferralDashboard( export async function getUserReferralDashboard(userId: string): Promise<{
userId: string,
maxDepth = 5
): Promise<{
referralCode: string | null; referralCode: string | null;
referralLink: string; referralLink: string;
directReferrals: number; directReferrals: number;
@ -868,9 +877,9 @@ export async function getUserReferralDashboard(
}> { }> {
const settings = await referralRepository.getSettings(); const settings = await referralRepository.getSettings();
const activeLevels = (await referralRepository.listLevels()).filter((l) => l.is_active); const activeLevels = (await referralRepository.listLevels()).filter((l) => l.is_active);
const maxActiveLevel = // Depth matches admin "Commission levels" (highest active level number).
const depth =
activeLevels.length > 0 ? Math.max(...activeLevels.map((l) => l.level_number)) : 1; activeLevels.length > 0 ? Math.max(...activeLevels.map((l) => l.level_number)) : 1;
const depth = Math.min(Math.max(1, maxDepth), Math.max(maxActiveLevel, 1), 10);
const [meInfo, referrer, summary, networkRows, countryMap] = await Promise.all([ const [meInfo, referrer, summary, networkRows, countryMap] = await Promise.all([
getUserReferralInfo(userId), getUserReferralInfo(userId),

View File

@ -547,6 +547,30 @@ sudo docker compose --profile http up -d
curl http://127.0.0.1:9080/api/v1/setup/status curl http://127.0.0.1:9080/api/v1/setup/status
``` ```
### Colonne manquante (`prediction_commissions_enabled does not exist`)
Le backend a été mis à jour (commissions par prédiction) mais **`schema.sql` n’a pas été réappliqué**.
`phase-b:up` rebuild le code ; il ne remplace pas un migrate explicite si le migrate au boot a échoué / été ignoré.
```bash
cd ~/projects_repository/games-project
git pull
sudo npm run db:migrate
# Doit afficher: Migrations completed successfully.
sudo docker compose --profile http up -d --build
# (ou profile https-dns selon votre setup)
sudo docker compose logs backend --tail 30
```
Vérification SQL (optionnel) :
```bash
sudo docker compose exec -T postgres psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c \
"\d referral_program_settings"
```
Vous devez voir `prediction_commissions_enabled`.
### nginx : `host not found in upstream "backend"` ### nginx : `host not found in upstream "backend"`
nginx démarre avant que le backend soit visible dans le DNS Docker. Mettez à jour le projet (`git pull`) — les templates nginx utilisent le résolveur Docker `127.0.0.11`. Puis : nginx démarre avant que le backend soit visible dans le DNS Docker. Mettez à jour le projet (`git pull`) — les templates nginx utilisent le résolveur Docker `127.0.0.11`. Puis :

View File

@ -96,6 +96,7 @@ class ReferralNetworkMember {
required this.parentUserId, required this.parentUserId,
required this.levelNumber, required this.levelNumber,
required this.displayName, required this.displayName,
this.email,
this.referralCode, this.referralCode,
this.countryOfResidence, this.countryOfResidence,
this.countryName, this.countryName,
@ -114,6 +115,7 @@ class ReferralNetworkMember {
final String parentUserId; final String parentUserId;
final int levelNumber; final int levelNumber;
final String displayName; final String displayName;
final String? email;
final String? referralCode; final String? referralCode;
final String? countryOfResidence; final String? countryOfResidence;
final String? countryName; final String? countryName;
@ -146,6 +148,7 @@ class ReferralNetworkMember {
parentUserId: (json['parentUserId'] ?? '').toString(), parentUserId: (json['parentUserId'] ?? '').toString(),
levelNumber: (json['levelNumber'] as num?)?.toInt() ?? 0, levelNumber: (json['levelNumber'] as num?)?.toInt() ?? 0,
displayName: (json['displayName'] ?? '—').toString(), displayName: (json['displayName'] ?? '—').toString(),
email: json['email'] as String?,
referralCode: json['referralCode'] as String?, referralCode: json['referralCode'] as String?,
countryOfResidence: json['countryOfResidence'] as String?, countryOfResidence: json['countryOfResidence'] as String?,
countryName: json['countryName'] as String?, countryName: json['countryName'] as String?,

View File

@ -86,6 +86,8 @@ class ReferralMemberCard extends StatelessWidget {
label: s.registeredAt, label: s.registeredAt,
value: formatReferralDate(member.registeredAt), value: formatReferralDate(member.registeredAt),
), ),
if (member.email != null && member.email!.isNotEmpty)
_InfoRow(label: s.email, value: member.email!),
if (member.countryName != null && member.countryName!.isNotEmpty) if (member.countryName != null && member.countryName!.isNotEmpty)
_InfoRow(label: s.countryOfResidence.replaceAll(' *', ''), value: member.countryName!), _InfoRow(label: s.countryOfResidence.replaceAll(' *', ''), value: member.countryName!),
if (member.referralCode != null && member.referralCode!.isNotEmpty) if (member.referralCode != null && member.referralCode!.isNotEmpty)

View File

@ -242,6 +242,9 @@ class _TreeNodeState extends State<_TreeNode> {
const SizedBox(height: 6), const SizedBox(height: 6),
Text( Text(
[ [
if (widget.member.email != null &&
widget.member.email!.isNotEmpty)
widget.member.email!,
if (widget.member.countryName != null && if (widget.member.countryName != null &&
widget.member.countryName!.isNotEmpty) widget.member.countryName!.isNotEmpty)
widget.member.countryName!, widget.member.countryName!,

View File

@ -20,6 +20,7 @@ import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { api } from '../../../shared/services/api'; import { api } from '../../../shared/services/api';
import { buildReferralRegisterLink } from '../../../shared/utils/referralLink'; import { buildReferralRegisterLink } from '../../../shared/utils/referralLink';
import { copyTextToClipboard } from '../../../shared/utils/clipboard';
type ReferralInfo = { type ReferralInfo = {
referralCode: string | null; referralCode: string | null;
@ -47,12 +48,8 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) {
onNotify(t('common.nothingToCopy')); onNotify(t('common.nothingToCopy'));
return; return;
} }
try { const ok = await copyTextToClipboard(text);
await navigator.clipboard.writeText(text); onNotify(ok ? t('common.copied', { label }) : t('common.copyFailed'));
onNotify(t('common.copied', { label }));
} catch {
onNotify(t('common.copyFailed'));
}
}; };
if (q.isLoading) { if (q.isLoading) {

View File

@ -9,6 +9,7 @@ import {
CardContent, CardContent,
Chip, Chip,
IconButton, IconButton,
InputAdornment,
Skeleton, Skeleton,
Snackbar, Snackbar,
Stack, Stack,
@ -31,6 +32,7 @@ import { ReferralCommissionsPanel } from './components/ReferralCommissionsPanel'
import { useReferralCommissions, useReferralDashboard } from './hooks/useReferralDashboard'; import { useReferralCommissions, useReferralDashboard } from './hooks/useReferralDashboard';
import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader'; import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader';
import { buildReferralRegisterLink } from '../../shared/utils/referralLink'; import { buildReferralRegisterLink } from '../../shared/utils/referralLink';
import { copyTextToClipboard } from '../../shared/utils/clipboard';
const USDT_DECIMALS = 6; const USDT_DECIMALS = 6;
@ -58,26 +60,24 @@ export function ReferralPage() {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
const { auth } = useAuth(); const { auth } = useAuth();
const [tab, setTab] = useState(0); const [tab, setTab] = useState(0);
const [maxDepth, setMaxDepth] = useState(5);
const [toast, setToast] = useState<string | null>(null); const [toast, setToast] = useState<string | null>(null);
const dashQ = useReferralDashboard(maxDepth); const dashQ = useReferralDashboard();
const commissionsQ = useReferralCommissions(30, 0); const commissionsQ = useReferralCommissions(30, 0);
const data = dashQ.data; const data = dashQ.data;
const referralLink = data?.referralCode ? buildReferralRegisterLink(data.referralCode) : ''; const referralCode = data?.referralCode?.trim() ?? '';
const referralLink = referralCode
? buildReferralRegisterLink(referralCode)
: (data?.referralLink ?? '');
const copy = async (text: string, label: string) => { const copy = async (text: string, label: string) => {
if (!text) { if (!text) {
setToast(t('common.nothingToCopy')); setToast(t('common.nothingToCopy'));
return; return;
} }
try { const ok = await copyTextToClipboard(text);
await navigator.clipboard.writeText(text); setToast(ok ? t('common.copied', { label }) : t('common.copyFailed'));
setToast(t('common.copied', { label }));
} catch {
setToast(t('common.copyFailed'));
}
}; };
const refreshAll = async () => { const refreshAll = async () => {
@ -183,35 +183,55 @@ export function ReferralPage() {
/> />
)} )}
</Stack> </Stack>
<Stack direction="row" spacing={0.5}> <TextField
<TextField size="small"
size="small" fullWidth
fullWidth label={t('profileReferral.referralCode')}
label={t('profileReferral.referralCode')} value={referralCode}
value={data.referralCode} slotProps={{
slotProps={{ input: { readOnly: true } }} input: {
sx={{ '& input': { fontFamily: 'monospace', fontWeight: 700 } }} readOnly: true,
/> endAdornment: (
<IconButton <InputAdornment position="end">
onClick={() => void copy(data.referralCode!, t('profileReferral.referralCode'))} <IconButton
> edge="end"
<ContentCopyRoundedIcon /> aria-label={t('profileReferral.copyCodeAria')}
</IconButton> onClick={() =>
</Stack> void copy(referralCode, t('profileReferral.referralCode'))
<Stack direction="row" spacing={0.5}> }
<TextField >
size="small" <ContentCopyRoundedIcon fontSize="small" />
fullWidth </IconButton>
label={t('profileReferral.referralLink')} </InputAdornment>
value={referralLink} ),
slotProps={{ input: { readOnly: true } }} },
/> }}
<IconButton sx={{ '& input': { fontFamily: 'monospace', fontWeight: 700 } }}
onClick={() => void copy(referralLink, t('profileReferral.referralLink'))} />
> <TextField
<ContentCopyRoundedIcon /> size="small"
</IconButton> fullWidth
</Stack> label={t('profileReferral.referralLink')}
value={referralLink}
slotProps={{
input: {
readOnly: true,
endAdornment: (
<InputAdornment position="end">
<IconButton
edge="end"
aria-label={t('profileReferral.copyLinkAria')}
onClick={() =>
void copy(referralLink, t('profileReferral.referralLink'))
}
>
<ContentCopyRoundedIcon fontSize="small" />
</IconButton>
</InputAdornment>
),
},
}}
/>
<Button <Button
variant="contained" variant="contained"
startIcon={<ContentCopyRoundedIcon />} startIcon={<ContentCopyRoundedIcon />}
@ -292,14 +312,12 @@ export function ReferralPage() {
<Typography variant="h6" sx={{ fontWeight: 800, flex: 1 }}> <Typography variant="h6" sx={{ fontWeight: 800, flex: 1 }}>
{t('referralPage.network.title')} {t('referralPage.network.title')}
</Typography> </Typography>
<TextField <Chip
size="small" label={t('referralPage.network.maxDepthValue', {
label={t('referralPage.network.maxDepth')} depth: data.maxNetworkDepth,
type="number" })}
value={maxDepth} variant="outlined"
onChange={(e) => setMaxDepth(Math.min(10, Math.max(1, Number(e.target.value) || 5)))} color="primary"
sx={{ width: 120 }}
helperText={t('referralPage.network.showingLevels', { count: data.maxNetworkDepth })}
/> />
</Stack> </Stack>

View File

@ -71,6 +71,11 @@ export function ReferralTableView({ members }: ReferralTableViewProps) {
<Typography variant="body2" sx={{ fontWeight: 700 }}> <Typography variant="body2" sx={{ fontWeight: 700 }}>
{m.displayName} {m.displayName}
</Typography> </Typography>
{m.email && (
<Typography variant="caption" color="text.secondary">
{m.email}
</Typography>
)}
{m.referralCode && ( {m.referralCode && (
<Typography variant="caption" color="text.secondary" sx={{ fontFamily: 'monospace' }}> <Typography variant="caption" color="text.secondary" sx={{ fontFamily: 'monospace' }}>
{m.referralCode} {m.referralCode}

View File

@ -79,6 +79,7 @@ function TreeNode({ member, children, childMap, defaultExpanded = false }: TreeN
)} )}
</Stack> </Stack>
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.5 }}> <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.5 }}>
{member.email ? `${member.email} · ` : ''}
{member.countryName ? `${member.countryName} · ` : ''} {member.countryName ? `${member.countryName} · ` : ''}
{t('referralPage.tree.paid', { {t('referralPage.tree.paid', {
amount: rawToHuman(member.commissionsPaidRaw, USDT_DECIMALS), amount: rawToHuman(member.commissionsPaidRaw, USDT_DECIMALS),

View File

@ -2,13 +2,11 @@ import { useQuery } from '@tanstack/react-query';
import { api } from '../../../shared/services/api'; import { api } from '../../../shared/services/api';
import type { ReferralCommissionsPage, ReferralDashboard } from '../types'; import type { ReferralCommissionsPage, ReferralDashboard } from '../types';
export function useReferralDashboard(maxDepth = 5) { export function useReferralDashboard() {
return useQuery({ return useQuery({
queryKey: ['referral-dashboard', maxDepth], queryKey: ['referral-dashboard'],
queryFn: async () => { queryFn: async () => {
const res = await api.get<ReferralDashboard>('/api/v1/referral/dashboard', { const res = await api.get<ReferralDashboard>('/api/v1/referral/dashboard');
params: { maxDepth },
});
return res.data; return res.data;
}, },
}); });

View File

@ -5,6 +5,7 @@ export type ReferralNetworkMember = {
parentUserId: string; parentUserId: string;
levelNumber: number; levelNumber: number;
displayName: string; displayName: string;
email: string | null;
referralCode: string | null; referralCode: string | null;
countryOfResidence: string | null; countryOfResidence: string | null;
countryName: string | null; countryName: string | null;

View File

@ -724,6 +724,7 @@ export const en = {
network: { network: {
title: 'Your referral network', title: 'Your referral network',
maxDepth: 'Max depth', maxDepth: 'Max depth',
maxDepthValue: 'Max depth: {{depth}}',
showingLevels: 'Showing {{count}} levels', showingLevels: 'Showing {{count}} levels',
tableView: 'Table view', tableView: 'Table view',
treeView: 'Tree view', treeView: 'Tree view',

View File

@ -737,6 +737,7 @@ export const fr = {
network: { network: {
title: 'Votre réseau de parrainage', title: 'Votre réseau de parrainage',
maxDepth: 'Profondeur max', maxDepth: 'Profondeur max',
maxDepthValue: 'Profondeur max : {{depth}}',
showingLevels: '{{count}} niveaux affichés', showingLevels: '{{count}} niveaux affichés',
tableView: 'Vue tableau', tableView: 'Vue tableau',
treeView: 'Vue arbre', treeView: 'Vue arbre',

View File

@ -0,0 +1,33 @@
/**
* Copies text to the clipboard with a fallback for non-secure contexts (HTTP).
*/
export async function copyTextToClipboard(text: string): Promise<boolean> {
const value = text ?? '';
if (!value) return false;
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(value);
return true;
}
} catch {
// Fall through to legacy path (common on HTTP origins).
}
try {
const ta = document.createElement('textarea');
ta.value = value;
ta.setAttribute('readonly', '');
ta.style.position = 'fixed';
ta.style.left = '-9999px';
ta.style.top = '0';
document.body.appendChild(ta);
ta.focus();
ta.select();
const ok = document.execCommand('copy');
document.body.removeChild(ta);
return ok;
} catch {
return false;
}
}