diff --git a/backend/Dockerfile b/backend/Dockerfile index 5df8e734..a65b7c6e 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -28,5 +28,5 @@ COPY --from=builder /app/src/db/schema.sql ./dist/db/ EXPOSE 4000 -# Run migrations then start the server (migrate may fail if DB not ready; index.js will retry on first request) -CMD ["sh", "-c", "node dist/db/migrate.js 2>/dev/null || true && node dist/index.js"] +# Migrate on boot (retry briefly if Postgres is still starting). Do not hide migrate stderr. +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"] diff --git a/backend/src/controllers/referralController.ts b/backend/src/controllers/referralController.ts index 67f06a45..0ccd5c5a 100644 --- a/backend/src/controllers/referralController.ts +++ b/backend/src/controllers/referralController.ts @@ -17,11 +17,7 @@ export async function getMyReferralInfo(req: AuthRequest, res: Response): Promis export async function getMyReferralDashboard(req: AuthRequest, res: Response): Promise { try { - const maxDepth = req.query.maxDepth ? Number(req.query.maxDepth) : 5; - const dashboard = await referralService.getUserReferralDashboard( - req.user!.userId, - Number.isFinite(maxDepth) ? maxDepth : 5 - ); + const dashboard = await referralService.getUserReferralDashboard(req.user!.userId); res.json(dashboard); } catch (e) { res.status(500).json({ error: e instanceof Error ? e.message : 'Failed' }); diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index e6873f0e..3fd92971 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -2424,18 +2424,26 @@ END $$; DO $$ DECLARE r record; BEGIN - -- Recreate commission_source check to allow 'prediction' - FOR r IN - SELECT conname FROM pg_constraint + -- Recreate commission_source check to allow 'prediction' (idempotent) + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint WHERE conrelid = 'public.referral_commission_payouts'::regclass AND contype = 'c' + AND pg_get_constraintdef(oid) LIKE '%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')); + ) THEN + FOR r IN + SELECT conname FROM pg_constraint + WHERE conrelid = 'public.referral_commission_payouts'::regclass + AND contype = 'c' + 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 $$; CREATE UNIQUE INDEX IF NOT EXISTS idx_referral_payouts_prediction_unique diff --git a/backend/src/repositories/referralRepository.ts b/backend/src/repositories/referralRepository.ts index 196d2578..c2c1c95a 100644 --- a/backend/src/repositories/referralRepository.ts +++ b/backend/src/repositories/referralRepository.ts @@ -524,6 +524,7 @@ export type ReferralNetworkRow = { referral_code: string | null; first_name: string | null; last_name: string | null; + email_encrypted: string | null; created_at: Date; first_deposit_at: Date | null; email_verified: boolean; @@ -547,6 +548,7 @@ export async function getReferralDownline( u.referral_code, u.first_name, u.last_name, + u.email_encrypted, u.created_at, u.first_deposit_at, u.email_verified, @@ -560,6 +562,7 @@ export async function getReferralDownline( u.referral_code, u.first_name, u.last_name, + u.email_encrypted, u.created_at, u.first_deposit_at, u.email_verified, @@ -574,6 +577,7 @@ export async function getReferralDownline( d.referral_code, d.first_name, d.last_name, + d.email_encrypted, d.created_at, d.first_deposit_at, d.email_verified, diff --git a/backend/src/services/referralService.ts b/backend/src/services/referralService.ts index cbf7ec93..a2161b96 100644 --- a/backend/src/services/referralService.ts +++ b/backend/src/services/referralService.ts @@ -22,6 +22,7 @@ import { notifyReferralSlack } from './referralNotificationService'; import { computeCommissionableWithdrawalBase } from './referralWithdrawalCommissionService'; import { formatCountryCode, getCountryNameMap } from '../utils/countryFormat'; import { buildReferralRegisterLink } from '../utils/publicWebUrl'; +import { decrypt } from '../utils/crypto'; import { maybeAutoSuspendForSybilFraud } from './fraudAutoBlockService'; export class ReferralError extends Error { @@ -792,6 +793,7 @@ function mapReferralNetworkMember( parentUserId: string; levelNumber: number; displayName: string; + email: string | null; referralCode: string | null; countryOfResidence: string | null; countryName: string | null; @@ -809,6 +811,15 @@ function mapReferralNetworkMember( if (!row.email_verified) status = 'unverified'; 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 { userId: row.user_id, parentUserId: row.parent_user_id, @@ -818,6 +829,7 @@ function mapReferralNetworkMember( row.last_name, row.user_id ), + email, referralCode: row.referral_code, countryOfResidence: row.country_of_residence, countryName: row.country_of_residence @@ -835,10 +847,7 @@ function mapReferralNetworkMember( }; } -export async function getUserReferralDashboard( - userId: string, - maxDepth = 5 -): Promise<{ +export async function getUserReferralDashboard(userId: string): Promise<{ referralCode: string | null; referralLink: string; directReferrals: number; @@ -868,9 +877,9 @@ export async function getUserReferralDashboard( }> { const settings = await referralRepository.getSettings(); 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; - const depth = Math.min(Math.max(1, maxDepth), Math.max(maxActiveLevel, 1), 10); const [meInfo, referrer, summary, networkRows, countryMap] = await Promise.all([ getUserReferralInfo(userId), diff --git a/docs/DEPLOY-VPS.md b/docs/DEPLOY-VPS.md index ed22e67a..1a532a64 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -547,6 +547,30 @@ sudo docker compose --profile http up -d 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 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 : diff --git a/prediqo_mobile/lib/data/models/referral_models.dart b/prediqo_mobile/lib/data/models/referral_models.dart index b0f3f2e4..f7d90dac 100644 --- a/prediqo_mobile/lib/data/models/referral_models.dart +++ b/prediqo_mobile/lib/data/models/referral_models.dart @@ -96,6 +96,7 @@ class ReferralNetworkMember { required this.parentUserId, required this.levelNumber, required this.displayName, + this.email, this.referralCode, this.countryOfResidence, this.countryName, @@ -114,6 +115,7 @@ class ReferralNetworkMember { final String parentUserId; final int levelNumber; final String displayName; + final String? email; final String? referralCode; final String? countryOfResidence; final String? countryName; @@ -146,6 +148,7 @@ class ReferralNetworkMember { parentUserId: (json['parentUserId'] ?? '').toString(), levelNumber: (json['levelNumber'] as num?)?.toInt() ?? 0, displayName: (json['displayName'] ?? '—').toString(), + email: json['email'] as String?, referralCode: json['referralCode'] as String?, countryOfResidence: json['countryOfResidence'] as String?, countryName: json['countryName'] as String?, diff --git a/prediqo_mobile/lib/features/referral/presentation/widgets/referral_member_card.dart b/prediqo_mobile/lib/features/referral/presentation/widgets/referral_member_card.dart index 9aa3ef5b..2096e9d9 100644 --- a/prediqo_mobile/lib/features/referral/presentation/widgets/referral_member_card.dart +++ b/prediqo_mobile/lib/features/referral/presentation/widgets/referral_member_card.dart @@ -86,6 +86,8 @@ class ReferralMemberCard extends StatelessWidget { label: s.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) _InfoRow(label: s.countryOfResidence.replaceAll(' *', ''), value: member.countryName!), if (member.referralCode != null && member.referralCode!.isNotEmpty) diff --git a/prediqo_mobile/lib/features/referral/presentation/widgets/referral_network_tree.dart b/prediqo_mobile/lib/features/referral/presentation/widgets/referral_network_tree.dart index 95dc8505..b55a3ce7 100644 --- a/prediqo_mobile/lib/features/referral/presentation/widgets/referral_network_tree.dart +++ b/prediqo_mobile/lib/features/referral/presentation/widgets/referral_network_tree.dart @@ -242,6 +242,9 @@ class _TreeNodeState extends State<_TreeNode> { const SizedBox(height: 6), Text( [ + if (widget.member.email != null && + widget.member.email!.isNotEmpty) + widget.member.email!, if (widget.member.countryName != null && widget.member.countryName!.isNotEmpty) widget.member.countryName!, diff --git a/prediqo_web/src/features/profile/components/ReferralPanel.tsx b/prediqo_web/src/features/profile/components/ReferralPanel.tsx index 918a3a3e..f18f8bb1 100644 --- a/prediqo_web/src/features/profile/components/ReferralPanel.tsx +++ b/prediqo_web/src/features/profile/components/ReferralPanel.tsx @@ -20,6 +20,7 @@ import { useQuery } from '@tanstack/react-query'; import { useTranslation } from 'react-i18next'; import { api } from '../../../shared/services/api'; import { buildReferralRegisterLink } from '../../../shared/utils/referralLink'; +import { copyTextToClipboard } from '../../../shared/utils/clipboard'; type ReferralInfo = { referralCode: string | null; @@ -47,12 +48,8 @@ export function ReferralPanel({ onNotify }: ReferralPanelProps) { onNotify(t('common.nothingToCopy')); return; } - try { - await navigator.clipboard.writeText(text); - onNotify(t('common.copied', { label })); - } catch { - onNotify(t('common.copyFailed')); - } + const ok = await copyTextToClipboard(text); + onNotify(ok ? t('common.copied', { label }) : t('common.copyFailed')); }; if (q.isLoading) { diff --git a/prediqo_web/src/features/referral/ReferralPage.tsx b/prediqo_web/src/features/referral/ReferralPage.tsx index 73337f17..7864855a 100644 --- a/prediqo_web/src/features/referral/ReferralPage.tsx +++ b/prediqo_web/src/features/referral/ReferralPage.tsx @@ -9,6 +9,7 @@ import { CardContent, Chip, IconButton, + InputAdornment, Skeleton, Snackbar, Stack, @@ -31,6 +32,7 @@ import { ReferralCommissionsPanel } from './components/ReferralCommissionsPanel' import { useReferralCommissions, useReferralDashboard } from './hooks/useReferralDashboard'; import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader'; import { buildReferralRegisterLink } from '../../shared/utils/referralLink'; +import { copyTextToClipboard } from '../../shared/utils/clipboard'; const USDT_DECIMALS = 6; @@ -58,26 +60,24 @@ export function ReferralPage() { const { t, i18n } = useTranslation(); const { auth } = useAuth(); const [tab, setTab] = useState(0); - const [maxDepth, setMaxDepth] = useState(5); const [toast, setToast] = useState(null); - const dashQ = useReferralDashboard(maxDepth); + const dashQ = useReferralDashboard(); const commissionsQ = useReferralCommissions(30, 0); 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) => { if (!text) { setToast(t('common.nothingToCopy')); return; } - try { - await navigator.clipboard.writeText(text); - setToast(t('common.copied', { label })); - } catch { - setToast(t('common.copyFailed')); - } + const ok = await copyTextToClipboard(text); + setToast(ok ? t('common.copied', { label }) : t('common.copyFailed')); }; const refreshAll = async () => { @@ -183,35 +183,55 @@ export function ReferralPage() { /> )} - - - void copy(data.referralCode!, t('profileReferral.referralCode'))} - > - - - - - - void copy(referralLink, t('profileReferral.referralLink'))} - > - - - + + + void copy(referralCode, t('profileReferral.referralCode')) + } + > + + + + ), + }, + }} + sx={{ '& input': { fontFamily: 'monospace', fontWeight: 700 } }} + /> + + + void copy(referralLink, t('profileReferral.referralLink')) + } + > + + + + ), + }, + }} + />