diff --git a/.bashrc b/.bashrc index 654e266..3b9ccf2 100644 --- a/.bashrc +++ b/.bashrc @@ -1,925 +1,6 @@ -# =============================================================== # -# -# PERSONAL $HOME/.bashrc FILE for bash-3.0 (or later) -# By Emmanuel Rouat [no-email] -# -# Last modified: Tue Nov 20 22:04:47 CET 2012 +PS1='\[\033[01;31m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ' -# This file is normally read by interactive shells only. -#+ Here is the place to define your aliases, functions and -#+ other interactive features like your prompt. -# -# The majority of the code here assumes you are on a GNU -#+ system (most likely a Linux box) and is often based on code -#+ found on Usenet or Internet. -# -# See for instance: -# http://tldp.org/LDP/abs/html/index.html -# http://www.caliban.org/bash -# http://www.shelldorado.com/scripts/categories.html -# http://www.dotfiles.org -# -# The choice of colors was done for a shell with a dark background -#+ (white on black), and this is usually also suited for pure text-mode -#+ consoles (no X server available). If you use a white background, -#+ you'll have to do some other choices for readability. -# -# This bashrc file is a bit overcrowded. -# Remember, it is just just an example. -# Tailor it to your needs. -# -# =============================================================== # - -# --> Comments added by HOWTO author. - -# If not running interactively, don't do anything -[ -z "$PS1" ] && return - - -#------------------------------------------------------------- -# Source global definitions (if any) -#------------------------------------------------------------- - - -if [ -f /etc/bashrc ]; then - . /etc/bashrc # --> Read /etc/bashrc, if present. -fi - - -#-------------------------------------------------------------- -# Automatic setting of $DISPLAY (if not set already). -# This works for me - your mileage may vary. . . . -# The problem is that different types of terminals give -#+ different answers to 'who am i' (rxvt in particular can be -#+ troublesome) - however this code seems to work in a majority -#+ of cases. -#-------------------------------------------------------------- - -function get_xserver () -{ - case $TERM in - xterm ) - XSERVER=$(who am i | awk '{print $NF}' | tr -d ')''(' ) - # Ane-Pieter Wieringa suggests the following alternative: - # I_AM=$(who am i) - # SERVER=${I_AM#*(} - # SERVER=${SERVER%*)} - XSERVER=${XSERVER%%:*} - ;; - aterm | rxvt) - # Find some code that works here. ... - ;; - esac -} - -if [ -z ${DISPLAY:=""} ]; then - # get_xserver - if [[ -z ${XSERVER} || ${XSERVER} == $(hostname) || - ${XSERVER} == "unix" ]]; then - DISPLAY=":0.0" # Display on local host. - else - DISPLAY=${XSERVER}:0.0 # Display on remote host. - fi -fi - -export DISPLAY - -#------------------------------------------------------------- -# Some settings -#------------------------------------------------------------- - -#set -o nounset # These two options are useful for debugging. -#set -o xtrace -alias debug="set -o nounset; set -o xtrace" - -ulimit -S -c 0 # Don't want coredumps. -set -o notify -set -o noclobber -# set -o ignoreeof - - -# Enable options: -shopt -s cdspell -shopt -s cdable_vars -shopt -s checkhash -shopt -s checkwinsize -shopt -s sourcepath -shopt -s no_empty_cmd_completion -shopt -s cmdhist -shopt -s histappend histreedit histverify -shopt -s extglob # Necessary for programmable completion. - -# Disable options: -shopt -u mailwarn -unset MAILCHECK # Don't want my shell to warn me of incoming mail. - - -#------------------------------------------------------------- -# Greeting, motd etc. ... -#------------------------------------------------------------- - -# Color definitions (taken from Color Bash Prompt HowTo). -# Some colors might look different of some terminals. -# For example, I see 'Bold Red' as 'orange' on my screen, -# hence the 'Green' 'BRed' 'Red' sequence I often use in my prompt. - - -# Normal Colors -Black='\e[0;30m' # Black -Red='\e[0;31m' # Red -Green='\e[0;32m' # Green -Yellow='\e[0;33m' # Yellow -Blue='\e[0;34m' # Blue -Purple='\e[0;35m' # Purple -Cyan='\e[0;36m' # Cyan -White='\e[0;37m' # White - -# Bold -BBlack='\e[1;30m' # Black -BRed='\e[1;31m' # Red -BGreen='\e[1;32m' # Green -BYellow='\e[1;33m' # Yellow -BBlue='\e[1;34m' # Blue -BPurple='\e[1;35m' # Purple -BCyan='\e[1;36m' # Cyan -BWhite='\e[1;37m' # White - -# Background -On_Black='\e[40m' # Black -On_Red='\e[41m' # Red -On_Green='\e[42m' # Green -On_Yellow='\e[43m' # Yellow -On_Blue='\e[44m' # Blue -On_Purple='\e[45m' # Purple -On_Cyan='\e[46m' # Cyan -On_White='\e[47m' # White - -NC="\e[m" # Color Reset - - -ALERT=${BWhite}${On_Red} # Bold White on red background - - - -echo -e "${BCyan}This is BASH ${BRed}${BASH_VERSION%.*}${BCyan}\ -- DISPLAY on ${BRed}$DISPLAY${NC}\n" -date -if [ -x /usr/games/fortune ]; then - /usr/games/fortune -s # Makes our day a bit more fun.... :-) -fi - -# function _exit() # Function to run upon exit of shell. -# { -# echo -e "${BRed}Hasta la vista, baby${NC}" -# } -# trap _exit EXIT - -#------------------------------------------------------------- -# Shell Prompt - for many examples, see: -# http://www.debian-administration.org/articles/205 -# http://www.askapache.com/linux/bash-power-prompt.html -# http://tldp.org/HOWTO/Bash-Prompt-HOWTO -# https://github.com/nojhan/liquidprompt -#------------------------------------------------------------- -# Current Format: [TIME USER@HOST PWD] > -# TIME: -# Green == machine load is low -# Orange == machine load is medium -# Red == machine load is high -# ALERT == machine load is very high -# USER: -# Cyan == normal user -# Orange == SU to user -# Red == root -# HOST: -# Cyan == local session -# Green == secured remote connection (via ssh) -# Red == unsecured remote connection -# PWD: -# Green == more than 10% free disk space -# Orange == less than 10% free disk space -# ALERT == less than 5% free disk space -# Red == current user does not have write privileges -# Cyan == current filesystem is size zero (like /proc) -# >: -# White == no background or suspended jobs in this shell -# Cyan == at least one background job in this shell -# Orange == at least one suspended job in this shell -# -# Command is added to the history file each time you hit enter, -# so it's available to all shells (using 'history -a'). - - -# Test connection type: -if [ -n "${SSH_CONNECTION}" ]; then - CNX=${Green} # Connected on remote machine, via ssh (good). -elif [[ "${DISPLAY%%:0*}" != "" ]]; then - CNX=${ALERT} # Connected on remote machine, not via ssh (bad). -else - CNX=${BCyan} # Connected on local machine. -fi - -# Test user type: -if [[ ${USER} == "root" ]]; then - SU=${Red} # User is root. -# elif [[ ${USER} != $(logname) ]]; then -# SU=${BRed} # User is not login user. -else - SU=${BCyan} # User is normal (well ... most of us are). -fi - - - -NCPU=$(grep -c 'processor' /proc/cpuinfo) # Number of CPUs -SLOAD=$(( 100*${NCPU} )) # Small load -MLOAD=$(( 200*${NCPU} )) # Medium load -XLOAD=$(( 400*${NCPU} )) # Xlarge load - -# Returns system load as percentage, i.e., '40' rather than '0.40)'. -function load() -{ - local SYSLOAD=$(cut -d " " -f1 /proc/loadavg | tr -d '.') - # System load of the current host. - echo $((10#$SYSLOAD)) # Convert to decimal. -} - -# Returns a color indicating system load. -function load_color() -{ - local SYSLOAD=$(load) - if [ ${SYSLOAD} -gt ${XLOAD} ]; then - echo -en ${ALERT} - elif [ ${SYSLOAD} -gt ${MLOAD} ]; then - echo -en ${Red} - elif [ ${SYSLOAD} -gt ${SLOAD} ]; then - echo -en ${BRed} - else - echo -en ${Green} - fi -} - -# Returns a color according to free disk space in $PWD. -function disk_color() -{ - if [ ! -w "${PWD}" ] ; then - echo -en ${Red} - # No 'write' privilege in the current directory. - elif [ -s "${PWD}" ] ; then - local used=$(command df -P "$PWD" | - awk 'END {print $5} {sub(/%/,"")}') - if [ ${used} -gt 95 ]; then - echo -en ${ALERT} # Disk almost full (>95%). - elif [ ${used} -gt 90 ]; then - echo -en ${BRed} # Free disk space almost gone. - else - echo -en ${Green} # Free disk space is ok. - fi - else - echo -en ${Cyan} - # Current directory is size '0' (like /proc, /sys etc). - fi -} - -# Returns a color according to running/suspended jobs. -function job_color() -{ - if [ $(jobs -s | wc -l) -gt "0" ]; then - echo -en ${BRed} - elif [ $(jobs -r | wc -l) -gt "0" ] ; then - echo -en ${BCyan} - fi -} - -# Adds some text in the terminal frame (if applicable). - - -# Now we construct the prompt. -PROMPT_COMMAND="history -a" -case ${TERM} in - *term | rxvt | linux) - PS1="\[\$(load_color)\][\A\[${NC}\] " - # Time of day (with load info): - PS1="\[\$(load_color)\][\A\[${NC}\] " - # User@Host (with connection type info): - PS1=${PS1}"\[${SU}\]\u\[${NC}\]@\[${CNX}\]\h\[${NC}\] " - # PWD (with 'disk space' info): - PS1=${PS1}"\[\$(disk_color)\]\W]\[${NC}\] " - # Prompt (with 'job' info): - PS1=${PS1}"\[\$(job_color)\]>\[${NC}\] " - # Set title of current xterm: - PS1=${PS1}"\[\e]0;[\u@\h] \w\a\]" - ;; - *) - PS1="(\A \u@\h \W) > " # --> PS1="(\A \u@\h \w) > " - # --> Shows full pathname of current dir. - ;; -esac - - - -export TIMEFORMAT=$'\nreal %3R\tuser %3U\tsys %3S\tpcpu %P\n' -export HISTIGNORE="&:bg:fg:ll:h" -export HISTTIMEFORMAT="$(echo -e ${BCyan})[%d/%m %H:%M:%S]$(echo -e ${NC}) " -export HISTCONTROL=ignoredups -export HOSTFILE=$HOME/.hosts # Put a list of remote hosts in ~/.hosts - - -#============================================================ -# -# ALIASES AND FUNCTIONS -# -# Arguably, some functions defined here are quite big. -# If you want to make this file smaller, these functions can -#+ be converted into scripts and removed from here. -# -#============================================================ - -#------------------- -# Personnal Aliases -#------------------- - -alias rm='rm -i' -alias cp='cp -i' -alias mv='mv -i' -# -> Prevents accidentally clobbering files. -alias mkdir='mkdir -p' - -alias h='history' -alias j='jobs -l' -alias which='type -a' -alias ..='cd ..' -alias ...='cd ../..' - -# Pretty-print of some PATH variables: -alias path='echo -e ${PATH//:/\\n}' -alias libpath='echo -e ${LD_LIBRARY_PATH//:/\\n}' - - -alias du='du -kh' # Makes a more readable output. -alias df='df -kTh' - -#------------------------------------------------------------- -# The 'ls' family (this assumes you use a recent GNU ls). -#------------------------------------------------------------- -# Add colors for filetype and human-readable sizes by default on 'ls': -alias ls='ls -h --color' -alias lx='ls -lXB' # Sort by extension. -alias lk='ls -lSr' # Sort by size, biggest last. -alias lt='ls -ltr' # Sort by date, most recent last. -alias lc='ls -ltcr' # Sort by/show change time,most recent last. -alias lu='ls -ltur' # Sort by/show access time,most recent last. - -# The ubiquitous 'll': directories first, with alphanumeric sorting: -alias ll="ls -lv --group-directories-first" -alias lm='ll |more' # Pipe through 'more' -alias lr='ll -R' # Recursive ls. -alias la='ll -A' # Show hidden files. -alias l='la' -alias tree='tree -Csuh' # Nice alternative to 'recursive ls' ... - - -#------------------------------------------------------------- -# Tailoring 'less' -#------------------------------------------------------------- - -alias more='less' -export PAGER=less -export LESSCHARSET='latin1' -export LESSOPEN='|/usr/bin/lesspipe.sh %s 2>&-' - # Use this if lesspipe.sh exists. -export LESS='-i -N -w -z-4 -g -e -M -X -F -R -P%t?f%f \ -:stdin .?pb%pb\%:?lbLine %lb:?bbByte %bb:-...' - -# LESS man page colors (makes Man pages more readable). -export LESS_TERMCAP_mb=$'\E[01;31m' -export LESS_TERMCAP_md=$'\E[01;31m' -export LESS_TERMCAP_me=$'\E[0m' -export LESS_TERMCAP_se=$'\E[0m' -export LESS_TERMCAP_so=$'\E[01;44;33m' -export LESS_TERMCAP_ue=$'\E[0m' -export LESS_TERMCAP_us=$'\E[01;32m' - - -#------------------------------------------------------------- -# Spelling typos - highly personnal and keyboard-dependent :-) -#------------------------------------------------------------- - -alias xs='cd' -alias vf='cd' -alias moer='more' -alias moew='more' -alias kk='ll' - - -#------------------------------------------------------------- -# A few fun ones -#------------------------------------------------------------- - -# Adds some text in the terminal frame (if applicable). - -function xtitle() -{ - case "$TERM" in - *term* | rxvt) - echo -en "\e]0;$*\a" ;; - *) ;; - esac -} - - -# Aliases that use xtitle -alias top='xtitle Processes on $HOST && top' -alias make='xtitle Making $(basename $PWD) ; make' - -# .. and functions -function man() -{ - for i ; do - xtitle The $(basename $1|tr -d .[:digit:]) manual - command man -a "$i" - done -} - - -#------------------------------------------------------------- -# Make the following commands run in background automatically: -#------------------------------------------------------------- - -function te() # wrapper around xemacs/gnuserv -{ - if [ "$(gnuclient -batch -eval t 2>&-)" == "t" ]; then - gnuclient -q "$@"; - else - ( xemacs "$@" &); - fi -} - -function soffice() { command soffice "$@" & } -function firefox() { command firefox "$@" & } -function xpdf() { command xpdf "$@" & } - - -#------------------------------------------------------------- -# File & strings related functions: -#------------------------------------------------------------- - - -# Find a file with a pattern in name: -function ff() { find . -type f -iname '*'"$*"'*' -ls ; } - -# Find a file with pattern $1 in name and Execute $2 on it: -function fe() { find . -type f -iname '*'"${1:-}"'*' \ --exec ${2:-file} {} \; ; } - -# Find a pattern in a set of files and highlight them: -#+ (needs a recent version of egrep). -function fstr() -{ - OPTIND=1 - local mycase="" - local usage="fstr: find string in files. -Usage: fstr [-i] \"pattern\" [\"filename pattern\"] " - while getopts :it opt - do - case "$opt" in - i) mycase="-i " ;; - *) echo "$usage"; return ;; - esac - done - shift $(( $OPTIND - 1 )) - if [ "$#" -lt 1 ]; then - echo "$usage" - return; - fi - find . -type f -name "${2:-*}" -print0 | \ -xargs -0 egrep --color=always -sn ${case} "$1" 2>&- | more - -} - - -function swap() -{ # Swap 2 filenames around, if they exist (from Uzi's bashrc). - local TMPFILE=tmp.$$ - - [ $# -ne 2 ] && echo "swap: 2 arguments needed" && return 1 - [ ! -e $1 ] && echo "swap: $1 does not exist" && return 1 - [ ! -e $2 ] && echo "swap: $2 does not exist" && return 1 - - mv "$1" $TMPFILE - mv "$2" "$1" - mv $TMPFILE "$2" -} - -function extract() # Handy Extract Program -{ - if [ -f $1 ] ; then - case $1 in - *.tar.bz2) tar xvjf $1 ;; - *.tar.gz) tar xvzf $1 ;; - *.bz2) bunzip2 $1 ;; - *.rar) unrar x $1 ;; - *.gz) gunzip $1 ;; - *.tar) tar xvf $1 ;; - *.tbz2) tar xvjf $1 ;; - *.tgz) tar xvzf $1 ;; - *.zip) unzip $1 ;; - *.Z) uncompress $1 ;; - *.7z) 7z x $1 ;; - *) echo "'$1' cannot be extracted via >extract<" ;; - esac - else - echo "'$1' is not a valid file!" - fi -} - - -# Creates an archive (*.tar.gz) from given directory. -function maketar() { tar cvzf "${1%%/}.tar.gz" "${1%%/}/"; } - -# Create a ZIP archive of a file or folder. -function makezip() { zip -r "${1%%/}.zip" "$1" ; } - -# Make your directories and files access rights sane. -function sanitize() { chmod -R u=rwX,g=rX,o= "$@" ;} - -#------------------------------------------------------------- -# Process/system related functions: -#------------------------------------------------------------- - - -function my_ps() { ps $@ -u $USER -o pid,%cpu,%mem,bsdtime,command ; } -function pp() { my_ps f | awk '!/awk/ && $0~var' var=${1:-".*"} ; } - - -function killps() # kill by process name -{ - local pid pname sig="-TERM" # default signal - if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then - echo "Usage: killps [-SIGNAL] pattern" - return; - fi - if [ $# = 2 ]; then sig=$1 ; fi - for pid in $(my_ps| awk '!/awk/ && $0~pat { print $1 }' pat=${!#} ) - do - pname=$(my_ps | awk '$1~var { print $5 }' var=$pid ) - if ask "Kill process $pid <$pname> with signal $sig?" - then kill $sig $pid - fi - done -} - -function mydf() # Pretty-print of 'df' output. -{ # Inspired by 'dfc' utility. - for fs ; do - - if [ ! -d $fs ] - then - echo -e $fs" :No such file or directory" ; continue - fi - - local info=( $(command df -P $fs | awk 'END{ print $2,$3,$5 }') ) - local free=( $(command df -Pkh $fs | awk 'END{ print $4 }') ) - local nbstars=$(( 20 * ${info[1]} / ${info[0]} )) - local out="[" - for ((j=0;j<20;j++)); do - if [ ${j} -lt ${nbstars} ]; then - out=$out"*" - else - out=$out"-" - fi - done - out=${info[2]}" "$out"] ("$free" free on "$fs")" - echo -e $out - done -} - - -function my_ip() # Get IP adress on ethernet. -{ - MY_IP=$(/sbin/ifconfig eth0 | awk '/inet/ { print $2 } ' | - sed -e s/addr://) - echo ${MY_IP:-"Not connected"} -} - -function ii() # Get current host related info. -{ - echo -e "\nYou are logged on ${BRed}$HOST" - echo -e "\n${BRed}Additionnal information:$NC " ; uname -a - echo -e "\n${BRed}Users logged on:$NC " ; w -hs | - cut -d " " -f1 | sort | uniq - echo -e "\n${BRed}Current date :$NC " ; date - echo -e "\n${BRed}Machine stats :$NC " ; uptime - echo -e "\n${BRed}Memory stats :$NC " ; free - echo -e "\n${BRed}Diskspace :$NC " ; mydf / $HOME - echo -e "\n${BRed}Local IP Address :$NC" ; my_ip - echo -e "\n${BRed}Open connections :$NC "; netstat -pan --inet; - echo -} - -#------------------------------------------------------------- -# Misc utilities: -#------------------------------------------------------------- - -function repeat() # Repeat n times command. -{ - local i max - max=$1; shift; - for ((i=1; i <= max ; i++)); do # --> C-like syntax - eval "$@"; - done -} - - -function ask() # See 'killps' for example of use. -{ - echo -n "$@" '[y/n] ' ; read ans - case "$ans" in - y*|Y*) return 0 ;; - *) return 1 ;; - esac -} - -function corename() # Get name of app that created a corefile. -{ - for file ; do - echo -n $file : ; gdb --core=$file --batch | head -1 - done -} - - - -#========================================================================= -# -# PROGRAMMABLE COMPLETION SECTION -# Most are taken from the bash 2.05 documentation and from Ian McDonald's -# 'Bash completion' package (http://www.caliban.org/bash/#completion) -# You will in fact need bash more recent then 3.0 for some features. -# -# Note that most linux distributions now provide many completions -# 'out of the box' - however, you might need to make your own one day, -# so I kept those here as examples. -#========================================================================= - -if [ "${BASH_VERSION%.*}" \< "3.0" ]; then - echo "You will need to upgrade to version 3.0 for full \ - programmable completion features" - return -fi - -shopt -s extglob # Necessary. - -complete -A hostname rsh rcp telnet rlogin ftp ping disk -complete -A export printenv -complete -A variable export local readonly unset -complete -A enabled builtin -complete -A alias alias unalias -complete -A function function -complete -A user su mail finger - -complete -A helptopic help # Currently same as builtins. -complete -A shopt shopt -complete -A stopped -P '%' bg -complete -A job -P '%' fg jobs disown - -complete -A directory mkdir rmdir -complete -A directory -o default cd - -# Compression -complete -f -o default -X '*.+(zip|ZIP)' zip -complete -f -o default -X '!*.+(zip|ZIP)' unzip -complete -f -o default -X '*.+(z|Z)' compress -complete -f -o default -X '!*.+(z|Z)' uncompress -complete -f -o default -X '*.+(gz|GZ)' gzip -complete -f -o default -X '!*.+(gz|GZ)' gunzip -complete -f -o default -X '*.+(bz2|BZ2)' bzip2 -complete -f -o default -X '!*.+(bz2|BZ2)' bunzip2 -complete -f -o default -X '!*.+(zip|ZIP|z|Z|gz|GZ|bz2|BZ2)' extract - - -# Documents - Postscript,pdf,dvi..... -complete -f -o default -X '!*.+(ps|PS)' gs ghostview ps2pdf ps2ascii -complete -f -o default -X \ -'!*.+(dvi|DVI)' dvips dvipdf xdvi dviselect dvitype -complete -f -o default -X '!*.+(pdf|PDF)' acroread pdf2ps -complete -f -o default -X '!*.@(@(?(e)ps|?(E)PS|pdf|PDF)?\ -(.gz|.GZ|.bz2|.BZ2|.Z))' gv ggv -complete -f -o default -X '!*.texi*' makeinfo texi2dvi texi2html texi2pdf -complete -f -o default -X '!*.tex' tex latex slitex -complete -f -o default -X '!*.lyx' lyx -complete -f -o default -X '!*.+(htm*|HTM*)' lynx html2ps -complete -f -o default -X \ -'!*.+(doc|DOC|xls|XLS|ppt|PPT|sx?|SX?|csv|CSV|od?|OD?|ott|OTT)' soffice - -# Multimedia -complete -f -o default -X \ -'!*.+(gif|GIF|jp*g|JP*G|bmp|BMP|xpm|XPM|png|PNG)' xv gimp ee gqview -complete -f -o default -X '!*.+(mp3|MP3)' mpg123 mpg321 -complete -f -o default -X '!*.+(ogg|OGG)' ogg123 -complete -f -o default -X \ -'!*.@(mp[23]|MP[23]|ogg|OGG|wav|WAV|pls|\ -m3u|xm|mod|s[3t]m|it|mtm|ult|flac)' xmms -complete -f -o default -X '!*.@(mp?(e)g|MP?(E)G|wma|avi|AVI|\ -asf|vob|VOB|bin|dat|vcd|ps|pes|fli|viv|rm|ram|yuv|mov|MOV|qt|\ -QT|wmv|mp3|MP3|ogg|OGG|ogm|OGM|mp4|MP4|wav|WAV|asx|ASX)' xine - - - -complete -f -o default -X '!*.pl' perl perl5 - - -# This is a 'universal' completion function - it works when commands have -#+ a so-called 'long options' mode , ie: 'ls --all' instead of 'ls -a' -# Needs the '-o' option of grep -#+ (try the commented-out version if not available). - -# First, remove '=' from completion word separators -#+ (this will allow completions like 'ls --color=auto' to work correctly). - -COMP_WORDBREAKS=${COMP_WORDBREAKS/=/} - - -_get_longopts() -{ - #$1 --help | sed -e '/--/!d' -e 's/.*--\([^[:space:].,]*\).*/--\1/'| \ - #grep ^"$2" |sort -u ; - $1 --help | grep -o -e "--[^[:space:].,]*" | grep -e "$2" |sort -u -} - -_longopts() -{ - local cur - cur=${COMP_WORDS[COMP_CWORD]} - - case "${cur:-*}" in - -*) ;; - *) return ;; - esac - - case "$1" in - \~*) eval cmd="$1" ;; - *) cmd="$1" ;; - esac - COMPREPLY=( $(_get_longopts ${1} ${cur} ) ) -} -complete -o default -F _longopts configure bash -complete -o default -F _longopts wget id info a2ps ls recode - -_tar() -{ - local cur ext regex tar untar - - COMPREPLY=() - cur=${COMP_WORDS[COMP_CWORD]} - - # If we want an option, return the possible long options. - case "$cur" in - -*) COMPREPLY=( $(_get_longopts $1 $cur ) ); return 0;; - esac - - if [ $COMP_CWORD -eq 1 ]; then - COMPREPLY=( $( compgen -W 'c t x u r d A' -- $cur ) ) - return 0 - fi - - case "${COMP_WORDS[1]}" in - ?(-)c*f) - COMPREPLY=( $( compgen -f $cur ) ) - return 0 - ;; - +([^Izjy])f) - ext='tar' - regex=$ext - ;; - *z*f) - ext='tar.gz' - regex='t\(ar\.\)\(gz\|Z\)' - ;; - *[Ijy]*f) - ext='t?(ar.)bz?(2)' - regex='t\(ar\.\)bz2\?' - ;; - *) - COMPREPLY=( $( compgen -f $cur ) ) - return 0 - ;; - - esac - - if [[ "$COMP_LINE" == tar*.$ext' '* ]]; then - # Complete on files in tar file. - # - # Get name of tar file from command line. - tar=$( echo "$COMP_LINE" | \ - sed -e 's|^.* \([^ ]*'$regex'\) .*$|\1|' ) - # Devise how to untar and list it. - untar=t${COMP_WORDS[1]//[^Izjyf]/} - - COMPREPLY=( $( compgen -W "$( echo $( tar $untar $tar \ - 2>/dev/null ) )" -- "$cur" ) ) - return 0 - - else - # File completion on relevant files. - COMPREPLY=( $( compgen -G $cur\*.$ext ) ) - - fi - - return 0 - -} - -complete -F _tar -o default tar - -_make() -{ - local mdef makef makef_dir="." makef_inc gcmd cur prev i; - COMPREPLY=(); - cur=${COMP_WORDS[COMP_CWORD]}; - prev=${COMP_WORDS[COMP_CWORD-1]}; - case "$prev" in - -*f) - COMPREPLY=($(compgen -f $cur )); - return 0 - ;; - esac; - case "$cur" in - -*) - COMPREPLY=($(_get_longopts $1 $cur )); - return 0 - ;; - esac; - - # ... make reads - # GNUmakefile, - # then makefile - # then Makefile ... - if [ -f ${makef_dir}/GNUmakefile ]; then - makef=${makef_dir}/GNUmakefile - elif [ -f ${makef_dir}/makefile ]; then - makef=${makef_dir}/makefile - elif [ -f ${makef_dir}/Makefile ]; then - makef=${makef_dir}/Makefile - else - makef=${makef_dir}/*.mk # Local convention. - fi - - - # Before we scan for targets, see if a Makefile name was - #+ specified with -f. - for (( i=0; i < ${#COMP_WORDS[@]}; i++ )); do - if [[ ${COMP_WORDS[i]} == -f ]]; then - # eval for tilde expansion - eval makef=${COMP_WORDS[i+1]} - break - fi - done - [ ! -f $makef ] && return 0 - - # Deal with included Makefiles. - makef_inc=$( grep -E '^-?include' $makef | - sed -e "s,^.* ,"$makef_dir"/," ) - for file in $makef_inc; do - [ -f $file ] && makef="$makef $file" - done - - - # If we have a partial word to complete, restrict completions - #+ to matches of that word. - if [ -n "$cur" ]; then gcmd='grep "^$cur"' ; else gcmd=cat ; fi - - COMPREPLY=( $( awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ \ - {split($1,A,/ /);for(i in A)print A[i]}' \ - $makef 2>/dev/null | eval $gcmd )) - -} - -complete -F _make -X '+($*|*.[cho])' make gmake pmake - - - - -_killall() -{ - local cur prev - COMPREPLY=() - cur=${COMP_WORDS[COMP_CWORD]} - - # Get a list of processes - #+ (the first sed evaluation - #+ takes care of swapped out processes, the second - #+ takes care of getting the basename of the process). - COMPREPLY=( $( ps -u $USER -o comm | \ - sed -e '1,1d' -e 's#[]\[]##g' -e 's#^.*/##'| \ - awk '{if ($0 ~ /^'$cur'/) print $0}' )) - - return 0 -} - -complete -F _killall killall killps - - - -# Local Variables: -# mode:shell-script -# sh-shell:bash -# End: \ No newline at end of file +alias ls='ls --color=auto' +alias ll='ls -l' +alias la='ls -A' +alias l='ls -lACF' diff --git a/.dockerignore b/.dockerignore index 12143a1..efc2616 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,3 @@ __pycache__ media -import_olddb db.sqlite3 diff --git a/.gitignore b/.gitignore index aa0a2fc..1299f3e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,3 @@ -# Server config files -nginx_note.conf - # Byte-compiled / optimized / DLL files dist build @@ -43,8 +40,5 @@ env/ venv/ db.sqlite3 -# Ignore migrations during first phase dev -migrations/ - -# Don't git personal data -import_olddb/ +# Don't git index +whoosh_index/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..7b3a6b4 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,27 @@ +stages: + - test + - quality-assurance + +py38: + stage: test + image: python:3.8-alpine + before_script: + - apk add --no-cache libmagic + - pip install tox --no-cache-dir + script: tox -e py38 + +py39: + stage: test + image: python:3.9-alpine + before_script: + - apk add --no-cache libmagic + - pip install tox --no-cache-dir + script: tox -e py39 + +linters: + stage: quality-assurance + image: python:3-alpine + before_script: + - pip install tox --no-cache-dir + script: tox -e linters + allow_failure: true diff --git a/.htaccess b/.htaccess deleted file mode 100644 index 12806a1..0000000 --- a/.htaccess +++ /dev/null @@ -1,7 +0,0 @@ -ErrorDocument 403 /tfjm/server_files/403.php -ErrorDocument 404 /tfjm/server_files/404.php - -Options +FollowSymlinks -Options -Indexes -RewriteEngine On -RewriteRule ^(.*)$ dispatcher.php?path=$1 [QSA,L] diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 0ed6303..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -# Default ignored files -/workspace.xml - -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml \ No newline at end of file diff --git a/.idea/TFJM.iml b/.idea/TFJM.iml deleted file mode 100644 index 940f6f9..0000000 --- a/.idea/TFJM.iml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml deleted file mode 100644 index a55e7a1..0000000 --- a/.idea/codeStyles/codeStyleConfig.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml deleted file mode 100644 index c28cc86..0000000 --- a/.idea/dataSources.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - mysql.8 - true - com.mysql.cj.jdbc.Driver - jdbc:mysql://ynerant.fr:3306/tfjm - - - - GMT+1 - - - \ No newline at end of file diff --git a/.idea/deployment.xml b/.idea/deployment.xml deleted file mode 100644 index f213652..0000000 --- a/.idea/deployment.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 28a804d..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 6fcadc0..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 71017de..0065ffa 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,29 +1,40 @@ -FROM python:3-alpine +FROM python:3.8-alpine ENV PYTHONUNBUFFERED 1 +ENV DJANGO_ALLOW_ASYNC_UNSAFE 1 # Install LaTeX requirements -RUN apk add --no-cache gettext texlive nginx gcc libc-dev libffi-dev postgresql-dev mariadb-connector-c-dev +RUN apk add --no-cache gettext nginx gcc libc-dev libffi-dev libxml2-dev libxslt-dev postgresql-dev libmagic RUN apk add --no-cache bash -RUN mkdir /code +RUN mkdir /code /code/docs WORKDIR /code COPY requirements.txt /code/requirements.txt +COPY docs/requirements.txt /code/docs/requirements.txt RUN pip install -r requirements.txt --no-cache-dir +RUN pip install -r docs/requirements.txt --no-cache-dir COPY . /code/ +# Compile documentation +RUN sphinx-build -M html docs docs/_build + +RUN python manage.py collectstatic --noinput && \ + python manage.py compilemessages + # Configure nginx RUN mkdir /run/nginx RUN ln -sf /dev/stdout /var/log/nginx/access.log && ln -sf /dev/stderr /var/log/nginx/error.log RUN ln -sf /code/nginx_tfjm.conf /etc/nginx/conf.d/tfjm.conf RUN rm /etc/nginx/conf.d/default.conf +RUN crontab /code/tfjm.cron + # With a bashrc, the shell is better RUN ln -s /code/.bashrc /root/.bashrc ENTRYPOINT ["/code/entrypoint.sh"] EXPOSE 80 -CMD ["./manage.py", "shell_plus", "--ptpython"] +CMD ["./manage.py", "shell_plus", "--ipython"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be948b1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) 2020 Animath + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) 2020 Animath + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index a9459c3..ef82004 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,10 @@ -# Plateforme d'inscription du TFJM² +# Plateforme du TFJM² -La plateforme du TFJM² est née pour l'édition 2020 du tournoi. D'abord codée en PHP, elle a subi une refonte totale en -Python, à l'aide du framework Web [Django](https://www.djangoproject.com/). +[![pipeline status](https://gitlab.com/animath/si/plateforme-tfjm/badges/master/pipeline.svg)](https://gitlab.com/animath/si/plateforme-tfjm/-/commits/master) +[![coverage report](https://gitlab.com/animath/si/plateforme-tfjm/badges/master/coverage.svg)](https://gitlab.com/animath/si/plateforme-tfjm/-/commits/master) + +La plateforme du TFJM² est née pour la dixième édition en 2019 de l'action. +D'abord codée en PHP, elle a subi une refonte totale en Python, à l'aide du framework Web [Django](https://www.djangoproject.com/). Cette plateforme permet aux participants et encadrants de s'inscrire et de déposer leurs autorisations nécessaires. Ils pourront ensuite déposer leurs solutions et notes de synthèse pour le premier tour en temps voulu. La plateforme @@ -18,8 +21,8 @@ Le plus simple pour installer la plateforme est d'utiliser l'image Docker inclus exposé sur le port 80 avec le serveur Django. Ci-dessous une configuration Docker-Compose, à adapter selon vos besoins : ```yaml - inscription-tfjm: - build: ./inscription-tfjm + plateforme-tfjm: + build: https://gitlab.com/animath/si/plateforme-tfjm.git links: - postgres ports: @@ -37,7 +40,6 @@ Il faut remplir les variables d'environnement suivantes : ```env TFJM_STAGE= # dev ou prod -TFJM_YEAR=2021 # Année de la session du TFJM² DJANGO_DB_TYPE= # MySQL, PostgreSQL ou SQLite (par défaut) DJANGO_DB_HOST= # Hôte de la base de données DJANGO_DB_NAME= # Nom de la base de données @@ -49,17 +51,20 @@ SMTP_HOST_USER= # Utilisateur du compte SMTP SMTP_HOST_PASSWORD= # Mot de passe du compte SMTP FROM_EMAIL=contact@tfjm.org # Nom de l'expéditeur des mails SERVER_EMAIL=contact@tfjm.org # Adresse e-mail expéditrice +SYMPA_URL=lists.example.com # Serveur Sympa à utiliser +SYMPA_EMAIL= # Adresse e-mail du compte administrateur de Sympa +SYMPA_PASSWORD= # Mot de passe du compte administrateur de Sympa +SYNAPSE_PASSWORD= # Mot de passe du robot Matrix ``` Si le type de base de données sélectionné est SQLite, la variable `DJANGO_DB_HOST` sera utilisée en guise de chemin vers le fichier de base de données (par défaut, `db.sqlite3`). En développement, il est recommandé d'utiliser SQLite pour des raisons de simplicité. Les paramètres de mail ne seront -pas utilisés, et les mails qui doivent être envoyés seront envoyés dans la console. +pas utilisés, et les mails qui doivent être envoyés seront envoyés dans la console. Les intégrations mail et Matrix +seront également désactivées. En production, il est recommandé de ne pas utiliser SQLite pour des raisons de performances. La dernière différence entre le développment et la production est qu'en développement, chaque modification d'un fichier -est détectée et le serveur se relance automatiquement dès lors. - -Une fois le site lancé, le premier compte créé sera un compte administrateur. \ No newline at end of file +est détectée et le serveur se relance automatiquement dès lors. \ No newline at end of file diff --git a/apps/api/__init__.py b/apps/api/__init__.py index 08884cb..240eb6e 100644 --- a/apps/api/__init__.py +++ b/apps/api/__init__.py @@ -1 +1,4 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + default_app_config = 'api.apps.APIConfig' diff --git a/apps/api/apps.py b/apps/api/apps.py index 6e03468..1392dc1 100644 --- a/apps/api/apps.py +++ b/apps/api/apps.py @@ -1,3 +1,6 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ diff --git a/apps/api/serializers.py b/apps/api/serializers.py index 1685020..cbd843d 100644 --- a/apps/api/serializers.py +++ b/apps/api/serializers.py @@ -1,6 +1,8 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.contrib.auth.models import User from rest_framework import serializers -from member.models import TFJMUser, Authorization, MotivationLetter, Solution, Synthesis -from tournament.models import Team, Tournament, Pool class UserSerializer(serializers.ModelSerializer): @@ -8,73 +10,10 @@ class UserSerializer(serializers.ModelSerializer): Serialize a User object into JSON. """ class Meta: - model = TFJMUser + model = User exclude = ( 'username', 'password', 'groups', 'user_permissions', ) - - -class TeamSerializer(serializers.ModelSerializer): - """ - Serialize a Team object into JSON. - """ - class Meta: - model = Team - fields = "__all__" - - -class TournamentSerializer(serializers.ModelSerializer): - """ - Serialize a Tournament object into JSON. - """ - class Meta: - model = Tournament - fields = "__all__" - - -class AuthorizationSerializer(serializers.ModelSerializer): - """ - Serialize an Authorization object into JSON. - """ - class Meta: - model = Authorization - fields = "__all__" - - -class MotivationLetterSerializer(serializers.ModelSerializer): - """ - Serialize a MotivationLetter object into JSON. - """ - class Meta: - model = MotivationLetter - fields = "__all__" - - -class SolutionSerializer(serializers.ModelSerializer): - """ - Serialize a Solution object into JSON. - """ - class Meta: - model = Solution - fields = "__all__" - - -class SynthesisSerializer(serializers.ModelSerializer): - """ - Serialize a Synthesis object into JSON. - """ - class Meta: - model = Synthesis - fields = "__all__" - - -class PoolSerializer(serializers.ModelSerializer): - """ - Serialize a Pool object into JSON. - """ - class Meta: - model = Pool - fields = "__all__" diff --git a/apps/api/tests.py b/apps/api/tests.py new file mode 100644 index 0000000..7c744fa --- /dev/null +++ b/apps/api/tests.py @@ -0,0 +1,27 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from unittest.case import skipIf + +from django.conf import settings +from django.contrib.auth.models import User +from django.test import TestCase + + +class TestAPIPages(TestCase): + def setUp(self): + self.user = User.objects.create_superuser( + username="admin", + password="apitest", + email="", + ) + self.client.force_login(self.user) + + def test_user_page(self): + response = self.client.get("/api/user/") + self.assertEqual(response.status_code, 200) + + @skipIf("logs" not in settings.INSTALLED_APPS, reason="logs app is not used") + def test_logs_page(self): + response = self.client.get("/api/logs/") + self.assertEqual(response.status_code, 200) diff --git a/apps/api/urls.py b/apps/api/urls.py index b2e617f..410fa86 100644 --- a/apps/api/urls.py +++ b/apps/api/urls.py @@ -1,20 +1,20 @@ -from django.conf.urls import url, include +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.conf import settings +from django.conf.urls import include, url from rest_framework import routers -from .viewsets import UserViewSet, TeamViewSet, TournamentViewSet, AuthorizationViewSet, MotivationLetterViewSet, \ - SolutionViewSet, SynthesisViewSet, PoolViewSet +from .viewsets import UserViewSet # Routers provide an easy way of automatically determining the URL conf. # Register each app API router and user viewset router = routers.DefaultRouter() router.register('user', UserViewSet) -router.register('team', TeamViewSet) -router.register('tournament', TournamentViewSet) -router.register('authorization', AuthorizationViewSet) -router.register('motivation_letter', MotivationLetterViewSet) -router.register('solution', SolutionViewSet) -router.register('synthesis', SynthesisViewSet) -router.register('pool', PoolViewSet) + +if "logs" in settings.INSTALLED_APPS: + from logs.api.urls import register_logs_urls + register_logs_urls(router, "logs") app_name = 'api' diff --git a/apps/api/viewsets.py b/apps/api/viewsets.py index 785e446..5c1a621 100644 --- a/apps/api/viewsets.py +++ b/apps/api/viewsets.py @@ -1,124 +1,20 @@ -from django_filters.rest_framework import DjangoFilterBackend -from rest_framework import status -from rest_framework.filters import SearchFilter -from rest_framework.response import Response -from rest_framework.viewsets import ModelViewSet -from member.models import TFJMUser, Authorization, MotivationLetter, Solution, Synthesis -from tournament.models import Team, Tournament, Pool +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later -from .serializers import UserSerializer, TeamSerializer, TournamentSerializer, AuthorizationSerializer, \ - MotivationLetterSerializer, SolutionSerializer, SynthesisSerializer, PoolSerializer +from django.contrib.auth.models import User +from django_filters.rest_framework import DjangoFilterBackend +from rest_framework.filters import SearchFilter +from rest_framework.viewsets import ModelViewSet + +from .serializers import UserSerializer class UserViewSet(ModelViewSet): """ Display list of users. """ - queryset = TFJMUser.objects.all() + queryset = User.objects.order_by("id").all() serializer_class = UserSerializer filter_backends = [DjangoFilterBackend, SearchFilter] - filterset_fields = ['id', 'first_name', 'last_name', 'email', 'gender', 'student_class', 'role', 'year', 'team', - 'team__trigram', 'is_superuser', 'is_staff', 'is_active', ] + filterset_fields = ['id', 'first_name', 'last_name', 'email', 'is_superuser', 'is_staff', 'is_active', ] search_fields = ['$first_name', '$last_name', ] - - -class TeamViewSet(ModelViewSet): - """ - Display list of teams. - """ - queryset = Team.objects.all() - serializer_class = TeamSerializer - filter_backends = [DjangoFilterBackend, SearchFilter] - filterset_fields = ['name', 'trigram', 'validation_status', 'selected_for_final', 'access_code', 'tournament', - 'year', ] - search_fields = ['$name', 'trigram', ] - - -class TournamentViewSet(ModelViewSet): - """ - Display list of tournaments. - """ - queryset = Tournament.objects.all() - serializer_class = TournamentSerializer - filter_backends = [DjangoFilterBackend, SearchFilter] - filterset_fields = ['name', 'size', 'price', 'date_start', 'date_end', 'final', 'organizers', 'year', ] - search_fields = ['$name', ] - - -class AuthorizationViewSet(ModelViewSet): - """ - Display list of authorizations. - """ - queryset = Authorization.objects.all() - serializer_class = AuthorizationSerializer - filter_backends = [DjangoFilterBackend] - filterset_fields = ['user', 'type', ] - - -class MotivationLetterViewSet(ModelViewSet): - """ - Display list of motivation letters. - """ - queryset = MotivationLetter.objects.all() - serializer_class = MotivationLetterSerializer - filter_backends = [DjangoFilterBackend] - filterset_fields = ['team', 'team__trigram', ] - - -class SolutionViewSet(ModelViewSet): - """ - Display list of solutions. - """ - queryset = Solution.objects.all() - serializer_class = SolutionSerializer - filter_backends = [DjangoFilterBackend] - filterset_fields = ['team', 'team__trigram', 'problem', ] - - -class SynthesisViewSet(ModelViewSet): - """ - Display list of syntheses. - """ - queryset = Synthesis.objects.all() - serializer_class = SynthesisSerializer - filter_backends = [DjangoFilterBackend] - filterset_fields = ['team', 'team__trigram', 'source', 'round', ] - - -class PoolViewSet(ModelViewSet): - """ - Display list of pools. - If the request is a POST request and the format is "A;X;x;Y;y;Z;z;..." where A = 1 or 1 = 2, - X, Y, Z, ... are team trigrams, x, y, z, ... are numbers of problems, then this is interpreted as a - creation a pool for the round A with the solutions of problems x, y, z, ... of the teams X, Y, Z, ... respectively. - """ - queryset = Pool.objects.all() - serializer_class = PoolSerializer - filter_backends = [DjangoFilterBackend] - filterset_fields = ['teams', 'teams__trigram', 'round', ] - - def create(self, request, *args, **kwargs): - data = request.data - try: - spl = data.split(";") - if len(spl) >= 7: - round = int(spl[0]) - teams = [] - solutions = [] - for i in range((len(spl) - 1) // 2): - trigram = spl[1 + 2 * i] - pb = int(spl[2 + 2 * i]) - team = Team.objects.get(trigram=trigram) - solution = Solution.objects.get(team=team, problem=pb, final=team.selected_for_final) - teams.append(team) - solutions.append(solution) - pool = Pool.objects.create(round=round) - pool.teams.set(teams) - pool.solutions.set(solutions) - pool.save() - serializer = PoolSerializer(pool) - headers = self.get_success_headers(serializer.data) - return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) - except BaseException: # JSON data - pass - return super().create(request, *args, **kwargs) \ No newline at end of file diff --git a/apps/eastereggs/__init__.py b/apps/eastereggs/__init__.py new file mode 100644 index 0000000..5bed298 --- /dev/null +++ b/apps/eastereggs/__init__.py @@ -0,0 +1,4 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +default_app_config = 'eastereggs.apps.EastereggsConfig' diff --git a/apps/eastereggs/apps.py b/apps/eastereggs/apps.py new file mode 100644 index 0000000..afe5de2 --- /dev/null +++ b/apps/eastereggs/apps.py @@ -0,0 +1,8 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.apps import AppConfig + + +class EastereggsConfig(AppConfig): + name = 'eastereggs' diff --git a/apps/eastereggs/migrations/__init__.py b/apps/eastereggs/migrations/__init__.py new file mode 100644 index 0000000..dfc9706 --- /dev/null +++ b/apps/eastereggs/migrations/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later diff --git a/apps/eastereggs/templates/eastereggs/xp.html b/apps/eastereggs/templates/eastereggs/xp.html new file mode 100644 index 0000000..00f67b5 --- /dev/null +++ b/apps/eastereggs/templates/eastereggs/xp.html @@ -0,0 +1,19 @@ +{% extends "index.html" %} + +{% block content %} +
+{% include "eastereggs/xp_modal.html" %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/eastereggs/templates/eastereggs/xp_modal.html b/apps/eastereggs/templates/eastereggs/xp_modal.html new file mode 100644 index 0000000..c456517 --- /dev/null +++ b/apps/eastereggs/templates/eastereggs/xp_modal.html @@ -0,0 +1,20 @@ +{% load crispy_forms_filters i18n %} + + \ No newline at end of file diff --git a/apps/eastereggs/urls.py b/apps/eastereggs/urls.py new file mode 100644 index 0000000..de4d195 --- /dev/null +++ b/apps/eastereggs/urls.py @@ -0,0 +1,11 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.urls import path +from django.views.generic import TemplateView + +app_name = "eastereggs" + +urlpatterns = [ + path("xp/", TemplateView.as_view(template_name="eastereggs/xp.html")), +] diff --git a/apps/logs/__init__.py b/apps/logs/__init__.py new file mode 100644 index 0000000..58ee5b0 --- /dev/null +++ b/apps/logs/__init__.py @@ -0,0 +1,4 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +default_app_config = 'logs.apps.LogsConfig' diff --git a/apps/logs/api/__init__.py b/apps/logs/api/__init__.py new file mode 100644 index 0000000..4e945ad --- /dev/null +++ b/apps/logs/api/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later diff --git a/apps/logs/api/serializers.py b/apps/logs/api/serializers.py new file mode 100644 index 0000000..c76e3a5 --- /dev/null +++ b/apps/logs/api/serializers.py @@ -0,0 +1,19 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from rest_framework import serializers + +from ..models import Changelog + + +class ChangelogSerializer(serializers.ModelSerializer): + """ + REST API Serializer for Changelog types. + The djangorestframework plugin will analyse the model `Changelog` and parse all fields in the API. + """ + + class Meta: + model = Changelog + fields = '__all__' + # noinspection PyProtectedMember + read_only_fields = [f.name for f in model._meta.get_fields()] # Changelogs are read-only protected diff --git a/apps/logs/api/urls.py b/apps/logs/api/urls.py new file mode 100644 index 0000000..9a0ceaa --- /dev/null +++ b/apps/logs/api/urls.py @@ -0,0 +1,11 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from .views import ChangelogViewSet + + +def register_logs_urls(router, path): + """ + Configure router for Activity REST API. + """ + router.register(path, ChangelogViewSet) diff --git a/apps/logs/api/views.py b/apps/logs/api/views.py new file mode 100644 index 0000000..5ac2a07 --- /dev/null +++ b/apps/logs/api/views.py @@ -0,0 +1,28 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from django_filters.rest_framework import DjangoFilterBackend +from rest_framework.filters import OrderingFilter +from rest_framework.viewsets import ModelViewSet + +from .serializers import ChangelogSerializer +from ..models import Changelog + + +class ChangelogViewSet(ModelViewSet): + """ + REST API View set. + The djangorestframework plugin will get all `Changelog` objects, serialize it to JSON with the given serializer, + then render it on /api/logs/ + """ + + def check_permissions(self, request): + # Only superusers can get access to logs + return self.request.user and self.request.user.is_superuser + + queryset = Changelog.objects.all() + serializer_class = ChangelogSerializer + filter_backends = [DjangoFilterBackend, OrderingFilter] + filterset_fields = ['model', 'action', "instance_pk", 'user', 'ip', ] + ordering_fields = ['timestamp', 'id', ] + ordering = ['-id', ] diff --git a/apps/logs/apps.py b/apps/logs/apps.py new file mode 100644 index 0000000..7409c20 --- /dev/null +++ b/apps/logs/apps.py @@ -0,0 +1,18 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.apps import AppConfig +from django.db.models.signals import post_delete, post_save, pre_save +from django.utils.translation import gettext_lazy as _ + + +class LogsConfig(AppConfig): + name = 'logs' + verbose_name = _('Logs') + + def ready(self): + # noinspection PyUnresolvedReferences + from . import signals + pre_save.connect(signals.pre_save_object) + post_save.connect(signals.save_object) + post_delete.connect(signals.delete_object) diff --git a/apps/logs/migrations/0001_initial.py b/apps/logs/migrations/0001_initial.py new file mode 100644 index 0000000..14b9bdf --- /dev/null +++ b/apps/logs/migrations/0001_initial.py @@ -0,0 +1,37 @@ +# Generated by Django 3.0.11 on 2021-01-21 21:06 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('contenttypes', '0002_remove_content_type_name'), + ] + + operations = [ + migrations.CreateModel( + name='Changelog', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('ip', models.GenericIPAddressField(blank=True, null=True, verbose_name='IP Address')), + ('instance_pk', models.CharField(max_length=255, verbose_name='identifier')), + ('previous', models.TextField(blank=True, default='', verbose_name='previous data')), + ('data', models.TextField(blank=True, default='', verbose_name='new data')), + ('action', models.CharField(choices=[('create', 'create'), ('edit', 'edit'), ('delete', 'delete')], default='edit', max_length=16, verbose_name='action')), + ('timestamp', models.DateTimeField(default=django.utils.timezone.now, verbose_name='timestamp')), + ('model', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contenttypes.ContentType', verbose_name='model')), + ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL, verbose_name='user')), + ], + options={ + 'verbose_name': 'changelog', + 'verbose_name_plural': 'changelogs', + }, + ), + ] diff --git a/apps/logs/migrations/__init__.py b/apps/logs/migrations/__init__.py new file mode 100644 index 0000000..cf6bcc8 --- /dev/null +++ b/apps/logs/migrations/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later diff --git a/apps/logs/models.py b/apps/logs/models.py new file mode 100644 index 0000000..0077af7 --- /dev/null +++ b/apps/logs/models.py @@ -0,0 +1,88 @@ +# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.conf import settings +from django.contrib.contenttypes.models import ContentType +from django.core.exceptions import ValidationError +from django.db import models +from django.utils import timezone +from django.utils.translation import gettext_lazy as _ + + +class Changelog(models.Model): + """ + Store each modification in the database (except sessions and logging), + including creating, editing and deleting models. + """ + + user = models.ForeignKey( + settings.AUTH_USER_MODEL, + on_delete=models.PROTECT, + null=True, + verbose_name=_('user'), + ) + + ip = models.GenericIPAddressField( + null=True, + blank=True, + verbose_name=_("IP Address") + ) + + model = models.ForeignKey( + ContentType, + on_delete=models.PROTECT, + null=False, + blank=False, + verbose_name=_('model'), + ) + + instance_pk = models.CharField( + max_length=255, + null=False, + blank=False, + verbose_name=_('identifier'), + ) + + previous = models.TextField( + blank=True, + default="", + verbose_name=_('previous data'), + ) + + data = models.TextField( + blank=True, + default="", + verbose_name=_('new data'), + ) + + action = models.CharField( # create, edit or delete + max_length=16, + null=False, + blank=False, + choices=[ + ('create', _('create')), + ('edit', _('edit')), + ('delete', _('delete')), + ], + default='edit', + verbose_name=_('action'), + ) + + timestamp = models.DateTimeField( + null=False, + blank=False, + default=timezone.now, + name='timestamp', + verbose_name=_('timestamp'), + ) + + def delete(self, using=None, keep_parents=False): + raise ValidationError(_("Logs cannot be destroyed.")) + + class Meta: + verbose_name = _("changelog") + verbose_name_plural = _("changelogs") + + def __str__(self): + return _("Changelog of type \"{action}\" for model {model} at {timestamp}").format( + action=self.get_action_display(), model=str(self.model), timestamp=str(self.timestamp)) diff --git a/apps/logs/signals.py b/apps/logs/signals.py new file mode 100644 index 0000000..e493301 --- /dev/null +++ b/apps/logs/signals.py @@ -0,0 +1,132 @@ +import getpass + +from django.contrib.auth.models import User +from django.contrib.contenttypes.models import ContentType +from rest_framework.renderers import JSONRenderer +from rest_framework.serializers import ModelSerializer +from tfjm.middlewares import get_current_authenticated_user, get_current_ip + +from .models import Changelog + + +# Ces modèles ne nécessitent pas de logs +EXCLUDED = [ + 'admin.logentry', + 'authtoken.token', + 'contenttypes.contenttype', + 'logs.changelog', # Never remove this line + 'mailer.dontsendentry', + 'mailer.message', + 'mailer.messagelog', + 'migrations.migration', + 'sessions.session', +] + + +def pre_save_object(sender, instance, **kwargs): + """ + Before a model get saved, we get the previous instance that is currently in the database + """ + qs = sender.objects.filter(pk=instance.pk).all() + if qs.exists(): + instance._previous = qs.get() + else: + instance._previous = None + + +def save_object(sender, instance, **kwargs): + """ + Each time a model is saved, an entry in the table `Changelog` is added in the database + in order to store each modification made + """ + # noinspection PyProtectedMember + if instance._meta.label_lower in EXCLUDED or hasattr(instance, "_no_signal"): + return + + # noinspection PyProtectedMember + previous = instance._previous + + # Si un utilisateur est connecté, on récupère l'utilisateur courant ainsi que son adresse IP + user, ip = get_current_authenticated_user(), get_current_ip() + + if user is None: + # Si la modification n'a pas été faite via le client Web, on suppose que c'est du à `manage.py` + # On récupère alors l'utilisateur·trice connecté·e à la VM, et on récupère la note associée + ip = "127.0.0.1" + username = getpass.getuser() + user = User.objects.get(username=username) if User.objects.filter(username=username).exists() else None + + # On n'enregistre pas les connexions + # noinspection PyProtectedMember + if user is not None and instance._meta.label_lower == "auth.user" and previous \ + and instance.last_login != previous.last_login: + return + + changed_fields = '__all__' + if previous: + # On ne garde que les champs modifiés + changed_fields = [] + for field in instance._meta.fields: + if field.name.endswith("_ptr"): + # A field ending with _ptr is a OneToOneRel with a subclass, e.g. NoteClub.note_ptr -> Note + continue + if getattr(instance, field.name) != getattr(previous, field.name): + changed_fields.append(field.name) + + if len(changed_fields) == 0: + # Pas de log s'il n'y a pas de modification + return + + # On crée notre propre sérialiseur JSON pour pouvoir sauvegarder les modèles avec uniquement les champs modifiés + class CustomSerializer(ModelSerializer): + class Meta: + model = instance.__class__ + fields = changed_fields + + previous_json = JSONRenderer().render(CustomSerializer(previous).data).decode("UTF-8") if previous else "" + instance_json = JSONRenderer().render(CustomSerializer(instance).data).decode("UTF-8") + + Changelog.objects.create(user=user, + ip=ip, + model=ContentType.objects.get_for_model(instance), + instance_pk=instance.pk, + previous=previous_json, + data=instance_json, + action=("edit" if previous else "create") + ).save() + + +def delete_object(sender, instance, **kwargs): + """ + Each time a model is deleted, an entry in the table `Changelog` is added in the database + """ + # noinspection PyProtectedMember + if instance._meta.label_lower in EXCLUDED or hasattr(instance, "_no_signal"): + return + + # Si un utilisateur est connecté, on récupère l'utilisateur courant ainsi que son adresse IP + user, ip = get_current_authenticated_user(), get_current_ip() + + if user is None: + # Si la modification n'a pas été faite via le client Web, on suppose que c'est du à `manage.py` + # On récupère alors l'utilisateur·trice connecté·e à la VM, et on récupère la note associée + ip = "127.0.0.1" + username = getpass.getuser() + user = User.objects.get(username=username) if User.objects.filter(username=username).exists() else None + + # On crée notre propre sérialiseur JSON pour pouvoir sauvegarder les modèles + class CustomSerializer(ModelSerializer): + class Meta: + model = instance.__class__ + fields = '__all__' + + instance_json = JSONRenderer().render(CustomSerializer(instance).data).decode("UTF-8") + + Changelog.objects.create(user=user, + ip=ip, + model=ContentType.objects.get_for_model(instance), + instance_pk=instance.pk, + previous=instance_json, + data="", + action="delete" + ) diff --git a/apps/logs/tests.py b/apps/logs/tests.py new file mode 100644 index 0000000..9c6da02 --- /dev/null +++ b/apps/logs/tests.py @@ -0,0 +1,21 @@ +from django.contrib.auth.models import User +from django.contrib.contenttypes.models import ContentType +from django.core.exceptions import ValidationError +from django.test import TestCase + +from .models import Changelog + + +class TestChangelog(TestCase): + def test_logs(self): + user = User.objects.create(email="admin@example.com") + self.assertTrue(Changelog.objects.filter(action="create", instance_pk=user.pk, + model=ContentType.objects.get_for_model(User)).exists()) + old_user_pk = user.pk + user.delete() + self.assertTrue(Changelog.objects.filter(action="delete", instance_pk=old_user_pk, + model=ContentType.objects.get_for_model(User)).exists()) + + changelog = Changelog.objects.first() + self.assertRaises(ValidationError, changelog.delete) + str(Changelog.objects.all()) diff --git a/apps/member/__init__.py b/apps/member/__init__.py deleted file mode 100644 index 6bb559b..0000000 --- a/apps/member/__init__.py +++ /dev/null @@ -1 +0,0 @@ -default_app_config = 'member.apps.MemberConfig' diff --git a/apps/member/admin.py b/apps/member/admin.py deleted file mode 100644 index a41bb92..0000000 --- a/apps/member/admin.py +++ /dev/null @@ -1,56 +0,0 @@ -from django.contrib.auth.admin import admin -from polymorphic.admin import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin -from member.models import TFJMUser, Document, Solution, Synthesis, MotivationLetter, Authorization, Config - - -@admin.register(TFJMUser) -class TFJMUserAdmin(admin.ModelAdmin): - """ - Django admin page for users. - """ - list_display = ('email', 'first_name', 'last_name', 'role', ) - search_fields = ('last_name', 'first_name',) - - -@admin.register(Document) -class DocumentAdmin(PolymorphicParentModelAdmin): - """ - Django admin page for any documents. - """ - child_models = (Authorization, MotivationLetter, Solution, Synthesis,) - polymorphic_list = True - - -@admin.register(Authorization) -class AuthorizationAdmin(PolymorphicChildModelAdmin): - """ - Django admin page for Authorization. - """ - - -@admin.register(MotivationLetter) -class MotivationLetterAdmin(PolymorphicChildModelAdmin): - """ - Django admin page for Motivation letters. - """ - - -@admin.register(Solution) -class SolutionAdmin(PolymorphicChildModelAdmin): - """ - Django admin page for solutions. - """ - - -@admin.register(Synthesis) -class SynthesisAdmin(PolymorphicChildModelAdmin): - """ - Django admin page for syntheses. - """ - - -@admin.register(Config) -class ConfigAdmin(admin.ModelAdmin): - """ - Django admin page for configurations. - """ diff --git a/apps/member/apps.py b/apps/member/apps.py deleted file mode 100644 index 61c9ae8..0000000 --- a/apps/member/apps.py +++ /dev/null @@ -1,10 +0,0 @@ -from django.apps import AppConfig -from django.utils.translation import gettext_lazy as _ - - -class MemberConfig(AppConfig): - """ - The member app handles the information that concern a user, its documents, ... - """ - name = 'member' - verbose_name = _('member') diff --git a/apps/member/forms.py b/apps/member/forms.py deleted file mode 100644 index 083b7b4..0000000 --- a/apps/member/forms.py +++ /dev/null @@ -1,73 +0,0 @@ -from django.contrib.auth.forms import UserCreationForm -from django import forms -from django.utils.translation import gettext_lazy as _ - -from .models import TFJMUser - - -class SignUpForm(UserCreationForm): - """ - Coaches and participants register on the website through this form. - TODO: Check if this form works, render it better - """ - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.fields["first_name"].required = True - self.fields["last_name"].required = True - self.fields["role"].choices = [ - ('', _("Choose a role...")), - ('3participant', _("Participant")), - ('2coach', _("Coach")), - ] - - class Meta: - model = TFJMUser - fields = ( - 'role', - 'email', - 'first_name', - 'last_name', - 'birth_date', - 'gender', - 'address', - 'postal_code', - 'city', - 'country', - 'phone_number', - 'school', - 'student_class', - 'responsible_name', - 'responsible_phone', - 'responsible_email', - 'description', - ) - - -class TFJMUserForm(forms.ModelForm): - """ - Form to update our own information when we are participant. - """ - class Meta: - model = TFJMUser - fields = ('last_name', 'first_name', 'email', 'phone_number', 'gender', 'birth_date', 'address', 'postal_code', - 'city', 'country', 'school', 'student_class', 'responsible_name', 'responsible_phone', - 'responsible_email',) - - -class CoachUserForm(forms.ModelForm): - """ - Form to update our own information when we are coach. - """ - class Meta: - model = TFJMUser - fields = ('last_name', 'first_name', 'email', 'phone_number', 'gender', 'birth_date', 'address', 'postal_code', - 'city', 'country', 'description',) - - -class AdminUserForm(forms.ModelForm): - """ - Form to update our own information when we are organizer or admin. - """ - class Meta: - model = TFJMUser - fields = ('last_name', 'first_name', 'email', 'phone_number', 'description',) diff --git a/apps/member/management/__init__.py b/apps/member/management/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/apps/member/management/commands/__init__.py b/apps/member/management/commands/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/apps/member/management/commands/create_su.py b/apps/member/management/commands/create_su.py deleted file mode 100644 index 93ec091..0000000 --- a/apps/member/management/commands/create_su.py +++ /dev/null @@ -1,32 +0,0 @@ -import os -from datetime import date -from getpass import getpass -from django.core.management import BaseCommand -from member.models import TFJMUser - - -class Command(BaseCommand): - def handle(self, *args, **options): - """ - Little script that generate a superuser. - """ - email = input("Email: ") - password = "1" - confirm_password = "2" - while password != confirm_password: - password = getpass("Password: ") - confirm_password = getpass("Confirm password: ") - if password != confirm_password: - self.stderr.write(self.style.ERROR("Passwords don't match.")) - - user = TFJMUser.objects.create( - email=email, - password="", - role="admin", - year=os.getenv("TFJM_YEAR", date.today().year), - is_active=True, - is_staff=True, - is_superuser=True, - ) - user.set_password(password) - user.save() diff --git a/apps/member/management/commands/extract_solutions.py b/apps/member/management/commands/extract_solutions.py deleted file mode 100644 index 7b59ad1..0000000 --- a/apps/member/management/commands/extract_solutions.py +++ /dev/null @@ -1,75 +0,0 @@ -import os -from urllib.request import urlretrieve -from shutil import copyfile - -from django.core.management import BaseCommand -from django.utils import translation -from member.models import Solution -from tournament.models import Tournament - - -class Command(BaseCommand): - PROBLEMS = [ - 'Création de puzzles', - 'Départ en vacances', - 'Un festin stratégique', - 'Sauver les meubles', - 'Prêt à décoller !', - 'Ils nous espionnent !', - 'De joyeux bûcherons', - 'Robots auto-réplicateurs', - ] - - def add_arguments(self, parser): - parser.add_argument('dir', - type=str, - default='.', - help="Directory where solutions should be saved.") - parser.add_argument('--language', '-l', - type=str, - choices=['en', 'fr'], - default='fr', - help="Language of the title of the files.") - - def handle(self, *args, **options): - """ - Copy solutions elsewhere. - """ - d = options['dir'] - teams_dir = d + '/Par équipe' - os.makedirs(teams_dir, exist_ok=True) - - translation.activate(options['language']) - - copied = 0 - - for tournament in Tournament.objects.all(): - os.mkdir(teams_dir + '/' + tournament.name) - for team in tournament.teams.filter(validation_status='2valid'): - os.mkdir(teams_dir + '/' + tournament.name + '/' + str(team)) - for sol in tournament.solutions: - if not os.path.isfile('media/' + sol.file.name): - self.stdout.write(self.style.WARNING(("Warning: solution '{sol}' is not found. Maybe the file" - "was deleted?").format(sol=str(sol)))) - continue - copyfile('media/' + sol.file.name, teams_dir + '/' + tournament.name - + '/' + str(sol.team) + '/' + str(sol) + '.pdf') - copied += 1 - - self.stdout.write(self.style.SUCCESS("Successfully copied {copied} solutions!".format(copied=copied))) - - os.mkdir(d + '/Par problème') - - for pb in range(1, 9): - sols = Solution.objects.filter(problem=pb).all() - pbdir = d + '/Par problème/Problème n°{number} — {problem}'.format(number=pb, problem=self.PROBLEMS[pb - 1]) - os.mkdir(pbdir) - for sol in sols: - os.symlink('../../Par équipe/' + sol.tournament.name + '/' + str(sol.team) + '/' + str(sol) + '.pdf', - pbdir + '/' + str(sol) + '.pdf') - - self.stdout.write(self.style.SUCCESS("Symlinks by problem created!")) - - urlretrieve('https://tfjm.org/wp-content/uploads/2020/01/Problemes2020_23_01_v1_1.pdf', d + '/Énoncés.pdf') - - self.stdout.write(self.style.SUCCESS("Questions retrieved!")) diff --git a/apps/member/management/commands/import_olddb.py b/apps/member/management/commands/import_olddb.py deleted file mode 100644 index d3ff94f..0000000 --- a/apps/member/management/commands/import_olddb.py +++ /dev/null @@ -1,309 +0,0 @@ -import os - -from django.core.management import BaseCommand, CommandError -from django.db import transaction -from member.models import TFJMUser, Document, Solution, Synthesis, Authorization, MotivationLetter -from tournament.models import Team, Tournament - - -class Command(BaseCommand): - """ - Import the old database. - Tables must be found into the import_olddb folder, as CSV files. - """ - - def add_arguments(self, parser): - parser.add_argument('--tournaments', '-t', action="store", help="Import tournaments") - parser.add_argument('--teams', '-T', action="store", help="Import teams") - parser.add_argument('--users', '-u', action="store", help="Import users") - parser.add_argument('--documents', '-d', action="store", help="Import all documents") - - def handle(self, *args, **options): - if "tournaments" in options: - self.import_tournaments() - - if "teams" in options: - self.import_teams() - - if "users" in options: - self.import_users() - - if "documents" in options: - self.import_documents() - - @transaction.atomic - def import_tournaments(self): - """ - Import tournaments into the new database. - """ - print("Importing tournaments...") - with open("import_olddb/tournaments.csv") as f: - first_line = True - for line in f: - if first_line: - first_line = False - continue - - line = line[:-1].replace("\"", "") - args = line.split(";") - args = [arg if arg and arg != "NULL" else None for arg in args] - - if Tournament.objects.filter(pk=args[0]).exists(): - continue - - obj_dict = { - "id": args[0], - "name": args[1], - "size": args[2], - "place": args[3], - "price": args[4], - "description": args[5], - "date_start": args[6], - "date_end": args[7], - "date_inscription": args[8], - "date_solutions": args[9], - "date_syntheses": args[10], - "date_solutions_2": args[11], - "date_syntheses_2": args[12], - "final": args[13], - "year": args[14], - } - with transaction.atomic(): - Tournament.objects.create(**obj_dict) - print(self.style.SUCCESS("Tournaments imported")) - - @staticmethod - def validation_status(status): - if status == "NOT_READY": - return "0invalid" - elif status == "WAITING": - return "1waiting" - elif status == "VALIDATED": - return "2valid" - else: - raise CommandError("Unknown status: {}".format(status)) - - @transaction.atomic - def import_teams(self): - """ - Import teams into new database. - """ - self.stdout.write("Importing teams...") - with open("import_olddb/teams.csv") as f: - first_line = True - for line in f: - if first_line: - first_line = False - continue - - line = line[:-1].replace("\"", "") - args = line.split(";") - args = [arg if arg and arg != "NULL" else None for arg in args] - - if Team.objects.filter(pk=args[0]).exists(): - continue - - obj_dict = { - "id": args[0], - "name": args[1], - "trigram": args[2], - "tournament": Tournament.objects.get(pk=args[3]), - "inscription_date": args[13], - "validation_status": Command.validation_status(args[14]), - "selected_for_final": args[15], - "access_code": args[16], - "year": args[17], - } - with transaction.atomic(): - Team.objects.create(**obj_dict) - print(self.style.SUCCESS("Teams imported")) - - @staticmethod - def role(role): - if role == "ADMIN": - return "0admin" - elif role == "ORGANIZER": - return "1volunteer" - elif role == "ENCADRANT": - return "2coach" - elif role == "PARTICIPANT": - return "3participant" - else: - raise CommandError("Unknown role: {}".format(role)) - - @transaction.atomic - def import_users(self): - """ - Import users into the new database. - :return: - """ - self.stdout.write("Importing users...") - with open("import_olddb/users.csv") as f: - first_line = True - for line in f: - if first_line: - first_line = False - continue - - line = line[:-1].replace("\"", "") - args = line.split(";") - args = [arg if arg and arg != "NULL" else None for arg in args] - - if TFJMUser.objects.filter(pk=args[0]).exists(): - continue - - obj_dict = { - "id": args[0], - "email": args[1], - "username": args[1], - "password": "bcrypt$" + args[2], - "last_name": args[3], - "first_name": args[4], - "birth_date": args[5], - "gender": "male" if args[6] == "M" else "female", - "address": args[7], - "postal_code": args[8], - "city": args[9], - "country": args[10], - "phone_number": args[11], - "school": args[12], - "student_class": args[13].lower().replace('premiere', 'première') if args[13] else None, - "responsible_name": args[14], - "responsible_phone": args[15], - "responsible_email": args[16], - "description": args[17].replace("\\n", "\n") if args[17] else None, - "role": Command.role(args[18]), - "team": Team.objects.get(pk=args[19]) if args[19] else None, - "year": args[20], - "date_joined": args[23], - "is_active": args[18] == "ADMIN" or os.getenv("TFJM_STAGE", "dev") == "prod", - "is_staff": args[18] == "ADMIN", - "is_superuser": args[18] == "ADMIN", - } - with transaction.atomic(): - TFJMUser.objects.create(**obj_dict) - self.stdout.write(self.style.SUCCESS("Users imported")) - - self.stdout.write("Importing organizers...") - # We also import the information about the organizers of a tournament. - with open("import_olddb/organizers.csv") as f: - first_line = True - for line in f: - if first_line: - first_line = False - continue - - line = line[:-1].replace("\"", "") - args = line.split(";") - args = [arg if arg and arg != "NULL" else None for arg in args] - - with transaction.atomic(): - tournament = Tournament.objects.get(pk=args[2]) - organizer = TFJMUser.objects.get(pk=args[1]) - tournament.organizers.add(organizer) - tournament.save() - self.stdout.write(self.style.SUCCESS("Organizers imported")) - - @transaction.atomic - def import_documents(self): - """ - Import the documents (authorizations, motivation letters, solutions, syntheses) from the old database. - """ - self.stdout.write("Importing documents...") - with open("import_olddb/documents.csv") as f: - first_line = True - for line in f: - if first_line: - first_line = False - continue - - line = line[:-1].replace("\"", "") - args = line.split(";") - args = [arg if arg and arg != "NULL" else None for arg in args] - - if Document.objects.filter(file=args[0]).exists(): - doc = Document.objects.get(file=args[0]) - doc.uploaded_at = args[5].replace(" ", "T") - doc.save() - continue - - obj_dict = { - "file": args[0], - "uploaded_at": args[5], - } - if args[4] != "MOTIVATION_LETTER": - obj_dict["user"] = TFJMUser.objects.get(args[1]), - obj_dict["type"] = args[4].lower() - else: - try: - obj_dict["team"] = Team.objects.get(pk=args[2]) - except Team.DoesNotExist: - print("Team with pk {} does not exist, ignoring".format(args[2])) - continue - with transaction.atomic(): - if args[4] != "MOTIVATION_LETTER": - Authorization.objects.create(**obj_dict) - else: - MotivationLetter.objects.create(**obj_dict) - self.stdout.write(self.style.SUCCESS("Authorizations imported")) - - with open("import_olddb/solutions.csv") as f: - first_line = True - for line in f: - if first_line: - first_line = False - continue - - line = line[:-1].replace("\"", "") - args = line.split(";") - args = [arg if arg and arg != "NULL" else None for arg in args] - - if Document.objects.filter(file=args[0]).exists(): - doc = Document.objects.get(file=args[0]) - doc.uploaded_at = args[4].replace(" ", "T") - doc.save() - continue - - obj_dict = { - "file": args[0], - "team": Team.objects.get(pk=args[1]), - "problem": args[3], - "uploaded_at": args[4], - } - with transaction.atomic(): - try: - Solution.objects.create(**obj_dict) - except: - print("Solution exists") - self.stdout.write(self.style.SUCCESS("Solutions imported")) - - with open("import_olddb/syntheses.csv") as f: - first_line = True - for line in f: - if first_line: - first_line = False - continue - - line = line[:-1].replace("\"", "") - args = line.split(";") - args = [arg if arg and arg != "NULL" else None for arg in args] - - if Document.objects.filter(file=args[0]).exists(): - doc = Document.objects.get(file=args[0]) - doc.uploaded_at = args[5].replace(" ", "T") - doc.save() - continue - - obj_dict = { - "file": args[0], - "team": Team.objects.get(pk=args[1]), - "source": "opponent" if args[3] == "1" else "rapporteur", - "round": args[4], - "uploaded_at": args[5], - } - with transaction.atomic(): - try: - Synthesis.objects.create(**obj_dict) - except: - print("Synthesis exists") - self.stdout.write(self.style.SUCCESS("Syntheses imported")) diff --git a/apps/member/migrations/__init__.py b/apps/member/migrations/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/apps/member/models.py b/apps/member/models.py deleted file mode 100644 index 82da7dd..0000000 --- a/apps/member/models.py +++ /dev/null @@ -1,368 +0,0 @@ -import os -from datetime import date - -from django.contrib.auth.models import AbstractUser -from django.db import models -from django.utils.translation import gettext_lazy as _ -from polymorphic.models import PolymorphicModel - -from tournament.models import Team, Tournament - - -class TFJMUser(AbstractUser): - """ - The model of registered users (organizers/juries/admins/coachs/participants) - """ - USERNAME_FIELD = 'email' - REQUIRED_FIELDS = [] - - email = models.EmailField( - unique=True, - verbose_name=_("email"), - help_text=_("This should be valid and will be controlled."), - ) - - team = models.ForeignKey( - Team, - null=True, - on_delete=models.SET_NULL, - related_name="users", - verbose_name=_("team"), - help_text=_("Concerns only coaches and participants."), - ) - - birth_date = models.DateField( - null=True, - default=None, - verbose_name=_("birth date"), - ) - - gender = models.CharField( - max_length=16, - null=True, - default=None, - choices=[ - ("male", _("Male")), - ("female", _("Female")), - ("non-binary", _("Non binary")), - ], - verbose_name=_("gender"), - ) - - address = models.CharField( - max_length=255, - null=True, - default=None, - verbose_name=_("address"), - ) - - postal_code = models.PositiveIntegerField( - null=True, - default=None, - verbose_name=_("postal code"), - ) - - city = models.CharField( - max_length=255, - null=True, - default=None, - verbose_name=_("city"), - ) - - country = models.CharField( - max_length=255, - default="France", - null=True, - verbose_name=_("country"), - ) - - phone_number = models.CharField( - max_length=20, - null=True, - blank=True, - default=None, - verbose_name=_("phone number"), - ) - - school = models.CharField( - max_length=255, - null=True, - default=None, - verbose_name=_("school"), - ) - - student_class = models.CharField( - max_length=16, - choices=[ - ('seconde', _("Seconde or less")), - ('première', _("Première")), - ('terminale', _("Terminale")), - ], - null=True, - default=None, - verbose_name="class", - ) - - responsible_name = models.CharField( - max_length=255, - null=True, - default=None, - verbose_name=_("responsible name"), - ) - - responsible_phone = models.CharField( - max_length=20, - null=True, - default=None, - verbose_name=_("responsible phone"), - ) - - responsible_email = models.EmailField( - null=True, - default=None, - verbose_name=_("responsible email"), - ) - - description = models.TextField( - null=True, - default=None, - verbose_name=_("description"), - ) - - role = models.CharField( - max_length=16, - choices=[ - ("0admin", _("Admin")), - ("1volunteer", _("Organizer")), - ("2coach", _("Coach")), - ("3participant", _("Participant")), - ] - ) - - year = models.PositiveIntegerField( - default=os.getenv("TFJM_YEAR", date.today().year), - verbose_name=_("year"), - ) - - @property - def participates(self): - """ - Return True iff this user is a participant or a coach, ie. if the user is a member of a team that worked - for the tournament. - """ - return self.role == "3participant" or self.role == "2coach" - - @property - def organizes(self): - """ - Return True iff this user is a local or global organizer of the tournament. This includes juries. - """ - return self.role == "1volunteer" or self.role == "0admin" - - @property - def admin(self): - """ - Return True iff this user is a global organizer, ie. an administrator. This should be equivalent to be - a superuser. - """ - return self.role == "0admin" - - class Meta: - verbose_name = _("user") - verbose_name_plural = _("users") - - def save(self, *args, **kwargs): - # We ensure that the username is the email of the user. - self.username = self.email - super().save(*args, **kwargs) - - def __str__(self): - return self.first_name + " " + self.last_name - - -class Document(PolymorphicModel): - """ - Abstract model of any saved document (solution, synthesis, motivation letter, authorization) - """ - file = models.FileField( - unique=True, - verbose_name=_("file"), - ) - - uploaded_at = models.DateTimeField( - auto_now_add=True, - verbose_name=_("uploaded at"), - ) - - class Meta: - verbose_name = _("document") - verbose_name_plural = _("documents") - - def delete(self, *args, **kwargs): - self.file.delete(True) - return super().delete(*args, **kwargs) - - -class Authorization(Document): - """ - Model for authorization papers (parental consent, photo consent, sanitary plug, ...) - """ - user = models.ForeignKey( - TFJMUser, - on_delete=models.CASCADE, - related_name="authorizations", - verbose_name=_("user"), - ) - - type = models.CharField( - max_length=32, - choices=[ - ("parental_consent", _("Parental consent")), - ("photo_consent", _("Photo consent")), - ("sanitary_plug", _("Sanitary plug")), - ("scholarship", _("Scholarship")), - ], - verbose_name=_("type"), - ) - - class Meta: - verbose_name = _("authorization") - verbose_name_plural = _("authorizations") - - def __str__(self): - return _("{authorization} for user {user}").format(authorization=self.type, user=str(self.user)) - - -class MotivationLetter(Document): - """ - Model for motivation letters of a team. - """ - team = models.ForeignKey( - Team, - on_delete=models.CASCADE, - related_name="motivation_letters", - verbose_name=_("team"), - ) - - class Meta: - verbose_name = _("motivation letter") - verbose_name_plural = _("motivation letters") - - def __str__(self): - return _("Motivation letter of team {team} ({trigram})").format(team=self.team.name, trigram=self.team.trigram) - - -class Solution(Document): - """ - Model for solutions of team for a given problem, for the regional or final tournament. - """ - team = models.ForeignKey( - Team, - on_delete=models.CASCADE, - related_name="solutions", - verbose_name=_("team"), - ) - - problem = models.PositiveSmallIntegerField( - verbose_name=_("problem"), - ) - - final = models.BooleanField( - default=False, - verbose_name=_("final solution"), - ) - - @property - def tournament(self): - """ - Get the concerned tournament of a solution. - Generally the local tournament of a team, but it can be the final tournament if this is a solution for the - final tournament. - """ - return Tournament.get_final() if self.final else self.team.tournament - - class Meta: - verbose_name = _("solution") - verbose_name_plural = _("solutions") - unique_together = ('team', 'problem', 'final',) - - def __str__(self): - if self.final: - return _("Solution of team {trigram} for problem {problem} for final")\ - .format(trigram=self.team.trigram, problem=self.problem) - else: - return _("Solution of team {trigram} for problem {problem}")\ - .format(trigram=self.team.trigram, problem=self.problem) - - -class Synthesis(Document): - """ - Model for syntheses of a team for a given round and for a given role, for the regional or final tournament. - """ - team = models.ForeignKey( - Team, - on_delete=models.CASCADE, - related_name="syntheses", - verbose_name=_("team"), - ) - - source = models.CharField( - max_length=16, - choices=[ - ("opponent", _("Opponent")), - ("rapporteur", _("Rapporteur")), - ], - verbose_name=_("source"), - ) - - round = models.PositiveSmallIntegerField( - choices=[ - (1, _("Round 1")), - (2, _("Round 2")), - ], - verbose_name=_("round"), - ) - - final = models.BooleanField( - default=False, - verbose_name=_("final synthesis"), - ) - - @property - def tournament(self): - """ - Get the concerned tournament of a solution. - Generally the local tournament of a team, but it can be the final tournament if this is a solution for the - final tournament. - """ - return Tournament.get_final() if self.final else self.team.tournament - - class Meta: - verbose_name = _("synthesis") - verbose_name_plural = _("syntheses") - unique_together = ('team', 'source', 'round', 'final',) - - def __str__(self): - return _("Synthesis of team {trigram} that is {source} for the round {round} of tournament {tournament}")\ - .format(trigram=self.team.trigram, source=self.get_source_display().lower(), round=self.round, - tournament=self.tournament) - - -class Config(models.Model): - """ - Dictionary of configuration variables. - """ - key = models.CharField( - max_length=255, - primary_key=True, - verbose_name=_("key"), - ) - - value = models.TextField( - default="", - verbose_name=_("value"), - ) - - class Meta: - verbose_name = _("configuration") - verbose_name_plural = _("configurations") diff --git a/apps/member/tables.py b/apps/member/tables.py deleted file mode 100644 index 779dc47..0000000 --- a/apps/member/tables.py +++ /dev/null @@ -1,26 +0,0 @@ -import django_tables2 as tables -from django_tables2 import A - -from .models import TFJMUser - - -class UserTable(tables.Table): - """ - Table of users that are matched with a given queryset. - """ - last_name = tables.LinkColumn( - "member:information", - args=[A("pk")], - ) - - first_name = tables.LinkColumn( - "member:information", - args=[A("pk")], - ) - - class Meta: - model = TFJMUser - fields = ("last_name", "first_name", "role", "date_joined", ) - attrs = { - 'class': 'table table-condensed table-striped table-hover' - } diff --git a/apps/member/templatetags/__init__.py b/apps/member/templatetags/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/apps/member/templatetags/getconfig.py b/apps/member/templatetags/getconfig.py deleted file mode 100644 index 0c6d776..0000000 --- a/apps/member/templatetags/getconfig.py +++ /dev/null @@ -1,25 +0,0 @@ -from django import template - -import os - -from member.models import Config - - -def get_config(value): - """ - Return a value stored into the config table in the database with a given key. - """ - config = Config.objects.get_or_create(key=value)[0] - return config.value - - -def get_env(value): - """ - Get a specified environment variable. - """ - return os.getenv(value) - - -register = template.Library() -register.filter('get_config', get_config) -register.filter('get_env', get_env) diff --git a/apps/member/urls.py b/apps/member/urls.py deleted file mode 100644 index 073f057..0000000 --- a/apps/member/urls.py +++ /dev/null @@ -1,19 +0,0 @@ -from django.urls import path - -from .views import CreateUserView, MyAccountView, UserDetailView, AddTeamView, JoinTeamView, MyTeamView,\ - ProfileListView, OrphanedProfileListView, OrganizersListView, ResetAdminView - -app_name = "member" - -urlpatterns = [ - path('signup/', CreateUserView.as_view(), name="signup"), - path("my-account/", MyAccountView.as_view(), name="my_account"), - path("information//", UserDetailView.as_view(), name="information"), - path("add-team/", AddTeamView.as_view(), name="add_team"), - path("join-team/", JoinTeamView.as_view(), name="join_team"), - path("my-team/", MyTeamView.as_view(), name="my_team"), - path("profiles/", ProfileListView.as_view(), name="all_profiles"), - path("orphaned-profiles/", OrphanedProfileListView.as_view(), name="orphaned_profiles"), - path("organizers/", OrganizersListView.as_view(), name="organizers"), - path("reset-admin/", ResetAdminView.as_view(), name="reset_admin"), -] diff --git a/apps/member/views.py b/apps/member/views.py deleted file mode 100644 index cebde40..0000000 --- a/apps/member/views.py +++ /dev/null @@ -1,292 +0,0 @@ -import random - -from django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin -from django.contrib.auth.models import AnonymousUser -from django.core.exceptions import PermissionDenied -from django.db.models import Q -from django.http import FileResponse, Http404 -from django.shortcuts import redirect -from django.urls import reverse_lazy -from django.utils import timezone -from django.utils.decorators import method_decorator -from django.utils.translation import gettext_lazy as _ -from django.views import View -from django.views.decorators.debug import sensitive_post_parameters -from django.views.generic import CreateView, UpdateView, DetailView, FormView -from django_tables2 import SingleTableView -from tournament.forms import TeamForm, JoinTeam -from tournament.models import Team, Tournament, Pool -from tournament.views import AdminMixin, TeamMixin, OrgaMixin - -from .forms import SignUpForm, TFJMUserForm, AdminUserForm, CoachUserForm -from .models import TFJMUser, Document, Solution, MotivationLetter, Synthesis -from .tables import UserTable - - -class CreateUserView(CreateView): - """ - Signup form view. - """ - model = TFJMUser - form_class = SignUpForm - template_name = "registration/signup.html" - - # When errors are reported from the signup view, don't send passwords to admins - @method_decorator(sensitive_post_parameters('password1', 'password2',)) - def dispatch(self, request, *args, **kwargs): - return super().dispatch(request, *args, **kwargs) - - def get_success_url(self): - return reverse_lazy('index') - - -class MyAccountView(LoginRequiredMixin, UpdateView): - """ - Update our personal data. - """ - model = TFJMUser - template_name = "member/my_account.html" - - def get_form_class(self): - # The used form can change according to the role of the user. - return AdminUserForm if self.request.user.organizes else TFJMUserForm \ - if self.request.user.role == "3participant" else CoachUserForm - - def get_object(self, queryset=None): - return self.request.user - - def get_success_url(self): - return reverse_lazy('member:my_account') - - -class UserDetailView(LoginRequiredMixin, DetailView): - """ - View the personal information of a given user. - Only organizers can see this page, since there are personal data. - """ - model = TFJMUser - form_class = TFJMUserForm - context_object_name = "tfjmuser" - - def dispatch(self, request, *args, **kwargs): - if isinstance(request.user, AnonymousUser): - raise PermissionDenied - - self.object = self.get_object() - - if not request.user.admin \ - and (self.object.team is not None and request.user not in self.object.team.tournament.organizers.all())\ - and (self.object.team is not None and self.object.team.selected_for_final - and request.user not in Tournament.get_final().organizers.all())\ - and self.request.user != self.object: - raise PermissionDenied - return super().dispatch(request, *args, **kwargs) - - def post(self, request, *args, **kwargs): - """ - An administrator can log in through this page as someone else, and act as this other person. - """ - if "view_as" in request.POST and self.request.user.admin: - session = request.session - session["admin"] = request.user.pk - obj = self.get_object() - session["_fake_user_id"] = obj.pk - return redirect(request.path) - return self.get(request, *args, **kwargs) - - def get_context_data(self, **kwargs): - context = super().get_context_data(**kwargs) - - context["title"] = str(self.object) - - return context - - -class AddTeamView(LoginRequiredMixin, CreateView): - """ - Register a new team. - Users can choose the name, the trigram and a preferred tournament. - """ - model = Team - form_class = TeamForm - - def form_valid(self, form): - if self.request.user.organizes: - form.add_error('name', _("You can't organize and participate at the same time.")) - return self.form_invalid(form) - - if self.request.user.team: - form.add_error('name', _("You are already in a team.")) - return self.form_invalid(form) - - # Generate a random access code - team = form.instance - alphabet = "0123456789abcdefghijklmnopqrstuvwxyz0123456789" - code = "" - for i in range(6): - code += random.choice(alphabet) - team.access_code = code - team.validation_status = "0invalid" - - team.save() - team.refresh_from_db() - - self.request.user.team = team - self.request.user.save() - - return super().form_valid(form) - - def get_success_url(self): - return reverse_lazy("member:my_team") - - -class JoinTeamView(LoginRequiredMixin, FormView): - """ - Join a team with a given access code. - """ - model = Team - form_class = JoinTeam - template_name = "tournament/team_form.html" - - def form_valid(self, form): - team = form.cleaned_data["team"] - - if self.request.user.organizes: - form.add_error('access_code', _("You can't organize and participate at the same time.")) - return self.form_invalid(form) - - if self.request.user.team: - form.add_error('access_code', _("You are already in a team.")) - return self.form_invalid(form) - - if self.request.user.role == '2coach' and len(team.coaches) == 3: - form.add_error('access_code', _("This team is full of coachs.")) - return self.form_invalid(form) - - if self.request.user.role == '3participant' and len(team.participants) == 6: - form.add_error('access_code', _("This team is full of participants.")) - return self.form_invalid(form) - - if not team.invalid: - form.add_error('access_code', _("This team is already validated or waiting for validation.")) - - self.request.user.team = team - self.request.user.save() - return super().form_valid(form) - - def get_success_url(self): - return reverse_lazy("member:my_team") - - -class MyTeamView(TeamMixin, View): - """ - Redirect to the page of the information of our personal team. - """ - - def get(self, request, *args, **kwargs): - return redirect("tournament:team_detail", pk=request.user.team.pk) - - -class DocumentView(AccessMixin, View): - """ - View a PDF document, if we have the right. - - - Everyone can see the documents that concern itself. - - An administrator can see anything. - - An organizer can see documents that are related to its tournament. - - A jury can see solutions and syntheses that are evaluated in their pools. - """ - - def get(self, request, *args, **kwargs): - try: - doc = Document.objects.get(file=self.kwargs["file"]) - except Document.DoesNotExist: - raise Http404(_("No %(verbose_name)s found matching the query") % - {'verbose_name': Document._meta.verbose_name}) - - if request.user.is_authenticated: - grant = request.user.admin - - if isinstance(doc, Solution) or isinstance(doc, Synthesis): - grant = grant or doc.team == request.user.team or request.user in doc.tournament.organizers.all() - elif isinstance(doc, MotivationLetter): - grant = grant or doc.team == request.user.team or request.user in doc.team.tournament.organizers.all() - grant = grant or doc.team.selected_for_final and request.user in Tournament.get_final().organizers.all() - - if isinstance(doc, Solution): - for pool in doc.pools.all(): - if request.user in pool.juries.all(): - grant = True - break - if pool.round == 2 and timezone.now() < doc.tournament.date_solutions_2: - continue - if self.request.user.team in pool.teams.all(): - grant = True - elif isinstance(doc, Synthesis): - for pool in request.user.pools.all(): # If the user is a jury in the pool - if doc.team in pool.teams.all() and doc.final == pool.tournament.final: - grant = True - break - else: - pool = Pool.objects.filter(extra_access_token=self.request.session["extra_access_token"]) - if pool.exists(): - pool = pool.get() - if isinstance(doc, Solution): - grant = doc in pool.solutions.all() - elif isinstance(doc, Synthesis): - grant = doc.team in pool.teams.all() and doc.final == pool.tournament.final - else: - grant = False - else: - grant = False - - if not grant: - raise PermissionDenied - - return FileResponse(doc.file, content_type="application/pdf", filename=str(doc) + ".pdf") - - -class ProfileListView(AdminMixin, SingleTableView): - """ - List all registered profiles. - """ - model = TFJMUser - queryset = TFJMUser.objects.order_by("role", "last_name", "first_name") - table_class = UserTable - template_name = "member/profile_list.html" - extra_context = dict(title=_("All profiles"), type="all") - - -class OrphanedProfileListView(AdminMixin, SingleTableView): - """ - List all orphaned profiles, ie. participants that have no team. - """ - model = TFJMUser - queryset = TFJMUser.objects.filter((Q(role="2coach") | Q(role="3participant")) & Q(team__isnull=True))\ - .order_by("role", "last_name", "first_name") - table_class = UserTable - template_name = "member/profile_list.html" - extra_context = dict(title=_("Orphaned profiles"), type="orphaned") - - -class OrganizersListView(OrgaMixin, SingleTableView): - """ - List all organizers. - """ - model = TFJMUser - queryset = TFJMUser.objects.filter(Q(role="0admin") | Q(role="1volunteer"))\ - .order_by("role", "last_name", "first_name") - table_class = UserTable - template_name = "member/profile_list.html" - extra_context = dict(title=_("Organizers"), type="organizers") - - -class ResetAdminView(AdminMixin, View): - """ - Return to admin view, clear the session field that let an administrator to log in as someone else. - """ - - def dispatch(self, request, *args, **kwargs): - if "_fake_user_id" in request.session: - del request.session["_fake_user_id"] - return redirect(request.GET["path"]) diff --git a/apps/participation/__init__.py b/apps/participation/__init__.py new file mode 100644 index 0000000..fe068b6 --- /dev/null +++ b/apps/participation/__init__.py @@ -0,0 +1,4 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +default_app_config = 'participation.apps.ParticipationConfig' diff --git a/apps/participation/admin.py b/apps/participation/admin.py new file mode 100644 index 0000000..54d4662 --- /dev/null +++ b/apps/participation/admin.py @@ -0,0 +1,54 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.contrib import admin +from django.utils.translation import gettext_lazy as _ + +from .models import Participation, Passage, Pool, Solution, Synthesis, Team, Tournament + + +@admin.register(Team) +class TeamAdmin(admin.ModelAdmin): + list_display = ('name', 'trigram', 'valid',) + search_fields = ('name', 'trigram',) + list_filter = ('participation__valid',) + + def valid(self, team): + return team.participation.valid + + valid.short_description = _('valid') + + +@admin.register(Participation) +class ParticipationAdmin(admin.ModelAdmin): + list_display = ('team', 'valid',) + search_fields = ('team__name', 'team__trigram',) + list_filter = ('valid',) + + +@admin.register(Pool) +class PoolAdmin(admin.ModelAdmin): + search_fields = ('participations__team__name', 'participations__team__trigram',) + + +@admin.register(Passage) +class PassageAdmin(admin.ModelAdmin): + search_fields = ('pool__participations__team__name', 'pool__participations__team__trigram',) + + +@admin.register(Solution) +class SolutionAdmin(admin.ModelAdmin): + list_display = ('participation',) + search_fields = ('participation__team__name', 'participation__team__trigram',) + + +@admin.register(Synthesis) +class SynthesisAdmin(admin.ModelAdmin): + list_display = ('participation',) + search_fields = ('participation__team__name', 'participation__team__trigram',) + + +@admin.register(Tournament) +class TournamentAdmin(admin.ModelAdmin): + list_display = ('name',) + search_fields = ('name',) diff --git a/apps/participation/apps.py b/apps/participation/apps.py new file mode 100644 index 0000000..23bd437 --- /dev/null +++ b/apps/participation/apps.py @@ -0,0 +1,19 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.apps import AppConfig +from django.db.models.signals import post_save, pre_save + + +class ParticipationConfig(AppConfig): + """ + The participation app contains the data about the teams, solutions, ... + """ + name = 'participation' + + def ready(self): + from participation.signals import create_notes, create_team_participation, update_mailing_list + pre_save.connect(update_mailing_list, "participation.Team") + post_save.connect(create_team_participation, "participation.Team") + post_save.connect(create_notes, "participation.Passage") + post_save.connect(create_notes, "participation.Pool") diff --git a/apps/participation/forms.py b/apps/participation/forms.py new file mode 100644 index 0000000..02a8279 --- /dev/null +++ b/apps/participation/forms.py @@ -0,0 +1,206 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +import re + +from bootstrap_datepicker_plus import DatePickerInput, DateTimePickerInput +from django import forms +from django.core.exceptions import ValidationError +from django.utils import formats +from django.utils.translation import gettext_lazy as _ +from PyPDF3 import PdfFileReader + +from .models import Note, Participation, Passage, Pool, Solution, Synthesis, Team, Tournament + + +class TeamForm(forms.ModelForm): + """ + Form to create a team, with the name and the trigram,... + """ + def clean_trigram(self): + trigram = self.cleaned_data["trigram"].upper() + if not re.match("[A-Z]{3}", trigram): + raise ValidationError(_("The trigram must be composed of three uppercase letters.")) + return trigram + + class Meta: + model = Team + fields = ('name', 'trigram',) + + +class JoinTeamForm(forms.ModelForm): + """ + Form to join a team by the access code. + """ + def clean_access_code(self): + access_code = self.cleaned_data["access_code"] + if not Team.objects.filter(access_code=access_code).exists(): + raise ValidationError(_("No team was found with this access code.")) + return access_code + + def clean(self): + cleaned_data = super().clean() + if "access_code" in cleaned_data: + team = Team.objects.get(access_code=cleaned_data["access_code"]) + self.instance = team + return cleaned_data + + class Meta: + model = Team + fields = ('access_code',) + + +class ParticipationForm(forms.ModelForm): + """ + Form to update the problem of a team participation. + """ + class Meta: + model = Participation + fields = ('tournament',) + + +class RequestValidationForm(forms.Form): + """ + Form to ask about validation. + """ + _form_type = forms.CharField( + initial="RequestValidationForm", + widget=forms.HiddenInput(), + ) + + engagement = forms.BooleanField( + label=_("I engage myself to participate to the whole TFJM²."), + required=True, + ) + + +class ValidateParticipationForm(forms.Form): + """ + Form to let administrators to accept or refuse a team. + """ + _form_type = forms.CharField( + initial="ValidateParticipationForm", + widget=forms.HiddenInput(), + ) + + message = forms.CharField( + label=_("Message to address to the team:"), + widget=forms.Textarea(), + ) + + +class TournamentForm(forms.ModelForm): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + self.fields["date_start"].widget = DatePickerInput( + format=formats.get_format_lazy(format_type="DATE_INPUT_FORMATS", use_l10n=True)[0]) + self.fields["date_end"].widget = DatePickerInput( + format=formats.get_format_lazy(format_type="DATE_INPUT_FORMATS", use_l10n=True)[0]) + self.fields["inscription_limit"].widget = DateTimePickerInput( + format=formats.get_format_lazy(format_type="DATETIME_INPUT_FORMATS", use_l10n=True)[0]) + self.fields["solution_limit"].widget = DateTimePickerInput( + format=formats.get_format_lazy(format_type="DATETIME_INPUT_FORMATS", use_l10n=True)[0]) + self.fields["solutions_draw"].widget = DateTimePickerInput( + format=formats.get_format_lazy(format_type="DATETIME_INPUT_FORMATS", use_l10n=True)[0]) + self.fields["syntheses_first_phase_limit"].widget = DateTimePickerInput( + format=formats.get_format_lazy(format_type="DATETIME_INPUT_FORMATS", use_l10n=True)[0]) + self.fields["solutions_available_second_phase"].widget = DateTimePickerInput( + format=formats.get_format_lazy(format_type="DATETIME_INPUT_FORMATS", use_l10n=True)[0]) + self.fields["syntheses_second_phase_limit"].widget = DateTimePickerInput( + format=formats.get_format_lazy(format_type="DATETIME_INPUT_FORMATS", use_l10n=True)[0]) + self.fields["organizers"].widget = forms.CheckboxSelectMultiple() + + class Meta: + model = Tournament + fields = '__all__' + + +class SolutionForm(forms.ModelForm): + def clean_file(self): + if "file" in self.files: + file = self.files["file"] + if file.size > 5e6: + raise ValidationError(_("The uploaded file size must be under 5 Mo.")) + if file.content_type != "application/pdf": + raise ValidationError(_("The uploaded file must be a PDF file.")) + pdf_reader = PdfFileReader(file) + pages = len(pdf_reader.pages) + if pages > 30: + raise ValidationError(_("The PDF file must not have more than 30 pages.")) + return self.cleaned_data["photo_authorization"] + + def save(self, commit=True): + """ + Don't save a solution with this way. Use a view instead + """ + + class Meta: + model = Solution + fields = ('problem', 'file',) + + +class PoolForm(forms.ModelForm): + class Meta: + model = Pool + fields = ('tournament', 'round', 'bbb_code', 'juries',) + widgets = { + "juries": forms.CheckboxSelectMultiple, + } + + +class PoolTeamsForm(forms.ModelForm): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["participations"].queryset = self.instance.tournament.participations.all() + + class Meta: + model = Pool + fields = ('participations',) + widgets = { + "participations": forms.CheckboxSelectMultiple, + } + + +class PassageForm(forms.ModelForm): + def clean(self): + cleaned_data = super().clean() + if "defender" in cleaned_data and "opponent" in cleaned_data and "reporter" in cleaned_data \ + and len({cleaned_data["defender"], cleaned_data["opponent"], cleaned_data["reporter"]}) < 3: + self.add_error(None, _("The defender, the opponent and the reporter must be different.")) + if "defender" in self.cleaned_data and "solution_number" in self.cleaned_data \ + and not Solution.objects.filter(participation=cleaned_data["defender"], + problem=cleaned_data["solution_number"]).exists(): + self.add_error("solution_number", _("This defender did not work on this problem.")) + return cleaned_data + + class Meta: + model = Passage + fields = ('solution_number', 'place', 'defender', 'opponent', 'reporter',) + + +class SynthesisForm(forms.ModelForm): + def clean_file(self): + if "file" in self.files: + file = self.files["file"] + if file.size > 2e6: + raise ValidationError(_("The uploaded file size must be under 2 Mo.")) + if file.content_type != "application/pdf": + raise ValidationError(_("The uploaded file must be a PDF file.")) + return self.cleaned_data["photo_authorization"] + + def save(self, commit=True): + """ + Don't save a synthesis with this way. Use a view instead + """ + + class Meta: + model = Synthesis + fields = ('type', 'file',) + + +class NoteForm(forms.ModelForm): + class Meta: + model = Note + fields = ('defender_writing', 'defender_oral', 'opponent_writing', + 'opponent_oral', 'reporter_writing', 'reporter_oral', ) diff --git a/apps/participation/management/commands/__init__.py b/apps/participation/management/commands/__init__.py new file mode 100644 index 0000000..dfc9706 --- /dev/null +++ b/apps/participation/management/commands/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later diff --git a/apps/participation/management/commands/check_hello_asso.py b/apps/participation/management/commands/check_hello_asso.py new file mode 100644 index 0000000..748b2bb --- /dev/null +++ b/apps/participation/management/commands/check_hello_asso.py @@ -0,0 +1,54 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +import os + +from django.contrib.auth.models import User +from django.core.management import BaseCommand +import requests + + +class Command(BaseCommand): + def handle(self, *args, **options): # noqa: C901 + organization = "animath" + form_slug = "tfjmm-2018" + from_date = "2000-01-01" + url = f"https://api.helloasso.com/v5/organizations/{organization}/forms/Event/{form_slug}/payments" \ + f"?from={from_date}&pageIndex=1&pageSize=10000&retrieveOfflineDonations=false" + headers = { + "Accept": "application/json", + "Authorization": f"Bearer {os.getenv('HELLO_ASSO_TOKEN', '')}", + } + http_response = requests.get(url, headers=headers) + response = http_response.json() + + if http_response.status_code != 200: + message = response["message"] + self.stderr.write(f"Error while querying Hello Asso: {message}") + return + + for payment in response: + if payment["state"] != "Authorized": + continue + + payer = payment["payer"] + email = payer["email"] + qs = User.objects.filter(email=email) + if not qs.exists(): + self.stderr.write(f"Warning: a payment was found by the email address {email}, " + "but this user is unknown.") + continue + user = qs.get() + if not user.registration.participates: + self.stderr.write(f"Warning: a payment was found by the email address {email}, " + "but this user is not a participant.") + continue + payment_obj = user.registration.payment + payment_obj.valid = True + payment_obj.type = "helloasso" + payment_obj.additional_information = f"Identifiant de transation : {payment['id']}\n" \ + f"Date : {payment['date']}\n" \ + f"Reçu : {payment['paymentReceiptUrl']}\n" \ + f"Montant : {payment['amount'] / 100:.2f} €" + payment_obj.save() + self.stdout.write(f"{payment_obj} is validated") diff --git a/apps/participation/management/commands/fix_matrix_channels.py b/apps/participation/management/commands/fix_matrix_channels.py new file mode 100644 index 0000000..ee033d0 --- /dev/null +++ b/apps/participation/management/commands/fix_matrix_channels.py @@ -0,0 +1,394 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +import os + +from asgiref.sync import async_to_sync +from django.core.management import BaseCommand +from django.utils.http import urlencode +from django.utils.translation import activate +from participation.models import Team, Tournament +from registration.models import AdminRegistration, Registration, VolunteerRegistration +from tfjm.matrix import Matrix, RoomPreset, RoomVisibility + + +class Command(BaseCommand): + def handle(self, *args, **options): # noqa: C901 + activate("fr") + + Matrix.set_display_name("Bot du TFJM²") + + if not os.getenv("SYNAPSE_PASSWORD"): + avatar_uri = "plop" + else: # pragma: no cover + if not os.path.isfile(".matrix_avatar"): + stat_file = os.stat("tfjm/static/logo.png") + with open("tfjm/static/logo.png", "rb") as f: + resp = Matrix.upload(f, filename="logo.png", content_type="image/png", + filesize=stat_file.st_size)[0][0] + avatar_uri = resp.content_uri + with open(".matrix_avatar", "w") as f: + f.write(avatar_uri) + Matrix.set_avatar(avatar_uri) + + with open(".matrix_avatar", "r") as f: + avatar_uri = f.read().rstrip(" \t\r\n") + + # Create basic channels + if not async_to_sync(Matrix.resolve_room_alias)("#aide-jurys-orgas:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="aide-jurys-orgas", + name="Aide jurys & orgas", + topic="Pour discuter de propblèmes d'organisation", + federate=False, + preset=RoomPreset.private_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)("#annonces:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="annonces", + name="Annonces", + topic="Informations importantes du TFJM²", + federate=False, + preset=RoomPreset.public_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)("#bienvenue:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="bienvenue", + name="Bienvenue", + topic="Bienvenue au TFJM² 2021 !", + federate=False, + preset=RoomPreset.public_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)("#bot:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="bot", + name="Bot", + topic="Vive les r0b0ts", + federate=False, + preset=RoomPreset.public_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)("#cno:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="cno", + name="CNO", + topic="Channel des dieux", + federate=False, + preset=RoomPreset.private_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)("#dev-bot:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="dev-bot", + name="Bot - développement", + topic="Vive le bot", + federate=False, + preset=RoomPreset.private_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)("#faq:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="faq", + name="FAQ", + topic="Posez toutes vos questions ici !", + federate=False, + preset=RoomPreset.public_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)("#flood:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="flood", + name="Flood", + topic="Discutez de tout et de rien !", + federate=False, + preset=RoomPreset.public_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)("#je-cherche-une-equipe:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias="je-cherche-une-equipe", + name="Je cherche une équipe", + topic="Le Tinder du TFJM²", + federate=False, + preset=RoomPreset.public_chat, + ) + + # Setup avatars + Matrix.set_room_avatar("#aide-jurys-orgas:tfjm.org", avatar_uri) + Matrix.set_room_avatar("#annonces:tfjm.org", avatar_uri) + Matrix.set_room_avatar("#bienvenue:tfjm.org", avatar_uri) + Matrix.set_room_avatar("#bot:tfjm.org", avatar_uri) + Matrix.set_room_avatar("#cno:tfjm.org", avatar_uri) + Matrix.set_room_avatar("#dev-bot:tfjm.org", avatar_uri) + Matrix.set_room_avatar("#faq:tfjm.org", avatar_uri) + Matrix.set_room_avatar("#flood:tfjm.org", avatar_uri) + Matrix.set_room_avatar("#je-cherche-une-equipe:tfjm.org", avatar_uri) + + # Read-only channels + Matrix.set_room_power_level_event("#annonces:tfjm.org", "events_default", 50) + Matrix.set_room_power_level_event("#bienvenue:tfjm.org", "events_default", 50) + + # Invite everyone to public channels + for r in Registration.objects.all(): + Matrix.invite("#annonces:tfjm.org", f"@{r.matrix_username}:tfjm.org") + Matrix.invite("#bienvenue:tfjm.org", f"@{r.matrix_username}:tfjm.org") + Matrix.invite("#bot:tfjm.org", f"@{r.matrix_username}:tfjm.org") + Matrix.invite("#faq:tfjm.org", f"@{r.matrix_username}:tfjm.org") + Matrix.invite("#flood:tfjm.org", f"@{r.matrix_username}:tfjm.org") + Matrix.invite("#je-cherche-une-equipe:tfjm.org", + f"@{r.matrix_username}:tfjm.org") + self.stdout.write(f"Invite {r} in most common channels...") + + # Volunteers have access to the help channel + for volunteer in VolunteerRegistration.objects.all(): + Matrix.invite("#aide-jurys-orgas:tfjm.org", f"@{volunteer.matrix_username}:tfjm.org") + self.stdout.write(f"Invite {volunteer} in #aide-jury-orgas...") + + # Admins are admins + for admin in AdminRegistration.objects.all(): + self.stdout.write(f"Invite {admin} in #cno and #dev-bot...") + Matrix.invite("#cno:tfjm.org", f"@{admin.matrix_username}:tfjm.org") + Matrix.invite("#dev-bot:tfjm.org", f"@{admin.matrix_username}:tfjm.org") + + self.stdout.write(f"Give admin permissions for {admin}...") + Matrix.set_room_power_level("#aide-jurys-orgas:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level("#annonces:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level("#bienvenue:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level("#bot:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level("#cno:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level("#dev-bot:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level("#faq:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level("#flood:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level("#je-cherche-une-equipe:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + + # Create tournament-specific channels + for tournament in Tournament.objects.all(): + self.stdout.write(f"Managing tournament of {tournament.name}.") + + name = tournament.name + slug = name.lower().replace(" ", "-") + + if not async_to_sync(Matrix.resolve_room_alias)(f"#annonces-{slug}:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias=f"annonces-{slug}", + name=f"{name} - Annonces", + topic=f"Annonces du tournoi de {name}", + federate=False, + preset=RoomPreset.private_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)(f"#general-{slug}:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias=f"general-{slug}", + name=f"{name} - Général", + topic=f"Accueil du tournoi de {name}", + federate=False, + preset=RoomPreset.private_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)(f"#flood-{slug}:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias=f"flood-{slug}", + name=f"{name} - Flood", + topic=f"Discussion libre du tournoi de {name}", + federate=False, + preset=RoomPreset.private_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)(f"#jury-{slug}:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias=f"jury-{slug}", + name=f"{name} - Jury", + topic=f"Discussion entre les orgas et jurys du tournoi de {name}", + federate=False, + preset=RoomPreset.private_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)(f"#orga-{slug}:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias=f"orga-{slug}", + name=f"{name} - Organisateurs", + topic=f"Discussion entre les orgas du tournoi de {name}", + federate=False, + preset=RoomPreset.private_chat, + ) + + if not async_to_sync(Matrix.resolve_room_alias)(f"#tirage-au-sort-{slug}:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias=f"tirage-au-sort-{slug}", + name=f"{name} - Tirage au sort", + topic=f"Tirage au sort du tournoi de {name}", + federate=False, + preset=RoomPreset.private_chat, + ) + + # Setup avatars + Matrix.set_room_avatar(f"#annonces-{slug}:tfjm.org", avatar_uri) + Matrix.set_room_avatar(f"#flood-{slug}:tfjm.org", avatar_uri) + Matrix.set_room_avatar(f"#general-{slug}:tfjm.org", avatar_uri) + Matrix.set_room_avatar(f"#jury-{slug}:tfjm.org", avatar_uri) + Matrix.set_room_avatar(f"#orga-{slug}:tfjm.org", avatar_uri) + Matrix.set_room_avatar(f"#tirage-au-sort-{slug}:tfjm.org", avatar_uri) + + # Invite admins and give permissions + for admin in AdminRegistration.objects.all(): + self.stdout.write(f"Invite {admin} in all channels of the tournament {name}...") + Matrix.invite(f"#annonces-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org") + Matrix.invite(f"#flood-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org") + Matrix.invite(f"#general-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org") + Matrix.invite(f"#jury-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org") + Matrix.invite(f"#orga-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org") + Matrix.invite(f"#tirage-au-sort-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org") + + self.stdout.write(f"Give permissions to {admin} in all channels of the tournament {name}...") + Matrix.set_room_power_level(f"#annonces-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level(f"#flood-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level(f"#general-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level(f"#jury-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level(f"#orga-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level(f"#tirage-au-sort-{slug}:tfjm.org", f"@{admin.matrix_username}:tfjm.org", 95) + + # Invite organizers and give permissions + for orga in tournament.organizers.all(): + self.stdout.write(f"Invite organizer {orga} in all channels of the tournament {name}...") + Matrix.invite(f"#annonces-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org") + Matrix.invite(f"#flood-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org") + Matrix.invite(f"#general-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org") + Matrix.invite(f"#jury-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org") + Matrix.invite(f"#orga-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org") + Matrix.invite(f"#tirage-au-sort-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org") + + if not orga.is_admin: + Matrix.set_room_power_level(f"#annonces-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org", 50) + Matrix.set_room_power_level(f"#flood-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org", 50) + Matrix.set_room_power_level(f"#general-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org", 50) + Matrix.set_room_power_level(f"#jury-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org", 50) + Matrix.set_room_power_level(f"#orga-{slug}:tfjm.org", f"@{orga.matrix_username}:tfjm.org", 50) + Matrix.set_room_power_level(f"#tirage-au-sort-{slug}:tfjm.org", + f"@{orga.matrix_username}:tfjm.org", 50) + + # Invite participants + for participation in tournament.participations.filter(valid=True).all(): + for participant in participation.team.participants.all(): + self.stdout.write(f"Invite {participant} in public channels of the tournament {name}...") + Matrix.invite(f"#annonces-{slug}:tfjm.org", f"@{participant.matrix_username}:tfjm.org") + Matrix.invite(f"#flood-{slug}:tfjm.org", f"@{participant.matrix_username}:tfjm.org") + Matrix.invite(f"#general-{slug}:tfjm.org", f"@{participant.matrix_username}:tfjm.org") + Matrix.invite(f"#tirage-au-sort-{slug}:tfjm.org", f"@{participant.matrix_username}:tfjm.org") + + # Create pool-specific channels + for pool in tournament.pools.all(): + self.stdout.write(f"Managing {pool}...") + if not async_to_sync(Matrix.resolve_room_alias)(f"#poule-{slug}-{pool.id}:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias=f"poule-{slug}-{pool.id}", + name=f"{name} - Jour {pool.round} - Poule " + f"{', '.join(participation.team.trigram for participation in pool.participations.all())}", + topic=f"Discussion avec les équipes - {pool}", + federate=False, + preset=RoomPreset.private_chat, + ) + if not async_to_sync(Matrix.resolve_room_alias)(f"#poule-{slug}-{pool.id}-jurys:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias=f"poule-{slug}-{pool.id}-jurys", + name=f"{name} - Jour {pool.round} - Jurys poule " + f"{', '.join(participation.team.trigram for participation in pool.participations.all())}", + topic=f"Discussion avec les jurys - {pool}", + federate=False, + preset=RoomPreset.private_chat, + ) + + Matrix.set_room_avatar(f"#poule-{slug}-{pool.id}:tfjm.org", avatar_uri) + Matrix.set_room_avatar(f"#poule-{slug}-{pool.id}-jurys:tfjm.org", avatar_uri) + + url_params = urlencode(dict(url=f"https://visio.animath.live/b/{pool.bbb_code}", + isAudioConf='false', displayName='$matrix_display_name', + avatarUrl='$matrix_avatar_url', userId='$matrix_user_id')) \ + .replace("%24", "$") + Matrix.add_integration(f"#poule-{slug}-{pool.id}:tfjm.org", + f"https://scalar.vector.im/api/widgets/bigbluebutton.html?{url_params}", + f"bbb-{slug}-{pool.id}", "bigbluebutton", "BigBlueButton", str(pool)) + Matrix.add_integration(f"#poule-{slug}-{pool.id}:tfjm.org", + f"https://board.tfjm.org/boards/{slug}-{pool.id}", f"board-{slug}-{pool.id}", + "customwidget", "Tableau", str(pool)) + + # Invite admins and give permissions + for admin in AdminRegistration.objects.all(): + Matrix.invite(f"#poule-{slug}-{pool.id}:tfjm.org", f"@{admin.matrix_username}:tfjm.org") + Matrix.invite(f"#poule-{slug}-{pool.id}-jurys:tfjm.org", f"@{admin.matrix_username}:tfjm.org") + + Matrix.set_room_power_level(f"#poule-{slug}-{pool.id}:tfjm.org", + f"@{admin.matrix_username}:tfjm.org", 95) + Matrix.set_room_power_level(f"#poule-{slug}-{pool.id}-jurys:tfjm.org", + f"@{admin.matrix_username}:tfjm.org", 95) + + # Invite organizers and give permissions + for orga in VolunteerRegistration.objects.all(): + Matrix.invite(f"#poule-{slug}-{pool.id}:tfjm.org", f"@{orga.matrix_username}:tfjm.org") + Matrix.invite(f"#poule-{slug}-{pool.id}-jurys:tfjm.org", f"@{orga.matrix_username}:tfjm.org") + + if not orga.is_admin: + Matrix.set_room_power_level(f"#poule-{slug}-{pool.id}:tfjm.org", + f"@{orga.matrix_username}:tfjm.org", 50) + Matrix.set_room_power_level(f"#poule-{slug}-{pool.id}-jurys:tfjm.org", + f"@{orga.matrix_username}:tfjm.org", 50) + + # Invite the jury, give good permissions + for jury in pool.juries.all(): + Matrix.invite(f"#annonces-{slug}:tfjm.org", f"@{jury.matrix_username}:tfjm.org") + Matrix.invite(f"#general-{slug}:tfjm.org", f"@{jury.matrix_username}:tfjm.org") + Matrix.invite(f"#flood-{slug}:tfjm.org", f"@{jury.matrix_username}:tfjm.org") + Matrix.invite(f"#jury-{slug}:tfjm.org", f"@{jury.matrix_username}:tfjm.org") + Matrix.invite(f"#orga-{slug}:tfjm.org", f"@{jury.matrix_username}:tfjm.org") + Matrix.invite(f"#poule-{slug}-{pool.id}:tfjm.org", f"@{jury.matrix_username}:tfjm.org") + Matrix.invite(f"#poule-{slug}-{pool.id}-jurys:tfjm.org", f"@{jury.matrix_username}:tfjm.org") + Matrix.invite(f"#tirage-au-sort-{slug}:tfjm.org", f"@{jury.matrix_username}:tfjm.org") + + if not jury.is_admin: + Matrix.set_room_power_level(f"#jury-{slug}:tfjm.org", f"@{jury.matrix_username}:tfjm.org", 50) + Matrix.set_room_power_level(f"#poule-{slug}-{pool.id}:tfjm.org", + f"@{jury.matrix_username}:tfjm.org", 50) + Matrix.set_room_power_level(f"#poule-{slug}-{pool.id}-jurys:tfjm.org", + f"@{jury.matrix_username}:tfjm.org", 50) + + # Invite participants to the right pool + for participation in pool.participations.all(): + for participant in participation.team.participants.all(): + Matrix.invite(f"#poule-{slug}-{pool.id}:tfjm.org", f"@{participant.matrix_username}:tfjm.org") + + # Create private channels for teams + for team in Team.objects.all(): + self.stdout.write(f"Create private channel for {team}...") + if not async_to_sync(Matrix.resolve_room_alias)(f"#equipe-{team.trigram.lower()}:tfjm.org"): + Matrix.create_room( + visibility=RoomVisibility.public, + alias=f"equipe-{team.trigram.lower()}", + name=f"Équipe {team.trigram}", + topic=f"Discussion interne de l'équipe {team.name}", + federate=False, + preset=RoomPreset.private_chat, + ) + for participant in team.participants.all(): + Matrix.invite(f"#equipe-{team.trigram.lower}:tfjm.org", f"@{participant.matrix_username}:tfjm.org") + Matrix.set_room_power_level(f"#equipe-{team.trigram.lower()}:tfjm.org", + f"@{participant.matrix_username}:tfjm.org", 50) diff --git a/apps/participation/management/commands/fix_sympa_lists.py b/apps/participation/management/commands/fix_sympa_lists.py new file mode 100644 index 0000000..404309a --- /dev/null +++ b/apps/participation/management/commands/fix_sympa_lists.py @@ -0,0 +1,74 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.core.management import BaseCommand +from django.db.models import Q +from participation.models import Team, Tournament +from registration.models import AdminRegistration, ParticipantRegistration, VolunteerRegistration +from tfjm.lists import get_sympa_client + + +class Command(BaseCommand): + def handle(self, *args, **options): + """ + Create Sympa mailing lists and register teams. + """ + sympa = get_sympa_client() + + sympa.create_list("equipes", "Equipes du TFJM2", "hotline", + "Liste de diffusion pour contacter toutes les equipes validees du TFJM2.", + "education", raise_error=False) + sympa.create_list("equipes-non-valides", "Equipes non valides du TFJM2", "hotline", + "Liste de diffusion pour contacter toutes les equipes non validees du TFJM2.", + "education", raise_error=False) + + sympa.create_list("admins", "Administrateurs du TFJM2", "hotline", + "Liste de diffusion pour contacter tous les administrateurs du TFJM2.", + "education", raise_error=False) + sympa.create_list("organisateurs", "Organisateurs du TFJM2", "hotline", + "Liste de diffusion pour contacter tous les organisateurs du TFJM2.", + "education", raise_error=False) + sympa.create_list("jurys", "Jurys du TFJM2", "hotline", + "Liste de diffusion pour contacter tous les jurys du TFJM2.", + "education", raise_error=False) + + for tournament in Tournament.objects.all(): + slug = tournament.name.lower().replace(" ", "-") + sympa.create_list(f"equipes-{slug}", f"Equipes du tournoi {tournament.name}", "hotline", + f"Liste de diffusion pour contacter toutes les equipes du tournoi {tournament.name}" + " du TFJM2.", "education", raise_error=False) + sympa.create_list(f"organisateurs-{slug}", f"Organisateurs du tournoi {tournament.name}", "hotline", + "Liste de diffusion pour contacter tous les organisateurs du tournoi " + f"{tournament.name} du TFJM2.", "education", raise_error=False) + sympa.create_list(f"jurys-{slug}", f"Jurys du tournoi {tournament.name}", "hotline", + f"Liste de diffusion pour contacter tous les jurys du tournoi {tournament.name}" + f" du TFJM2.", "education", raise_error=False) + + sympa.subscribe(tournament.teams_email, "equipes", True) + sympa.subscribe(tournament.organizers_email, "organisateurs", True) + sympa.subscribe(tournament.jurys_email, "jurys", True) + + for team in Team.objects.filter(participation__valid=True).all(): + team.create_mailing_list() + sympa.unsubscribe(team.email, "equipes-non-valides", True) + sympa.subscribe(team.email, f"equipes-{team.participation.tournament.name.lower().replace(' ', '-')}", + True, f"Equipe {team.name}") + + for team in Team.objects.filter(Q(participation__valid=False) | Q(participation__valid__isnull=True)).all(): + team.create_mailing_list() + sympa.subscribe(team.email, "equipes-non-valides", f"Equipe {team.name}", True) + + for participant in ParticipantRegistration.objects.filter(team__isnull=False).all(): + sympa.subscribe(participant.user.email, f"equipe-{participant.team.trigram.lower}", True, f"{participant}") + + for volunteer in VolunteerRegistration.objects.all(): + for organized_tournament in volunteer.organized_tournaments.all(): + slug = organized_tournament.name.lower().replace(" ", "-") + sympa.subscribe(volunteer.user.email, f"organisateurs-{slug}", True) + + for jury_in in volunteer.jury_in.all(): + slug = jury_in.tournament.name.lower().replace(" ", "-") + sympa.subscribe(volunteer.user.email, f"jurys-{slug}", True) + + for admin in AdminRegistration.objects.all(): + sympa.subscribe(admin.user.email, "admins", True) diff --git a/apps/participation/migrations/0001_initial.py b/apps/participation/migrations/0001_initial.py new file mode 100644 index 0000000..44441c6 --- /dev/null +++ b/apps/participation/migrations/0001_initial.py @@ -0,0 +1,131 @@ +# Generated by Django 3.0.11 on 2021-01-21 21:06 + +import datetime +import django.core.validators +from django.db import migrations, models +import django.utils.timezone +import participation.models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Note', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('defender_writing', models.PositiveSmallIntegerField(choices=[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 16), (17, 17), (18, 18), (19, 19), (20, 20)], default=0, verbose_name='defender writing note')), + ('defender_oral', models.PositiveSmallIntegerField(choices=[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 16)], default=0, verbose_name='defender oral note')), + ('opponent_writing', models.PositiveSmallIntegerField(choices=[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)], default=0, verbose_name='opponent writing note')), + ('opponent_oral', models.PositiveSmallIntegerField(choices=[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)], default=0, verbose_name='opponent oral note')), + ('reporter_writing', models.PositiveSmallIntegerField(choices=[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)], default=0, verbose_name='reporter writing note')), + ('reporter_oral', models.PositiveSmallIntegerField(choices=[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)], default=0, verbose_name='reporter oral note')), + ], + options={ + 'verbose_name': 'note', + 'verbose_name_plural': 'notes', + }, + ), + migrations.CreateModel( + name='Participation', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('valid', models.BooleanField(default=None, help_text='The participation got the validation of the organizers.', null=True, verbose_name='valid')), + ('final', models.BooleanField(default=False, help_text='The team is selected for the final tournament.', verbose_name='selected for final')), + ], + options={ + 'verbose_name': 'participation', + 'verbose_name_plural': 'participations', + }, + ), + migrations.CreateModel( + name='Passage', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('place', models.CharField(default='Non indiqué', help_text='Where the solution is presented?', max_length=255, verbose_name='place')), + ('solution_number', models.PositiveSmallIntegerField(choices=[(1, 'Problem #1'), (2, 'Problem #2'), (3, 'Problem #3'), (4, 'Problem #4'), (5, 'Problem #5'), (6, 'Problem #6'), (7, 'Problem #7'), (8, 'Problem #8')], verbose_name='defended solution')), + ], + options={ + 'verbose_name': 'passage', + 'verbose_name_plural': 'passages', + }, + ), + migrations.CreateModel( + name='Pool', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('round', models.PositiveSmallIntegerField(choices=[(1, 'Round 1'), (2, 'Round 2')], verbose_name='round')), + ('bbb_code', models.CharField(blank=True, default='', help_text='The code of the form xxx-xxx-xxx at the end of the BBB link.', max_length=11, validators=[django.core.validators.RegexValidator('[a-z]{3}-[a-z]{3}-[a-z]{3}')], verbose_name='BigBlueButton code')), + ], + options={ + 'verbose_name': 'pool', + 'verbose_name_plural': 'pools', + }, + ), + migrations.CreateModel( + name='Solution', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('problem', models.PositiveSmallIntegerField(choices=[(1, 'Problem #1'), (2, 'Problem #2'), (3, 'Problem #3'), (4, 'Problem #4'), (5, 'Problem #5'), (6, 'Problem #6'), (7, 'Problem #7'), (8, 'Problem #8')], verbose_name='problem')), + ('final_solution', models.BooleanField(default=False, verbose_name='solution for the final tournament')), + ('file', models.FileField(blank=True, default='', unique=True, upload_to=participation.models.get_solution_filename, verbose_name='file')), + ], + options={ + 'verbose_name': 'solution', + 'verbose_name_plural': 'solutions', + }, + ), + migrations.CreateModel( + name='Synthesis', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('type', models.PositiveSmallIntegerField(choices=[(1, 'opponent'), (2, 'reporter')])), + ('file', models.FileField(blank=True, default='', unique=True, upload_to=participation.models.get_synthesis_filename, verbose_name='file')), + ], + options={ + 'verbose_name': 'synthesis', + 'verbose_name_plural': 'syntheses', + }, + ), + migrations.CreateModel( + name='Team', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, unique=True, verbose_name='name')), + ('trigram', models.CharField(help_text='The trigram must be composed of three uppercase letters.', max_length=3, unique=True, validators=[django.core.validators.RegexValidator('[A-Z]{3}')], verbose_name='trigram')), + ('access_code', models.CharField(help_text='The access code let other people to join the team.', max_length=6, verbose_name='access code')), + ], + options={ + 'verbose_name': 'team', + 'verbose_name_plural': 'teams', + }, + ), + migrations.CreateModel( + name='Tournament', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=255, unique=True, verbose_name='name')), + ('date_start', models.DateField(default=datetime.date.today, verbose_name='start')), + ('date_end', models.DateField(default=datetime.date.today, verbose_name='end')), + ('max_teams', models.PositiveSmallIntegerField(default=9, verbose_name='max team count')), + ('price', models.PositiveSmallIntegerField(default=21, verbose_name='price')), + ('inscription_limit', models.DateTimeField(default=django.utils.timezone.now, verbose_name='limit date for registrations')), + ('solution_limit', models.DateTimeField(default=django.utils.timezone.now, verbose_name='limit date to upload solutions')), + ('solutions_draw', models.DateTimeField(default=django.utils.timezone.now, verbose_name='random draw for solutions')), + ('syntheses_first_phase_limit', models.DateTimeField(default=django.utils.timezone.now, verbose_name='limit date to upload the syntheses for the first phase')), + ('solutions_available_second_phase', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date when the solutions for the second round become available')), + ('syntheses_second_phase_limit', models.DateTimeField(default=django.utils.timezone.now, verbose_name='limit date to upload the syntheses for the second phase')), + ('description', models.TextField(blank=True, verbose_name='description')), + ('final', models.BooleanField(default=False, verbose_name='final')), + ], + options={ + 'verbose_name': 'tournament', + 'verbose_name_plural': 'tournaments', + }, + ), + ] diff --git a/apps/participation/migrations/0002_auto_20210121_2206.py b/apps/participation/migrations/0002_auto_20210121_2206.py new file mode 100644 index 0000000..101af95 --- /dev/null +++ b/apps/participation/migrations/0002_auto_20210121_2206.py @@ -0,0 +1,115 @@ +# Generated by Django 3.0.11 on 2021-01-21 21:06 + +import address.models +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('address', '0003_auto_20200830_1851'), + ('registration', '0001_initial'), + ('participation', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='tournament', + name='organizers', + field=models.ManyToManyField(related_name='organized_tournaments', to='registration.VolunteerRegistration', verbose_name='organizers'), + ), + migrations.AddField( + model_name='tournament', + name='place', + field=address.models.AddressField(on_delete=django.db.models.deletion.CASCADE, to='address.Address', verbose_name='place'), + ), + migrations.AddIndex( + model_name='team', + index=models.Index(fields=['trigram'], name='participati_trigram_239255_idx'), + ), + migrations.AddField( + model_name='synthesis', + name='participation', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='participation.Participation', verbose_name='participation'), + ), + migrations.AddField( + model_name='synthesis', + name='passage', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='syntheses', to='participation.Passage', verbose_name='passage'), + ), + migrations.AddField( + model_name='solution', + name='participation', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='solutions', to='participation.Participation', verbose_name='participation'), + ), + migrations.AddField( + model_name='pool', + name='juries', + field=models.ManyToManyField(related_name='jury_in', to='registration.VolunteerRegistration', verbose_name='juries'), + ), + migrations.AddField( + model_name='pool', + name='participations', + field=models.ManyToManyField(related_name='pools', to='participation.Participation', verbose_name='participations'), + ), + migrations.AddField( + model_name='pool', + name='tournament', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='pools', to='participation.Tournament', verbose_name='tournament'), + ), + migrations.AddField( + model_name='passage', + name='defender', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='participation.Participation', verbose_name='defender'), + ), + migrations.AddField( + model_name='passage', + name='opponent', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='participation.Participation', verbose_name='opponent'), + ), + migrations.AddField( + model_name='passage', + name='pool', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='passages', to='participation.Pool', verbose_name='pool'), + ), + migrations.AddField( + model_name='passage', + name='reporter', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='participation.Participation', verbose_name='reporter'), + ), + migrations.AddField( + model_name='participation', + name='team', + field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='participation.Team', verbose_name='team'), + ), + migrations.AddField( + model_name='participation', + name='tournament', + field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='participation.Tournament', verbose_name='tournament'), + ), + migrations.AddField( + model_name='note', + name='jury', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notes', to='registration.VolunteerRegistration', verbose_name='jury'), + ), + migrations.AddField( + model_name='note', + name='passage', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notes', to='participation.Passage', verbose_name='passage'), + ), + migrations.AddIndex( + model_name='tournament', + index=models.Index(fields=['name', 'date_start', 'date_end'], name='participati_name_b43174_idx'), + ), + migrations.AlterUniqueTogether( + name='synthesis', + unique_together={('participation', 'passage', 'type')}, + ), + migrations.AlterUniqueTogether( + name='solution', + unique_together={('participation', 'problem', 'final_solution')}, + ), + ] diff --git a/apps/participation/migrations/__init__.py b/apps/participation/migrations/__init__.py new file mode 100644 index 0000000..dfc9706 --- /dev/null +++ b/apps/participation/migrations/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later diff --git a/apps/participation/models.py b/apps/participation/models.py new file mode 100644 index 0000000..d19a0d6 --- /dev/null +++ b/apps/participation/models.py @@ -0,0 +1,647 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from datetime import date +import os + +from address.models import AddressField +from django.conf import settings +from django.core.exceptions import ValidationError +from django.core.validators import RegexValidator +from django.db import models +from django.db.models import Index +from django.urls import reverse_lazy +from django.utils import timezone +from django.utils.crypto import get_random_string +from django.utils.text import format_lazy +from django.utils.translation import gettext_lazy as _ +from registration.models import VolunteerRegistration +from tfjm.lists import get_sympa_client +from tfjm.matrix import Matrix, RoomPreset, RoomVisibility + + +class Team(models.Model): + """ + The Team model represents a real team that participates to the TFJM². + This only includes the registration detail. + """ + name = models.CharField( + max_length=255, + verbose_name=_("name"), + unique=True, + ) + + trigram = models.CharField( + max_length=3, + verbose_name=_("trigram"), + help_text=_("The trigram must be composed of three uppercase letters."), + unique=True, + validators=[RegexValidator("[A-Z]{3}")], + ) + + access_code = models.CharField( + max_length=6, + verbose_name=_("access code"), + help_text=_("The access code let other people to join the team."), + ) + + @property + def students(self): + return self.participants.filter(studentregistration__isnull=False) + + @property + def coaches(self): + return self.participants.filter(coachregistration__isnull=False) + + @property + def email(self): + """ + :return: The mailing list to contact the team members. + """ + return f"equipe-{self.trigram.lower()}@{os.getenv('SYMPA_HOST', 'localhost')}" + + def create_mailing_list(self): + """ + Create a new Sympa mailing list to contact the team. + """ + get_sympa_client().create_list( + f"equipe-{self.trigram.lower()}", + f"Equipe {self.name} ({self.trigram})", + "hotline", # TODO Use a custom sympa template + f"Liste de diffusion pour contacter l'equipe {self.name} du TFJM2", + "education", + raise_error=False, + ) + + def delete_mailing_list(self): + """ + Drop the Sympa mailing list, if the team is empty or if the trigram changed. + """ + if self.participation.valid: # pragma: no cover + get_sympa_client().unsubscribe( + self.email, f"equipes-{self.participation.tournament.name.lower().replace(' ', '-')}", False) + else: + get_sympa_client().unsubscribe(self.email, "equipes-non-valides", False) + get_sympa_client().delete_list(f"equipe-{self.trigram}") + + def save(self, *args, **kwargs): + if not self.access_code: + # if the team got created, generate the access code, create the contact mailing list + # and create a dedicated Matrix room. + self.access_code = get_random_string(6) + self.create_mailing_list() + + Matrix.create_room( + visibility=RoomVisibility.private, + name=f"#équipe-{self.trigram.lower()}", + alias=f"equipe-{self.trigram.lower()}", + topic=f"Discussion de l'équipe {self.name}", + preset=RoomPreset.private_chat, + ) + + return super().save(*args, **kwargs) + + def get_absolute_url(self): + return reverse_lazy("participation:team_detail", args=(self.pk,)) + + def __str__(self): + return _("Team {name} ({trigram})").format(name=self.name, trigram=self.trigram) + + class Meta: + verbose_name = _("team") + verbose_name_plural = _("teams") + indexes = [ + Index(fields=("trigram", )), + ] + + +class Tournament(models.Model): + name = models.CharField( + max_length=255, + verbose_name=_("name"), + unique=True, + ) + + date_start = models.DateField( + verbose_name=_("start"), + default=date.today, + ) + + date_end = models.DateField( + verbose_name=_("end"), + default=date.today, + ) + + place = AddressField( + verbose_name=_("place"), + ) + + max_teams = models.PositiveSmallIntegerField( + verbose_name=_("max team count"), + default=9, + ) + + price = models.PositiveSmallIntegerField( + verbose_name=_("price"), + default=21, + ) + + inscription_limit = models.DateTimeField( + verbose_name=_("limit date for registrations"), + default=timezone.now, + ) + + solution_limit = models.DateTimeField( + verbose_name=_("limit date to upload solutions"), + default=timezone.now, + ) + + solutions_draw = models.DateTimeField( + verbose_name=_("random draw for solutions"), + default=timezone.now, + ) + + syntheses_first_phase_limit = models.DateTimeField( + verbose_name=_("limit date to upload the syntheses for the first phase"), + default=timezone.now, + ) + + solutions_available_second_phase = models.DateTimeField( + verbose_name=_("date when the solutions for the second round become available"), + default=timezone.now, + ) + + syntheses_second_phase_limit = models.DateTimeField( + verbose_name=_("limit date to upload the syntheses for the second phase"), + default=timezone.now, + ) + + description = models.TextField( + verbose_name=_("description"), + blank=True, + ) + + organizers = models.ManyToManyField( + VolunteerRegistration, + verbose_name=_("organizers"), + related_name="organized_tournaments", + ) + + final = models.BooleanField( + verbose_name=_("final"), + default=False, + ) + + @property + def teams_email(self): + """ + :return: The mailing list to contact the team members. + """ + return f"equipes-{self.name.lower().replace(' ', '-')}@{os.getenv('SYMPA_HOST', 'localhost')}" + + @property + def organizers_email(self): + """ + :return: The mailing list to contact the team members. + """ + return f"organisateurs-{self.name.lower().replace(' ', '-')}@{os.getenv('SYMPA_HOST', 'localhost')}" + + @property + def jurys_email(self): + """ + :return: The mailing list to contact the team members. + """ + return f"jurys-{self.name.lower().replace(' ', '-')}@{os.getenv('SYMPA_HOST', 'localhost')}" + + def create_mailing_lists(self): + """ + Create a new Sympa mailing list to contact the team. + """ + get_sympa_client().create_list( + f"equipes-{self.name.lower().replace(' ', '-')}", + f"Equipes du tournoi de {self.name}", + "hotline", # TODO Use a custom sympa template + f"Liste de diffusion pour contacter les equipes du tournoi {self.name} du TFJM²", + "education", + raise_error=False, + ) + get_sympa_client().create_list( + f"organisateurs-{self.name.lower().replace(' ', '-')}", + f"Organisateurs du tournoi de {self.name}", + "hotline", # TODO Use a custom sympa template + f"Liste de diffusion pour contacter les equipes du tournoi {self.name} du TFJM²", + "education", + raise_error=False, + ) + + @staticmethod + def final_tournament(): + qs = Tournament.objects.filter(final=True) + if qs.exists(): + return qs.get() + + @property + def participations(self): + if self.final: + return Participation.objects.filter(final=True) + return self.participation_set + + @property + def solutions(self): + if self.final: + return Solution.objects.filter(final_solution=True) + return Solution.objects.filter(participation__tournament=self) + + @property + def syntheses(self): + if self.final: + return Synthesis.objects.filter(final_solution=True) + return Synthesis.objects.filter(participation__tournament=self) + + def get_absolute_url(self): + return reverse_lazy("participation:tournament_detail", args=(self.pk,)) + + def __str__(self): + return self.name + + class Meta: + verbose_name = _("tournament") + verbose_name_plural = _("tournaments") + indexes = [ + Index(fields=("name", "date_start", "date_end", )), + ] + + +class Participation(models.Model): + """ + The Participation model contains all data that are related to the participation: + chosen problem, validity status, solutions,... + """ + team = models.OneToOneField( + Team, + on_delete=models.CASCADE, + verbose_name=_("team"), + ) + + tournament = models.ForeignKey( + Tournament, + on_delete=models.SET_NULL, + null=True, + blank=True, + default=None, + verbose_name=_("tournament"), + ) + + valid = models.BooleanField( + null=True, + default=None, + verbose_name=_("valid"), + help_text=_("The participation got the validation of the organizers."), + ) + + final = models.BooleanField( + default=False, + verbose_name=_("selected for final"), + help_text=_("The team is selected for the final tournament."), + ) + + def get_absolute_url(self): + return reverse_lazy("participation:participation_detail", args=(self.pk,)) + + def __str__(self): + return _("Participation of the team {name} ({trigram})").format(name=self.team.name, trigram=self.team.trigram) + + class Meta: + verbose_name = _("participation") + verbose_name_plural = _("participations") + + +class Pool(models.Model): + tournament = models.ForeignKey( + Tournament, + on_delete=models.CASCADE, + related_name="pools", + verbose_name=_("tournament"), + ) + + round = models.PositiveSmallIntegerField( + verbose_name=_("round"), + choices=[ + (1, format_lazy(_("Round {round}"), round=1)), + (2, format_lazy(_("Round {round}"), round=2)), + ] + ) + + participations = models.ManyToManyField( + Participation, + related_name="pools", + verbose_name=_("participations"), + ) + + juries = models.ManyToManyField( + VolunteerRegistration, + related_name="jury_in", + verbose_name=_("juries"), + ) + + bbb_code = models.CharField( + max_length=11, + blank=True, + default="", + verbose_name=_("BigBlueButton code"), + help_text=_("The code of the form xxx-xxx-xxx at the end of the BBB link."), + validators=[RegexValidator("[a-z]{3}-[a-z]{3}-[a-z]{3}")], + ) + + @property + def bbb_url(self): + return f"https://visio.animath.live/b/{self.bbb_code}" + + @property + def solutions(self): + return Solution.objects.filter(participation__in=self.participations, final_solution=self.tournament.final) + + def average(self, participation): + return sum(passage.average(participation) for passage in self.passages.all()) + + def get_absolute_url(self): + return reverse_lazy("participation:pool_detail", args=(self.pk,)) + + def __str__(self): + return _("Pool {round} for tournament {tournament} with teams {teams}")\ + .format(round=self.round, + tournament=str(self.tournament), + teams=", ".join(participation.team.trigram for participation in self.participations.all())) + + class Meta: + verbose_name = _("pool") + verbose_name_plural = _("pools") + + +class Passage(models.Model): + pool = models.ForeignKey( + Pool, + on_delete=models.CASCADE, + verbose_name=_("pool"), + related_name="passages", + ) + + place = models.CharField( + verbose_name=_("place"), + max_length=255, + help_text=_("Where the solution is presented?"), + default="Non indiqué", + ) + + solution_number = models.PositiveSmallIntegerField( + verbose_name=_("defended solution"), + choices=[ + (i, format_lazy(_("Problem #{problem}"), problem=i)) for i in range(1, settings.PROBLEM_COUNT + 1) + ], + ) + + defender = models.ForeignKey( + Participation, + on_delete=models.PROTECT, + verbose_name=_("defender"), + related_name="+", + ) + + opponent = models.ForeignKey( + Participation, + on_delete=models.PROTECT, + verbose_name=_("opponent"), + related_name="+", + ) + + reporter = models.ForeignKey( + Participation, + on_delete=models.PROTECT, + verbose_name=_("reporter"), + related_name="+", + ) + + @property + def defended_solution(self) -> "Solution": + return Solution.objects.get( + participation=self.defender, + problem=self.solution_number, + final_solution=self.pool.tournament.final) + + def avg(self, iterator) -> int: + items = [i for i in iterator if i] + return sum(items) / len(items) if items else 0 + + @property + def average_defender_writing(self) -> int: + return self.avg(note.defender_writing for note in self.notes.all()) + + @property + def average_defender_oral(self) -> int: + return self.avg(note.defender_oral for note in self.notes.all()) + + @property + def average_defender(self) -> int: + return self.average_defender_writing + 2 * self.average_defender_oral + + @property + def average_opponent_writing(self) -> int: + return self.avg(note.opponent_writing for note in self.notes.all()) + + @property + def average_opponent_oral(self) -> int: + return self.avg(note.opponent_oral for note in self.notes.all()) + + @property + def average_opponent(self) -> int: + return self.average_opponent_writing + 2 * self.average_opponent_oral + + @property + def average_reporter_writing(self) -> int: + return self.avg(note.reporter_writing for note in self.notes.all()) + + @property + def average_reporter_oral(self) -> int: + return self.avg(note.reporter_oral for note in self.notes.all()) + + @property + def average_reporter(self) -> int: + return self.average_reporter_writing + self.average_reporter_oral + + def average(self, participation): + return self.average_defender if participation == self.defender else self.average_opponent \ + if participation == self.opponent else self.average_reporter if participation == self.reporter else 0 + + def get_absolute_url(self): + return reverse_lazy("participation:passage_detail", args=(self.pk,)) + + def clean(self): + if self.defender not in self.pool.participations.all(): + raise ValidationError(_("Team {trigram} is not registered in the pool.") + .format(trigram=self.defender.team.trigram)) + if self.opponent not in self.pool.participations.all(): + raise ValidationError(_("Team {trigram} is not registered in the pool.") + .format(trigram=self.opponent.team.trigram)) + if self.reporter not in self.pool.participations.all(): + raise ValidationError(_("Team {trigram} is not registered in the pool.") + .format(trigram=self.reporter.team.trigram)) + return super().clean() + + def __str__(self): + return _("Passage of {defender} for problem {problem}")\ + .format(defender=self.defender.team, problem=self.solution_number) + + class Meta: + verbose_name = _("passage") + verbose_name_plural = _("passages") + + +def get_solution_filename(instance, filename): + return f"solutions/{instance.participation.team.trigram}_{instance.problem}" \ + + ("final" if instance.final_solution else "") + + +def get_synthesis_filename(instance, filename): + return f"syntheses/{instance.participation.team.trigram}_{instance.type}_{instance.passage.pk}" + + +class Solution(models.Model): + participation = models.ForeignKey( + Participation, + on_delete=models.CASCADE, + verbose_name=_("participation"), + related_name="solutions", + ) + + problem = models.PositiveSmallIntegerField( + verbose_name=_("problem"), + choices=[ + (i, format_lazy(_("Problem #{problem}"), problem=i)) for i in range(1, settings.PROBLEM_COUNT + 1) + ], + ) + + final_solution = models.BooleanField( + verbose_name=_("solution for the final tournament"), + default=False, + ) + + file = models.FileField( + verbose_name=_("file"), + upload_to=get_solution_filename, + unique=True, + blank=True, + default="", + ) + + def __str__(self): + return _("Solution of team {team} for problem {problem}")\ + .format(team=self.participation.team.name, problem=self.problem) + + class Meta: + verbose_name = _("solution") + verbose_name_plural = _("solutions") + unique_together = (('participation', 'problem', 'final_solution', ), ) + + +class Synthesis(models.Model): + participation = models.ForeignKey( + Participation, + on_delete=models.CASCADE, + verbose_name=_("participation"), + ) + + passage = models.ForeignKey( + Passage, + on_delete=models.CASCADE, + related_name="syntheses", + verbose_name=_("passage"), + ) + + type = models.PositiveSmallIntegerField( + choices=[ + (1, _("opponent"), ), + (2, _("reporter"), ), + ] + ) + + file = models.FileField( + verbose_name=_("file"), + upload_to=get_synthesis_filename, + unique=True, + blank=True, + default="", + ) + + def __str__(self): + return _("Synthesis for the {type} of the {passage}").format(type=self.get_type_display(), passage=self.passage) + + class Meta: + verbose_name = _("synthesis") + verbose_name_plural = _("syntheses") + unique_together = (('participation', 'passage', 'type', ), ) + + +class Note(models.Model): + jury = models.ForeignKey( + VolunteerRegistration, + on_delete=models.CASCADE, + verbose_name=_("jury"), + related_name="notes", + ) + + passage = models.ForeignKey( + Passage, + on_delete=models.CASCADE, + verbose_name=_("passage"), + related_name="notes", + ) + + defender_writing = models.PositiveSmallIntegerField( + verbose_name=_("defender writing note"), + choices=[(i, i) for i in range(0, 21)], + default=0, + ) + + defender_oral = models.PositiveSmallIntegerField( + verbose_name=_("defender oral note"), + choices=[(i, i) for i in range(0, 17)], + default=0, + ) + + opponent_writing = models.PositiveSmallIntegerField( + verbose_name=_("opponent writing note"), + choices=[(i, i) for i in range(0, 10)], + default=0, + ) + + opponent_oral = models.PositiveSmallIntegerField( + verbose_name=_("opponent oral note"), + choices=[(i, i) for i in range(0, 11)], + default=0, + ) + + reporter_writing = models.PositiveSmallIntegerField( + verbose_name=_("reporter writing note"), + choices=[(i, i) for i in range(0, 10)], + default=0, + ) + + reporter_oral = models.PositiveSmallIntegerField( + verbose_name=_("reporter oral note"), + choices=[(i, i) for i in range(0, 11)], + default=0, + ) + + def get_absolute_url(self): + return reverse_lazy("participation:passage_detail", args=(self.passage.pk,)) + + def __str__(self): + return _("Notes of {jury} for {passage}").format(jury=self.jury, passage=self.passage) + + def __bool__(self): + return any((self.defender_writing, self.defender_oral, self.opponent_writing, self.opponent_oral, + self.reporter_writing, self.reporter_oral)) + + class Meta: + verbose_name = _("note") + verbose_name_plural = _("notes") diff --git a/apps/participation/search_indexes.py b/apps/participation/search_indexes.py new file mode 100644 index 0000000..e67f758 --- /dev/null +++ b/apps/participation/search_indexes.py @@ -0,0 +1,36 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from haystack import indexes + +from .models import Participation, Team, Tournament + + +class TeamIndex(indexes.ModelSearchIndex, indexes.Indexable): + """ + Index all teams by their name and trigram. + """ + text = indexes.NgramField(document=True, use_template=True) + + class Meta: + model = Team + + +class ParticipationIndex(indexes.ModelSearchIndex, indexes.Indexable): + """ + Index all participations by their team name and team trigram. + """ + text = indexes.NgramField(document=True, use_template=True) + + class Meta: + model = Participation + + +class TournamentIndex(indexes.ModelSearchIndex, indexes.Indexable): + """ + Index all tournaments by their name. + """ + text = indexes.NgramField(document=True, use_template=True) + + class Meta: + model = Tournament diff --git a/apps/participation/signals.py b/apps/participation/signals.py new file mode 100644 index 0000000..d5b1394 --- /dev/null +++ b/apps/participation/signals.py @@ -0,0 +1,46 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later +from typing import Union + +from participation.models import Note, Participation, Passage, Pool, Team +from tfjm.lists import get_sympa_client + + +def create_team_participation(instance, created, **_): + """ + When a team got created, create an associated participation. + """ + participation = Participation.objects.get_or_create(team=instance)[0] + participation.save() + if not created: + participation.team.create_mailing_list() + + +def update_mailing_list(instance: Team, **_): + """ + When a team name or trigram got updated, update mailing lists and Matrix rooms + """ + if instance.pk: + old_team = Team.objects.get(pk=instance.pk) + if old_team.trigram != instance.trigram: + # TODO Rename Matrix room + # Delete old mailing list, create a new one + old_team.delete_mailing_list() + instance.create_mailing_list() + # Subscribe all team members in the mailing list + for student in instance.students.all(): + get_sympa_client().subscribe(student.user.email, f"equipe-{instance.trigram.lower()}", False, + f"{student.user.first_name} {student.user.last_name}") + for coach in instance.coaches.all(): + get_sympa_client().subscribe(coach.user.email, f"equipe-{instance.trigram.lower()}", False, + f"{coach.user.first_name} {coach.user.last_name}") + + +def create_notes(instance: Union[Passage, Pool], **_): + if isinstance(instance, Pool): + for passage in instance.passages.all(): + create_notes(passage) + return + + for jury in instance.pool.juries.all(): + Note.objects.get_or_create(jury=jury, passage=instance) diff --git a/apps/participation/tables.py b/apps/participation/tables.py new file mode 100644 index 0000000..7dea78d --- /dev/null +++ b/apps/participation/tables.py @@ -0,0 +1,142 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.utils import formats +from django.utils.text import format_lazy +from django.utils.translation import gettext_lazy as _ +import django_tables2 as tables + +from .models import Note, Passage, Pool, Team, Tournament + + +# noinspection PyTypeChecker +class TeamTable(tables.Table): + name = tables.LinkColumn( + 'participation:team_detail', + args=[tables.A("id")], + verbose_name=lambda: _("name").capitalize(), + ) + + class Meta: + attrs = { + 'class': 'table table-condensed table-striped', + } + model = Team + fields = ('name', 'trigram',) + template_name = 'django_tables2/bootstrap4.html' + + +# noinspection PyTypeChecker +class ParticipationTable(tables.Table): + name = tables.LinkColumn( + 'participation:team_detail', + args=[tables.A("team__id")], + verbose_name=_("name").capitalize, + accessor="team__name", + ) + + trigram = tables.Column( + verbose_name=_("trigram").capitalize, + accessor="team__trigram", + ) + + valid = tables.Column( + verbose_name=_("valid").capitalize, + accessor="valid", + empty_values=(), + ) + + def render_valid(self, value): + return _("Validated") if value else _("Validation pending") if value is False else _("Not validated") + + class Meta: + attrs = { + 'class': 'table table-condensed table-striped', + } + model = Team + fields = ('name', 'trigram', 'valid',) + template_name = 'django_tables2/bootstrap4.html' + + +class TournamentTable(tables.Table): + name = tables.LinkColumn() + + date = tables.Column(_("date").capitalize, accessor="id") + + def render_date(self, record): + return format_lazy(_("From {start} to {end}"), + start=formats.date_format(record.date_start, format="SHORT_DATE_FORMAT", use_l10n=True), + end=formats.date_format(record.date_end, format="SHORT_DATE_FORMAT", use_l10n=True)) + + class Meta: + attrs = { + 'class': 'table table-condensed table-striped', + } + model = Tournament + fields = ('name', 'date',) + template_name = 'django_tables2/bootstrap4.html' + + +class PoolTable(tables.Table): + teams = tables.LinkColumn( + 'participation:pool_detail', + args=[tables.A('id')], + verbose_name=_("teams").capitalize, + empty_values=(), + ) + + def render_teams(self, record): + return ", ".join(participation.team.trigram for participation in record.participations.all()) \ + or _("No defined team") + + class Meta: + attrs = { + 'class': 'table table-condensed table-striped', + } + model = Pool + fields = ('teams', 'round', 'tournament',) + template_name = 'django_tables2/bootstrap4.html' + + +class PassageTable(tables.Table): + defender = tables.LinkColumn( + "participation:passage_detail", + args=[tables.A("id")], + verbose_name=_("defender").capitalize, + ) + + def render_defender(self, value): + return value.team + + def render_opponent(self, value): + return value.team + + def render_reporter(self, value): + return value.team + + class Meta: + attrs = { + 'class': 'table table-condensed table-striped text-center', + } + model = Passage + fields = ('defender', 'opponent', 'reporter', 'place',) + template_name = 'django_tables2/bootstrap4.html' + + +class NoteTable(tables.Table): + jury = tables.Column( + attrs={ + "td": { + "class": "text-nowrap", + } + } + ) + + class Meta: + attrs = { + 'class': 'table table-condensed table-striped text-center', + } + model = Note + fields = ('jury', 'defender_writing', 'defender_oral', 'opponent_writing', 'opponent_oral', + 'reporter_writing', 'reporter_oral',) + template_name = 'django_tables2/bootstrap4.html' diff --git a/apps/participation/templates/participation/chat.html b/apps/participation/templates/participation/chat.html new file mode 100644 index 0000000..3a385f3 --- /dev/null +++ b/apps/participation/templates/participation/chat.html @@ -0,0 +1,39 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +
+ {% blocktrans trimmed %} + The chat is located on the dedicated Matrix server: + {% endblocktrans %} +
+ + + +
+

+ {% blocktrans trimmed %} + To connect to the server, you can select "Log in", then use your credentials of this platform to connect + with the central authentication server, then you must trust the connection between the Matrix account and the + platform. Finally, you will be able to access to the chat platform. + {% endblocktrans %} +

+ +

+ {% blocktrans trimmed %} + You will be invited in some basic rooms. You must confirm the invitations to join channels. + {% endblocktrans %} +

+ +

+ {% blocktrans trimmed %} + If you have any trouble, don't hesitate to contact us :) + {% endblocktrans %} +

+
+{% endblock %} diff --git a/apps/participation/templates/participation/create_team.html b/apps/participation/templates/participation/create_team.html new file mode 100644 index 0000000..1c93537 --- /dev/null +++ b/apps/participation/templates/participation/create_team.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} diff --git a/apps/participation/templates/participation/join_team.html b/apps/participation/templates/participation/join_team.html new file mode 100644 index 0000000..9beef23 --- /dev/null +++ b/apps/participation/templates/participation/join_team.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} \ No newline at end of file diff --git a/apps/participation/templates/participation/mails/request_validation.html b/apps/participation/templates/participation/mails/request_validation.html new file mode 100644 index 0000000..0f280fb --- /dev/null +++ b/apps/participation/templates/participation/mails/request_validation.html @@ -0,0 +1,29 @@ + + + + + Demande de validation - TFJM² + + +

+Bonjour {{ user.registration }}, +

+ +

+L'équipe « {{ team.name }} » ({{ team.trigram }}) vient de demander à valider son équipe pour participer +au {{ team.participation.get_problem_display }} du TFJM². +Vous pouvez décider d'accepter ou de refuser l'équipe en vous rendant sur la page de l'équipe : + + https://{{ domain }}{% url "participation:team_detail" pk=team.pk %} + +

+ +

+Cordialement, +

+ +

+L'organisation du TFJM² +

+ + diff --git a/apps/participation/templates/participation/mails/request_validation.txt b/apps/participation/templates/participation/mails/request_validation.txt new file mode 100644 index 0000000..f68a12c --- /dev/null +++ b/apps/participation/templates/participation/mails/request_validation.txt @@ -0,0 +1,10 @@ +Bonjour {{ user.registration }}, + +L'équipe « {{ team.name }} » ({{ team.trigram }}) vient de demander à valider son équipe pour participer +au {{ team.participation.get_problem_display }} du TFJM². +Vous pouvez décider d'accepter ou de refuser l'équipe en vous rendant sur la page de l'équipe : +https://{{ domain }}{% url "participation:team_detail" pk=team.pk %} + +Cordialement, + +L'organisation du TFJM² diff --git a/templates/mail_templates/unvalidate_team.html b/apps/participation/templates/participation/mails/team_not_validated.html similarity index 51% rename from templates/mail_templates/unvalidate_team.html rename to apps/participation/templates/participation/mails/team_not_validated.html index 1ba3ce8..915a003 100644 --- a/templates/mail_templates/unvalidate_team.html +++ b/apps/participation/templates/participation/mails/team_not_validated.html @@ -5,22 +5,18 @@ Équipe non validée – TFJM² -Bonjour {{ user }},
-
-Maleureusement, votre équipe « {{ team.name }} » ({{ team.trigram }}) n'a pas été validée. Veuillez vérifier que vos autorisations sont correctes. -{% if message %} -

- Le CNO vous adresse le message suivant : -

- {{ message }} -
-

-{% endif %} +Bonjour,

-N'hésitez pas à nous contacter à l'adresse contact@tfjm.org pour plus d'informations. +Maleureusement, votre équipe « {{ team.name }} » ({{ team.trigram }}) n'a pas été validée. Veuillez vérifier que vos autorisations +de droit à l'image sont correctes. Les organisateurs vous adressent ce message :
+
+{{ message }}
+
+N'hésitez pas à nous contacter à l'adresse contact@tfjm.org +pour plus d'informations.
-Avec toute notre bienveillance,
+Cordialement,

-Le comité national d'organisation du TFJM2 +Le comité d'organisation du TFJM² diff --git a/apps/participation/templates/participation/mails/team_not_validated.txt b/apps/participation/templates/participation/mails/team_not_validated.txt new file mode 100644 index 0000000..9479fba --- /dev/null +++ b/apps/participation/templates/participation/mails/team_not_validated.txt @@ -0,0 +1,12 @@ +Bonjour, + +Maleureusement, votre équipe « {{ team.name }} » ({{ team.trigram }}) n'a pas été validée. Veuillez vérifier que vos +autorisations de droit à l'image sont correctes. Les organisateurs vous adressent ce message : + +{{ message }} + +N'hésitez pas à nous contacter à l'adresse contact@tfjm.org pour plus d'informations. + +Cordialement, + +Le comité d'organisation du TFJM² diff --git a/apps/participation/templates/participation/mails/team_validated.html b/apps/participation/templates/participation/mails/team_validated.html new file mode 100644 index 0000000..c8b789c --- /dev/null +++ b/apps/participation/templates/participation/mails/team_validated.html @@ -0,0 +1,20 @@ + + + + + Équipe validée – TFJM² + + +Bonjour,
+
+Félicitations ! Votre équipe « {{ team.name }} » ({{ team.trigram }}) est désormais validée ! Vous êtes désormais apte +à travailler sur vos problèmes. Vous pourrez ensuite envoyer vos solutions sur la plateforme.
+Les organisateurs vous adressent ce message :
+
+{{ message }}
+
+Cordialement,
+
+Le comité d'organisation du TFJM² + + diff --git a/apps/participation/templates/participation/mails/team_validated.txt b/apps/participation/templates/participation/mails/team_validated.txt new file mode 100644 index 0000000..2653724 --- /dev/null +++ b/apps/participation/templates/participation/mails/team_validated.txt @@ -0,0 +1,12 @@ +Bonjour, + +Félicitations ! Votre équipe « {{ team.name }} » ({{ team.trigram }}) est désormais validée ! Vous êtes désormais apte +à travailler sur vos problèmes. Vous pourrez ensuite envoyer vos solutions sur la plateforme. + +Les organisateurs vous adressent ce message : + +{{ message }} + +Cordialement, + +Le comité d'organisation du TFJM² diff --git a/apps/participation/templates/participation/note_form.html b/apps/participation/templates/participation/note_form.html new file mode 100644 index 0000000..78231ff --- /dev/null +++ b/apps/participation/templates/participation/note_form.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} diff --git a/apps/participation/templates/participation/participation_detail.html b/apps/participation/templates/participation/participation_detail.html new file mode 100644 index 0000000..0b824b5 --- /dev/null +++ b/apps/participation/templates/participation/participation_detail.html @@ -0,0 +1,65 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +{% trans "any" as any %} +
+
+

{% trans "Participation of team" %} {{ participation.team.name }} ({{ participation.team.trigram }})

+
+
+
+
{% trans "Team:" %}
+
{{ participation.team }}
+ +
{% trans "Tournament:" %}
+
+ {% if participation.tournament %} + {{ participation.tournament }} + {% else %} + {% trans "any" %} + {% endif %} +
+ +
{% trans "Solutions:" %}
+
+ {% for solution in participation.solutions.all %} + {{ solution }}{% if not forloop.last %}, {% endif %} + {% empty %} + {% trans "No solution was uploaded yet." %} + {% endfor %} +
+ + {% if participation.pools.all %} +
{% trans "Pools:" %}
+
+ {% for pool in participation.pools.all %} + {{ pool }}{% if not forloop.last %}, {% endif %} + {% endfor %} +
+ {% endif %} +
+
+ +
+ + {% trans "Upload solution" as modal_title %} + {% trans "Upload" as modal_button %} + {% url "participation:upload_solution" pk=participation.pk as modal_action %} + {% include "base_modal.html" with modal_id="uploadSolution" modal_enctype="multipart/form-data" %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/participation/templates/participation/passage_detail.html b/apps/participation/templates/participation/passage_detail.html new file mode 100644 index 0000000..0fae622 --- /dev/null +++ b/apps/participation/templates/participation/passage_detail.html @@ -0,0 +1,140 @@ +{% extends "base.html" %} + +{% load django_tables2 i18n %} + +{% block content %} +{% trans "any" as any %} +
+
+

{{ passage }}

+
+
+
+
{% trans "Pool:" %}
+
{{ passage.pool }}
+ +
{% trans "Defender:" %}
+
{{ passage.defender.team }}
+ +
{% trans "Opponent:" %}
+
{{ passage.opponent.team }}
+ +
{% trans "Reporter:" %}
+
{{ passage.reporter.team }}
+ +
{% trans "Defended solution:" %}
+
{{ passage.defended_solution }}
+ +
{% trans "Place:" %}
+
{{ passage.place }}
+ +
{% trans "Syntheses:" %}
+
+ {% for synthesis in passage.syntheses.all %} + {{ synthesis }}{% if not forloop.last %}, {% endif %} + {% empty %} + {% trans "No synthesis was uploaded yet." %} + {% endfor %} +
+
+
+ {% if user.registration.is_admin %} + + {% elif user.registration.participates %} + + {% endif %} +
+ + {% if notes %} +
+ +

{% trans "Notes detail" %}

+ + {% render_table notes %} + +
+
+
+
{% trans "Average points for the defender writing:" %}
+
{{ passage.average_defender_writing }}/20
+ +
{% trans "Average points for the defender oral:" %}
+
{{ passage.average_defender_oral }}/16
+ +
{% trans "Average points for the opponent writing:" %}
+
{{ passage.average_opponent_writing }}/9
+ +
{% trans "Average points for the opponent oral:" %}
+
{{ passage.average_opponent_oral }}/10
+ +
{% trans "Average points for the reporter writing:" %}
+
{{ passage.average_reporter_writing }}/9
+ +
{% trans "Average points for the reporter oral:" %}
+
{{ passage.average_reporter_oral }}/10
+
+ +
+ +
+
{% trans "Defender points:" %}
+
{{ passage.average_defender }}/52
+ +
{% trans "Opponent points:" %}
+
{{ passage.average_opponent }}/29
+ +
{% trans "Reporter points:" %}
+
{{ passage.average_reporter }}/19
+
+
+
+ {% endif %} + + {% if user.registration.is_admin %} + {% trans "Update passage" as modal_title %} + {% trans "Update" as modal_button %} + {% url "participation:passage_update" pk=passage.pk as modal_action %} + {% include "base_modal.html" with modal_id="updatePassage" %} + + {% trans "Update notes" as modal_title %} + {% trans "Update" as modal_button %} + {% url "participation:update_notes" pk=my_note.pk as modal_action %} + {% include "base_modal.html" with modal_id="updateNotes" %} + {% elif user.registration.participates %} + {% trans "Upload synthesis" as modal_title %} + {% trans "Upload" as modal_button %} + {% url "participation:upload_synthesis" pk=passage.pk as modal_action %} + {% include "base_modal.html" with modal_id="uploadSynthesis" modal_enctype="multipart/form-data" %} + {% endif %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/participation/templates/participation/passage_form.html b/apps/participation/templates/participation/passage_form.html new file mode 100644 index 0000000..daabd59 --- /dev/null +++ b/apps/participation/templates/participation/passage_form.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} diff --git a/apps/participation/templates/participation/pool_detail.html b/apps/participation/templates/participation/pool_detail.html new file mode 100644 index 0000000..287cf71 --- /dev/null +++ b/apps/participation/templates/participation/pool_detail.html @@ -0,0 +1,105 @@ +{% extends "base.html" %} + +{% load django_tables2 i18n %} + +{% block content %} +
+
+

{{ pool }}

+
+
+
+
{% trans "Tournament:" %}
+
{{ pool.tournament }}
+ +
{% trans "Round:" %}
+
{{ pool.get_round_display }}
+ +
{% trans "Teams:" %}
+
+ {% for participation in pool.participations.all %} + {{ participation.team }}{% if not forloop.last %}, {% endif %} + {% endfor %} +
+ +
{% trans "Juries:" %}
+
{{ pool.juries.all|join:", " }}
+ +
{% trans "Defended solutions:" %}
+
+ {% for passage in pool.passages.all %} + {{ passage.defended_solution }}{% if not forloop.last %}, {% endif %} + {% endfor %} +
+ +
{% trans "BigBlueButton link:" %}
+
{{ pool.bbb_url }}
+
+ +
+
+
{% trans "Ranking" %}
+
+
+
    + {% for participation, note in notes %} +
  • {{ participation.team }} : {{ note }}
  • + {% endfor %} +
+
+
+
+ {% if user.registration.is_admin %} + + {% endif %} +
+ +
+ +

{% trans "Passages" %}

+ + {% render_table passages %} + + {% trans "Add passage" as modal_title %} + {% trans "Add" as modal_button %} + {% url "participation:passage_create" pk=pool.pk as modal_action %} + {% include "base_modal.html" with modal_id="addPassage" modal_button_type="success" %} + + {% trans "Update pool" as modal_title %} + {% trans "Update" as modal_button %} + {% url "participation:pool_update" pk=pool.pk as modal_action %} + {% include "base_modal.html" with modal_id="updatePool" %} + + {% trans "Update teams" as modal_title %} + {% trans "Update" as modal_button %} + {% url "participation:pool_update_teams" pk=pool.pk as modal_action %} + {% include "base_modal.html" with modal_id="updateTeams" %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/participation/templates/participation/pool_form.html b/apps/participation/templates/participation/pool_form.html new file mode 100644 index 0000000..ae9bb21 --- /dev/null +++ b/apps/participation/templates/participation/pool_form.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} diff --git a/apps/participation/templates/participation/team_detail.html b/apps/participation/templates/participation/team_detail.html new file mode 100644 index 0000000..03dc45f --- /dev/null +++ b/apps/participation/templates/participation/team_detail.html @@ -0,0 +1,175 @@ +{% extends "base.html" %} + +{% load i18n %} +{% load crispy_forms_filters %} + +{% block content %} +
+
+

{{ team.name }}

+
+
+
+
{% trans "Name:" %}
+
{{ team.name }}
+ +
{% trans "Trigram:" %}
+
{{ team.trigram }}
+ +
{% trans "Email:" %}
+
{{ team.email }}
+ +
{% trans "Access code:" %}
+
{{ team.access_code }}
+ +
{% trans "Coaches:" %}
+
+ {% for coach in team.coaches.all %} + {{ coach }}{% if not forloop.last %},{% endif %} + {% empty %} + {% trans "any" %} + {% endfor %} +
+ +
{% trans "Participants:" %}
+
+ {% for student in team.students.all %} + {{ student }}{% if not forloop.last %},{% endif %} + {% empty %} + {% trans "any" %} + {% endfor %} +
+ +
{% trans "Tournament:" %}
+
+ {% if team.participation.tournament %} + {{ team.participation.tournament }} + {% else %} + {% trans "any" %} + {% endif %} +
+ +
{% trans "Photo authorizations:" %}
+
+ {% for participant in team.participants.all %} + {% if participant.photo_authorization %} + {{ participant }}{% if not forloop.last %},{% endif %} + {% else %} + {{ participant }} ({% trans "Not uploaded yet" %}){% if not forloop.last %},{% endif %} + {% endif %} + {% endfor %} +
+ +
{% trans "Health sheets:" %}
+
+ {% for student in team.students.all %} + {% if student.under_18 %} + {% if student.health_sheet %} + {{ student }}{% if not forloop.last %},{% endif %} + {% else %} + {{ student }} ({% trans "Not uploaded yet" %}){% if not forloop.last %},{% endif %} + {% endif %} + {% endif %} + {% endfor %} +
+ +
{% trans "Parental authorizations:" %}
+
+ {% for student in team.students.all %} + {% if student.under_18 %} + {% if student.parental_authorization %} + {{ student }}{% if not forloop.last %},{% endif %} + {% else %} + {{ student }} ({% trans "Not uploaded yet" %}){% if not forloop.last %},{% endif %} + {% endif %} + {% endif %} + {% endfor %} +
+
+
+ +
+ +
+ + {% if team.participation.valid %} + + {% elif team.participation.valid == None %} {# Team did not ask for validation #} + {% if user.registration.participates %} + {% if can_validate %} +
+ {% trans "Your team has at least 4 members and a coach and all authorizations were given: the team can be validated." %} +
+
+ {% csrf_token %} + {{ request_validation_form|crispy }} + +
+
+
+ {% else %} +
+ {% trans "Your team must be composed of 4 members and a coach and each member must upload their authorizations and confirm its email address." %} +
+ {% endif %} + {% else %} +
+ {% trans "This team didn't ask for validation yet." %} +
+ {% endif %} + {% else %} {# Team is waiting for validation #} + {% if user.registration.participates %} +
+ {% trans "Your validation is pending." %} +
+ {% else %} +
+ {% trans "The team requested to be validated. You may now control the authorizations and confirm that they can participate." %} +
+
+ {% csrf_token %} + {{ validation_form|crispy }} +
+ + +
+
+ {% endif %} + {% endif %} + + {% trans "Update team" as modal_title %} + {% trans "Update" as modal_button %} + {% url "participation:update_team" pk=team.pk as modal_action %} + {% include "base_modal.html" with modal_id="updateTeam" %} + + {% trans "Leave team" as modal_title %} + {% trans "Leave" as modal_button %} + {% url "participation:team_leave" as modal_action %} + {% include "base_modal.html" with modal_id="leaveTeam" modal_button_type="danger" %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/participation/templates/participation/team_leave.html b/apps/participation/templates/participation/team_leave.html new file mode 100644 index 0000000..72d3db9 --- /dev/null +++ b/apps/participation/templates/participation/team_leave.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {% trans "Are you sure that you want to leave this team?" %} +
+ +
+{% endblock %} diff --git a/apps/participation/templates/participation/team_list.html b/apps/participation/templates/participation/team_list.html new file mode 100644 index 0000000..71d0b98 --- /dev/null +++ b/apps/participation/templates/participation/team_list.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load django_tables2 i18n %} + +{% block contenttitle %} +

{% trans "All teams" %}

+{% endblock %} + +{% block content %} +
+ {% render_table table %} +
+{% endblock %} diff --git a/apps/participation/templates/participation/tournament_detail.html b/apps/participation/templates/participation/tournament_detail.html new file mode 100644 index 0000000..d62150d --- /dev/null +++ b/apps/participation/templates/participation/tournament_detail.html @@ -0,0 +1,123 @@ +{% extends "base.html" %} + +{% load getconfig i18n django_tables2 %} + +{% block content %} +
+
+

{{ tournament.name }}

+
+
+
+
{% trans 'organizers'|capfirst %}
+
{{ tournament.organizers.all|join:", " }}
+ +
{% trans 'size'|capfirst %}
+
{{ tournament.max_teams }}
+ +
{% trans 'place'|capfirst %}
+
{{ tournament.place }}
+ +
{% trans 'price'|capfirst %}
+
{% if tournament.price %}{{ tournament.price }} €{% else %}{% trans "Free" %}{% endif %}
+ +
{% trans 'dates'|capfirst %}
+
{% trans "From" %} {{ tournament.date_start }} {% trans "to" %} {{ tournament.date_end }}
+ +
{% trans 'date of registration closing'|capfirst %}
+
{{ tournament.inscription_limit }}
+ +
{% trans 'date of maximal solution submission'|capfirst %}
+
{{ tournament.solution_limit }}
+ +
{% trans 'date of the random draw'|capfirst %}
+
{{ tournament.solutions_draw }}
+ +
{% trans 'date of maximal syntheses submission for the first round'|capfirst %}
+
{{ tournament.syntheses_first_phase_limit }}
+ +
{% trans 'date when solutions of round 2 are available'|capfirst %}
+
{{ tournament.solutions_available_second_phase }}
+ +
{% trans 'date of maximal syntheses submission for the second round'|capfirst %}
+
{{ tournament.syntheses_second_phase_limit }}
+ +
{% trans 'description'|capfirst %}
+
{{ tournament.description }}
+ +
{% trans 'To contact organizers' %}
+
{{ tournament.organizers_email }}
+ +
{% trans 'To contact juries' %}
+
{{ tournament.jurys_email }}
+ +
{% trans 'To contact valid teams' %}
+
{{ tournament.teams_email }}
+
+
+ + {% if user.registration.is_admin or user.registration in tournament.organizers.all %} + + {% endif %} +
+ +
+ +

{% trans "Teams" %}

+
+ {% render_table teams %} +
+ + {% if pools.data %} +
+ +

{% trans "Pools" %}

+
+ {% render_table pools %} +
+ {% endif %} + + {% if user.registration.is_admin %} + + {% endif %} + + {% if notes %} +
+ +
+
+
{% trans "Ranking" %}
+
+
+
    + {% for participation, note in notes %} +
  • {{ participation.team }} : {{ note }}
  • + {% endfor %} +
+
+
+ {% endif %} + + {% if user.registration.is_admin %} + {% trans "Add pool" as modal_title %} + {% trans "Add" as modal_button %} + {% url "participation:pool_create" as modal_action %} + {% include "base_modal.html" with modal_id="addPool" %} + {% endif %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/participation/templates/participation/tournament_form.html b/apps/participation/templates/participation/tournament_form.html new file mode 100644 index 0000000..e436656 --- /dev/null +++ b/apps/participation/templates/participation/tournament_form.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ {% if object.pk %} + + {% else %} + + {% endif %} +
+{% endblock content %} diff --git a/apps/participation/templates/participation/tournament_list.html b/apps/participation/templates/participation/tournament_list.html new file mode 100644 index 0000000..860342d --- /dev/null +++ b/apps/participation/templates/participation/tournament_list.html @@ -0,0 +1,16 @@ +{% extends "base.html" %} + +{% load django_tables2 i18n %} + +{% block contenttitle %} +

{% trans "All tournaments" %}

+{% endblock %} + +{% block content %} +
+ {% render_table table %} + {% if user.registration.is_admin %} + {% trans "Add tournament" %} + {% endif %} +
+{% endblock %} diff --git a/apps/participation/templates/participation/update_team.html b/apps/participation/templates/participation/update_team.html new file mode 100644 index 0000000..28f0d28 --- /dev/null +++ b/apps/participation/templates/participation/update_team.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} + {{ participation_form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/participation/templates/participation/upload_solution.html b/apps/participation/templates/participation/upload_solution.html new file mode 100644 index 0000000..378585f --- /dev/null +++ b/apps/participation/templates/participation/upload_solution.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} diff --git a/apps/participation/templates/participation/upload_synthesis.html b/apps/participation/templates/participation/upload_synthesis.html new file mode 100644 index 0000000..378585f --- /dev/null +++ b/apps/participation/templates/participation/upload_synthesis.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} diff --git a/apps/participation/templates/search/indexes/participation/participation_text.txt b/apps/participation/templates/search/indexes/participation/participation_text.txt new file mode 100644 index 0000000..740c12e --- /dev/null +++ b/apps/participation/templates/search/indexes/participation/participation_text.txt @@ -0,0 +1,3 @@ +{{ object.team.name }} +{{ object.team.trigram }} +{{ object.tournament.name }} diff --git a/apps/participation/templates/search/indexes/participation/team_text.txt b/apps/participation/templates/search/indexes/participation/team_text.txt new file mode 100644 index 0000000..d673407 --- /dev/null +++ b/apps/participation/templates/search/indexes/participation/team_text.txt @@ -0,0 +1,2 @@ +{{ object.name }} +{{ object.trigram }} diff --git a/apps/participation/templates/search/indexes/participation/tournament_text.txt b/apps/participation/templates/search/indexes/participation/tournament_text.txt new file mode 100644 index 0000000..b5fb63a --- /dev/null +++ b/apps/participation/templates/search/indexes/participation/tournament_text.txt @@ -0,0 +1,3 @@ +{{ object.name }} +{{ object.place }} +{{ object.description }} diff --git a/apps/participation/templates/search/indexes/participation/video_text.txt b/apps/participation/templates/search/indexes/participation/video_text.txt new file mode 100644 index 0000000..4303f3a --- /dev/null +++ b/apps/participation/templates/search/indexes/participation/video_text.txt @@ -0,0 +1,5 @@ +{{ object.link }} +{{ object.participation.team.name }} +{{ object.participation.team.trigram }} +{{ object.participation.problem }} +{{ object.participation.get_problem_display }} diff --git a/apps/participation/tests.py b/apps/participation/tests.py new file mode 100644 index 0000000..597a2f0 --- /dev/null +++ b/apps/participation/tests.py @@ -0,0 +1,585 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.contrib.auth.models import User +from django.contrib.contenttypes.models import ContentType +from django.contrib.sites.models import Site +from django.core.management import call_command +from django.test import TestCase +from django.urls import reverse +from registration.models import CoachRegistration, StudentRegistration + +from .models import Participation, Team, Tournament + + +class TestStudentParticipation(TestCase): + def setUp(self) -> None: + self.superuser = User.objects.create_superuser( + username="admin", + email="admin@example.com", + password="toto1234", + ) + + self.user = User.objects.create( + first_name="Toto", + last_name="Toto", + email="toto@example.com", + password="toto", + ) + StudentRegistration.objects.create( + user=self.user, + student_class=12, + school="Earth", + give_contact_to_animath=True, + email_confirmed=True, + ) + self.team = Team.objects.create( + name="Super team", + trigram="AAA", + access_code="azerty", + ) + self.client.force_login(self.user) + + self.second_user = User.objects.create( + first_name="Lalala", + last_name="Lalala", + email="lalala@example.com", + password="lalala", + ) + StudentRegistration.objects.create( + user=self.second_user, + student_class=11, + school="Moon", + give_contact_to_animath=True, + email_confirmed=True, + ) + self.second_team = Team.objects.create( + name="Poor team", + trigram="FFF", + access_code="qwerty", + ) + + self.coach = User.objects.create( + first_name="Coach", + last_name="Coach", + email="coach@example.com", + password="coach", + ) + CoachRegistration.objects.create(user=self.coach) + + self.tournament = Tournament.objects.create( + name="France", + place="Here", + ) + + def test_admin_pages(self): + """ + Load Django-admin pages. + """ + self.client.force_login(self.superuser) + + # Test team pages + response = self.client.get(reverse("admin:index") + "participation/team/") + self.assertEqual(response.status_code, 200) + + response = self.client.get(reverse("admin:index") + + f"participation/team/{self.team.pk}/change/") + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("admin:index") + + f"r/{ContentType.objects.get_for_model(Team).id}/" + f"{self.team.pk}/") + self.assertRedirects(response, "http://" + Site.objects.get().domain + + str(self.team.get_absolute_url()), 302, 200) + + # Test participation pages + self.team.participation.valid = True + self.team.participation.save() + response = self.client.get(reverse("admin:index") + "participation/participation/") + self.assertEqual(response.status_code, 200) + + response = self.client.get(reverse("admin:index") + + f"participation/participation/{self.team.participation.pk}/change/") + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("admin:index") + + f"r/{ContentType.objects.get_for_model(Participation).id}/" + f"{self.team.participation.pk}/") + self.assertRedirects(response, "http://" + Site.objects.get().domain + + str(self.team.participation.get_absolute_url()), 302, 200) + + def test_create_team(self): + """ + Try to create a team. + """ + response = self.client.get(reverse("participation:create_team")) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("participation:create_team"), data=dict( + name="Test team", + trigram="123", + )) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("participation:create_team"), data=dict( + name="Test team", + trigram="TES", + )) + self.assertTrue(Team.objects.filter(trigram="TES").exists()) + team = Team.objects.get(trigram="TES") + self.assertRedirects(response, reverse("participation:team_detail", args=(team.pk,)), 302, 200) + + # Already in a team + response = self.client.post(reverse("participation:create_team"), data=dict( + name="Test team 2", + trigram="TET", + )) + self.assertEqual(response.status_code, 403) + + def test_join_team(self): + """ + Try to join an existing team. + """ + response = self.client.get(reverse("participation:join_team")) + self.assertEqual(response.status_code, 200) + + team = Team.objects.create(name="Test", trigram="TES") + + response = self.client.post(reverse("participation:join_team"), data=dict( + access_code="éééééé", + )) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("participation:join_team"), data=dict( + access_code=team.access_code, + )) + self.assertRedirects(response, reverse("participation:team_detail", args=(team.pk,)), 302, 200) + self.assertTrue(Team.objects.filter(trigram="TES").exists()) + + # Already joined + response = self.client.post(reverse("participation:join_team"), data=dict( + access_code=team.access_code, + )) + self.assertEqual(response.status_code, 403) + + def test_team_list(self): + """ + Test to display the list of teams. + """ + response = self.client.get(reverse("participation:team_list")) + self.assertTrue(response.status_code, 200) + + def test_no_myteam_redirect_noteam(self): + """ + Test redirection. + """ + response = self.client.get(reverse("participation:my_team_detail")) + self.assertTrue(response.status_code, 200) + + def test_team_detail(self): + """ + Try to display the information of a team. + """ + self.user.registration.team = self.team + self.user.registration.save() + + response = self.client.get(reverse("participation:my_team_detail")) + self.assertRedirects(response, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200) + + response = self.client.get(reverse("participation:team_detail", args=(self.team.pk,))) + self.assertEqual(response.status_code, 200) + + # Can't see other teams + self.second_user.registration.team = self.second_team + self.second_user.registration.save() + self.client.force_login(self.second_user) + response = self.client.get(reverse("participation:team_detail", args=(self.team.participation.pk,))) + self.assertEqual(response.status_code, 403) + + def test_request_validate_team(self): + """ + The team ask for validation. + """ + self.user.registration.team = self.team + self.user.registration.save() + + second_user = User.objects.create( + first_name="Blublu", + last_name="Blublu", + email="blublu@example.com", + password="blublu", + ) + StudentRegistration.objects.create( + user=second_user, + student_class=12, + school="Jupiter", + give_contact_to_animath=True, + email_confirmed=True, + team=self.team, + photo_authorization="authorization/photo/mai-linh", + health_sheet="authorization/health/mai-linh", + parental_authorization="authorization/parental/mai-linh", + ) + + third_user = User.objects.create( + first_name="Zupzup", + last_name="Zupzup", + email="zupzup@example.com", + password="zupzup", + ) + StudentRegistration.objects.create( + user=third_user, + student_class=10, + school="Sun", + give_contact_to_animath=False, + email_confirmed=True, + team=self.team, + photo_authorization="authorization/photo/yohann", + health_sheet="authorization/health/yohann", + parental_authorization="authorization/parental/yohann", + ) + + fourth_user = User.objects.create( + first_name="tfjm", + last_name="tfjm", + email="tfjm@example.com", + password="tfjm", + ) + StudentRegistration.objects.create( + user=fourth_user, + student_class=10, + school="Sun", + give_contact_to_animath=False, + email_confirmed=True, + team=self.team, + photo_authorization="authorization/photo/tfjm", + health_sheet="authorization/health/tfjm", + parental_authorization="authorization/parental/tfjm", + ) + + self.coach.registration.team = self.team + self.coach.registration.health_sheet = "authorization/health/coach" + self.coach.registration.photo_authorization = "authorization/photo/coach" + self.coach.registration.email_confirmed = True + self.coach.registration.save() + + self.client.force_login(self.superuser) + # Admin users can't ask for validation + resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict( + _form_type="RequestValidationForm", + engagement=True, + )) + self.assertEqual(resp.status_code, 200) + + self.client.force_login(self.user) + + self.assertIsNone(self.team.participation.valid) + + resp = self.client.get(reverse("participation:team_detail", args=(self.team.pk,))) + self.assertEqual(resp.status_code, 200) + self.assertFalse(resp.context["can_validate"]) + # Can't validate + resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict( + _form_type="RequestValidationForm", + engagement=True, + )) + self.assertEqual(resp.status_code, 200) + + self.user.registration.photo_authorization = "authorization/photo/ananas" + self.user.registration.health_sheet = "authorization/health/ananas" + self.user.registration.parental_authorization = "authorization/parental/ananas" + self.user.registration.save() + + resp = self.client.get(reverse("participation:team_detail", args=(self.team.pk,))) + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.context["can_validate"]) + + resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict( + _form_type="RequestValidationForm", + engagement=True, + )) + self.assertRedirects(resp, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200) + self.team.participation.refresh_from_db() + self.assertFalse(self.team.participation.valid) + self.assertIsNotNone(self.team.participation.valid) + + # Team already asked for validation + resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict( + _form_type="RequestValidationForm", + engagement=True, + )) + self.assertEqual(resp.status_code, 200) + + def test_validate_team(self): + """ + A team asked for validation. Try to validate it. + """ + self.team.participation.valid = False + self.team.participation.save() + + # No right to do that + resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict( + _form_type="ValidateParticipationForm", + message="J'ai 4 ans", + validate=True, + )) + self.assertEqual(resp.status_code, 200) + + self.client.force_login(self.superuser) + + resp = self.client.get(reverse("participation:team_detail", args=(self.team.pk,))) + self.assertEqual(resp.status_code, 200) + + resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict( + _form_type="ValidateParticipationForm", + message="Woops I didn't said anything", + )) + self.assertEqual(resp.status_code, 200) + + # Test invalidate team + resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict( + _form_type="ValidateParticipationForm", + message="Wsh nope", + invalidate=True, + )) + self.assertRedirects(resp, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200) + self.team.participation.refresh_from_db() + self.assertIsNone(self.team.participation.valid) + + # Team did not ask validation + resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict( + _form_type="ValidateParticipationForm", + message="Bienvenue ça va être trop cool", + validate=True, + )) + self.assertEqual(resp.status_code, 200) + + self.team.participation.tournament = self.tournament + self.team.participation.valid = False + self.team.participation.save() + + # Test validate team + resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict( + _form_type="ValidateParticipationForm", + message="Bienvenue ça va être trop cool", + validate=True, + )) + self.assertRedirects(resp, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200) + self.team.participation.refresh_from_db() + self.assertTrue(self.team.participation.valid) + + def test_update_team(self): + """ + Try to update team information. + """ + self.user.registration.team = self.team + self.user.registration.save() + + self.coach.registration.team = self.team + self.coach.registration.save() + + response = self.client.get(reverse("participation:update_team", args=(self.team.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("participation:update_team", args=(self.team.pk,)), data=dict( + name="Updated team name", + trigram="BBB", + )) + self.assertRedirects(response, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200) + self.assertTrue(Team.objects.filter(trigram="BBB").exists()) + + def test_leave_team(self): + """ + A user is in a team, and leaves it. + """ + # User is not in a team + response = self.client.post(reverse("participation:team_leave")) + self.assertEqual(response.status_code, 403) + + self.user.registration.team = self.team + self.user.registration.save() + + # Team is valid + self.team.participation.valid = True + self.team.participation.save() + response = self.client.post(reverse("participation:team_leave")) + self.assertEqual(response.status_code, 403) + + # Unauthenticated users are redirected to login page + self.client.logout() + response = self.client.get(reverse("participation:team_leave")) + self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:team_leave"), 302, 200) + + self.client.force_login(self.user) + + self.team.participation.valid = None + self.team.participation.save() + + response = self.client.post(reverse("participation:team_leave")) + self.assertRedirects(response, reverse("index"), 302, 200) + self.user.registration.refresh_from_db() + self.assertIsNone(self.user.registration.team) + self.assertFalse(Team.objects.filter(pk=self.team.pk).exists()) + + def test_no_myparticipation_redirect_nomyparticipation(self): + """ + Ensure a permission denied when we search my team participation when we are in no team. + """ + response = self.client.get(reverse("participation:my_participation_detail")) + self.assertEqual(response.status_code, 403) + + def test_participation_detail(self): + """ + Try to display the detail of a team participation. + """ + self.user.registration.team = self.team + self.user.registration.save() + + # Can't see the participation if it is not valid + response = self.client.get(reverse("participation:my_participation_detail")) + self.assertRedirects(response, + reverse("participation:participation_detail", args=(self.team.participation.pk,)), + 302, 403) + + self.team.participation.valid = True + self.team.participation.save() + response = self.client.get(reverse("participation:my_participation_detail")) + self.assertRedirects(response, + reverse("participation:participation_detail", args=(self.team.participation.pk,)), + 302, 200) + + response = self.client.get(reverse("participation:participation_detail", args=(self.team.participation.pk,))) + self.assertEqual(response.status_code, 200) + + # Can't see other participations + self.second_user.registration.team = self.second_team + self.second_user.registration.save() + self.client.force_login(self.second_user) + response = self.client.get(reverse("participation:participation_detail", args=(self.team.participation.pk,))) + self.assertEqual(response.status_code, 403) + + def test_forbidden_access(self): + """ + Load personal pages and ensure that these are protected. + """ + self.user.registration.team = self.team + self.user.registration.save() + + resp = self.client.get(reverse("participation:team_detail", args=(self.second_team.pk,))) + self.assertEqual(resp.status_code, 403) + resp = self.client.get(reverse("participation:update_team", args=(self.second_team.pk,))) + self.assertEqual(resp.status_code, 403) + resp = self.client.get(reverse("participation:team_authorizations", args=(self.second_team.pk,))) + self.assertEqual(resp.status_code, 403) + resp = self.client.get(reverse("participation:participation_detail", args=(self.second_team.pk,))) + self.assertEqual(resp.status_code, 403) + + def test_cover_matrix(self): + """ + Load matrix scripts, to cover them and ensure that they can run. + """ + self.user.registration.team = self.team + self.user.registration.save() + self.second_user.registration.team = self.second_team + self.second_user.registration.save() + self.team.participation.valid = True + self.team.participation.received_participation = self.second_team.participation + self.team.participation.save() + + call_command('fix_matrix_channels') + + +class TestAdmin(TestCase): + def setUp(self) -> None: + self.user = User.objects.create_superuser( + username="admin@example.com", + email="admin@example.com", + password="admin", + ) + self.client.force_login(self.user) + + self.team1 = Team.objects.create( + name="Toto", + trigram="TOT", + ) + self.team1.participation.valid = True + self.team1.participation.problem = 1 + self.team1.participation.save() + + self.team2 = Team.objects.create( + name="Bliblu", + trigram="BIU", + ) + self.team2.participation.valid = True + self.team2.participation.problem = 1 + self.team2.participation.save() + + self.team3 = Team.objects.create( + name="Zouplop", + trigram="ZPL", + ) + self.team3.participation.valid = True + self.team3.participation.problem = 1 + self.team3.participation.save() + + self.other_team = Team.objects.create( + name="I am different", + trigram="IAD", + ) + self.other_team.participation.valid = True + self.other_team.participation.problem = 2 + self.other_team.participation.save() + + def test_research(self): + """ + Try to search some things. + """ + call_command("rebuild_index", "--noinput", "--verbosity", 0) + + response = self.client.get(reverse("haystack_search") + "?q=" + self.team1.name) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context["object_list"]) + + response = self.client.get(reverse("haystack_search") + "?q=" + self.team2.trigram) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context["object_list"]) + + def test_create_team_forbidden(self): + """ + Ensure that an admin can't create a team. + """ + response = self.client.post(reverse("participation:create_team"), data=dict( + name="Test team", + trigram="TES", + )) + self.assertEqual(response.status_code, 403) + + def test_join_team_forbidden(self): + """ + Ensure that an admin can't join a team. + """ + team = Team.objects.create(name="Test", trigram="TES") + + response = self.client.post(reverse("participation:join_team"), data=dict( + access_code=team.access_code, + )) + self.assertTrue(response.status_code, 403) + + def test_leave_team_forbidden(self): + """ + Ensure that an admin can't leave a team. + """ + response = self.client.get(reverse("participation:team_leave")) + self.assertTrue(response.status_code, 403) + + def test_my_team_forbidden(self): + """ + Ensure that an admin can't access to "My team". + """ + response = self.client.get(reverse("participation:my_team_detail")) + self.assertEqual(response.status_code, 403) + + def test_my_participation_forbidden(self): + """ + Ensure that an admin can't access to "My participation". + """ + response = self.client.get(reverse("participation:my_participation_detail")) + self.assertEqual(response.status_code, 403) diff --git a/apps/participation/urls.py b/apps/participation/urls.py new file mode 100644 index 0000000..8a4c289 --- /dev/null +++ b/apps/participation/urls.py @@ -0,0 +1,42 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.urls import path +from django.views.generic import TemplateView + +from .views import CreateTeamView, JoinTeamView, MyParticipationDetailView, MyTeamDetailView, NoteUpdateView, \ + ParticipationDetailView, PassageCreateView, PassageDetailView, PassageUpdateView, PoolCreateView, PoolDetailView, \ + PoolUpdateTeamsView, PoolUpdateView, SolutionUploadView, SynthesisUploadView, TeamAuthorizationsView, \ + TeamDetailView, TeamLeaveView, TeamListView, TeamUpdateView, TournamentCreateView, TournamentDetailView, \ + TournamentListView, TournamentUpdateView + + +app_name = "participation" + +urlpatterns = [ + path("create_team/", CreateTeamView.as_view(), name="create_team"), + path("join_team/", JoinTeamView.as_view(), name="join_team"), + path("teams/", TeamListView.as_view(), name="team_list"), + path("team/", MyTeamDetailView.as_view(), name="my_team_detail"), + path("team//", TeamDetailView.as_view(), name="team_detail"), + path("team//update/", TeamUpdateView.as_view(), name="update_team"), + path("team//authorizations/", TeamAuthorizationsView.as_view(), name="team_authorizations"), + path("team/leave/", TeamLeaveView.as_view(), name="team_leave"), + path("detail/", MyParticipationDetailView.as_view(), name="my_participation_detail"), + path("detail//", ParticipationDetailView.as_view(), name="participation_detail"), + path("detail//solution/", SolutionUploadView.as_view(), name="upload_solution"), + path("tournament/", TournamentListView.as_view(), name="tournament_list"), + path("tournament/create/", TournamentCreateView.as_view(), name="tournament_create"), + path("tournament//", TournamentDetailView.as_view(), name="tournament_detail"), + path("tournament//update/", TournamentUpdateView.as_view(), name="tournament_update"), + path("pools/create/", PoolCreateView.as_view(), name="pool_create"), + path("pools//", PoolDetailView.as_view(), name="pool_detail"), + path("pools//update/", PoolUpdateView.as_view(), name="pool_update"), + path("pools//update-teams/", PoolUpdateTeamsView.as_view(), name="pool_update_teams"), + path("pools/passages/add//", PassageCreateView.as_view(), name="passage_create"), + path("pools/passages//", PassageDetailView.as_view(), name="passage_detail"), + path("pools/passages//update/", PassageUpdateView.as_view(), name="passage_update"), + path("pools/passages//solution/", SynthesisUploadView.as_view(), name="upload_synthesis"), + path("pools/passages/notes//", NoteUpdateView.as_view(), name="update_notes"), + path("chat/", TemplateView.as_view(template_name="participation/chat.html"), name="chat") +] diff --git a/apps/participation/views.py b/apps/participation/views.py new file mode 100644 index 0000000..9e31f77 --- /dev/null +++ b/apps/participation/views.py @@ -0,0 +1,723 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from io import BytesIO +from zipfile import ZipFile + +from django.contrib.auth.mixins import LoginRequiredMixin +from django.contrib.sites.models import Site +from django.core.exceptions import PermissionDenied +from django.core.mail import send_mail +from django.db import transaction +from django.http import Http404, HttpResponse +from django.shortcuts import redirect +from django.template.loader import render_to_string +from django.urls import reverse_lazy +from django.utils import timezone +from django.utils.translation import gettext_lazy as _ +from django.views.generic import CreateView, DetailView, FormView, RedirectView, TemplateView, UpdateView +from django.views.generic.edit import FormMixin, ProcessFormView +from django_tables2 import SingleTableView +from magic import Magic +from registration.models import AdminRegistration, StudentRegistration +from tfjm.lists import get_sympa_client +from tfjm.matrix import Matrix +from tfjm.views import AdminMixin, VolunteerMixin + +from .forms import JoinTeamForm, NoteForm, ParticipationForm, PassageForm, PoolForm, PoolTeamsForm, \ + RequestValidationForm, SolutionForm, SynthesisForm, TeamForm, TournamentForm, ValidateParticipationForm +from .models import Note, Participation, Passage, Pool, Solution, Synthesis, Team, Tournament +from .tables import NoteTable, ParticipationTable, PassageTable, PoolTable, TeamTable, TournamentTable + + +class CreateTeamView(LoginRequiredMixin, CreateView): + """ + Display the page to create a team for new users. + """ + + model = Team + form_class = TeamForm + extra_context = dict(title=_("Create team")) + template_name = "participation/create_team.html" + + def dispatch(self, request, *args, **kwargs): + user = request.user + if not user.is_authenticated: + return super().handle_no_permission() + registration = user.registration + if not registration.participates: + raise PermissionDenied(_("You don't participate, so you can't create a team.")) + elif registration.team: + raise PermissionDenied(_("You are already in a team.")) + return super().dispatch(request, *args, **kwargs) + + @transaction.atomic + def form_valid(self, form): + """ + When a team is about to be created, the user automatically + joins the team, a mailing list got created and the user is + automatically subscribed to this mailing list, and finally + a Matrix room is created and the user is invited in this room. + """ + ret = super().form_valid(form) + # The user joins the team + user = self.request.user + registration = user.registration + registration.team = form.instance + registration.save() + + # Subscribe the user mail address to the team mailing list + get_sympa_client().subscribe(user.email, f"equipe-{form.instance.trigram.lower()}", False, + f"{user.first_name} {user.last_name}") + + # Invite the user in the team Matrix room + Matrix.invite(f"#equipe-{form.instance.trigram.lower()}:tfjm.org", + f"@{user.registration.matrix_username}:tfjm.org") + return ret + + +class JoinTeamView(LoginRequiredMixin, FormView): + """ + Participants can join a team with the access code of the team. + """ + model = Team + form_class = JoinTeamForm + extra_context = dict(title=_("Join team")) + template_name = "participation/create_team.html" + + def dispatch(self, request, *args, **kwargs): + user = request.user + if not user.is_authenticated: + return super().handle_no_permission() + registration = user.registration + if not registration.participates: + raise PermissionDenied(_("You don't participate, so you can't create a team.")) + elif registration.team: + raise PermissionDenied(_("You are already in a team.")) + return super().dispatch(request, *args, **kwargs) + + @transaction.atomic + def form_valid(self, form): + """ + When a user joins a team, the user is automatically subscribed to + the team mailing list,the user is invited in the team Matrix room. + """ + self.object = form.instance + ret = super().form_valid(form) + + # Join the team + user = self.request.user + registration = user.registration + registration.team = form.instance + registration.save() + + # Subscribe to the team mailing list + get_sympa_client().subscribe(user.email, f"equipe-{form.instance.trigram.lower()}", False, + f"{user.first_name} {user.last_name}") + + # Invite the user in the team Matrix room + Matrix.invite(f"#equipe-{form.instance.trigram.lower()}:tfjm.org", + f"@{user.registration.matrix_username}:tfjm.org") + return ret + + def get_success_url(self): + return reverse_lazy("participation:team_detail", args=(self.object.pk,)) + + +class TeamListView(AdminMixin, SingleTableView): + """ + Display the whole list of teams + """ + model = Team + table_class = TeamTable + ordering = ('trigram',) + + +class MyTeamDetailView(LoginRequiredMixin, RedirectView): + """ + Redirect to the detail of the team in which the user is. + """ + + def get_redirect_url(self, *args, **kwargs): + user = self.request.user + registration = user.registration + if registration.participates: + if registration.team: + return reverse_lazy("participation:team_detail", args=(registration.team_id,)) + raise PermissionDenied(_("You are not in a team.")) + raise PermissionDenied(_("You don't participate, so you don't have any team.")) + + +class TeamDetailView(LoginRequiredMixin, FormMixin, ProcessFormView, DetailView): + """ + Display the detail of a team. + """ + model = Team + + def get(self, request, *args, **kwargs): + user = request.user + self.object = self.get_object() + # Ensure that the user is an admin or a volunteer or a member of the team + if user.registration.is_admin or user.registration.participates and \ + user.registration.team and user.registration.team.pk == kwargs["pk"] \ + or user.registration.is_volunteer \ + and self.object.participation.tournament in user.registration.interesting_tournaments: + return super().get(request, *args, **kwargs) + raise PermissionDenied + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + + team = self.get_object() + context["title"] = _("Detail of team {trigram}").format(trigram=self.object.trigram) + context["request_validation_form"] = RequestValidationForm(self.request.POST or None) + context["validation_form"] = ValidateParticipationForm(self.request.POST or None) + # A team is complete when there are at least 4 members plus a coache that have sent their authorizations, + # their health sheet, they confirmed their email address and under-18 people sent their parental authorization. + context["can_validate"] = team.students.count() >= 4 and team.coaches.exists() and \ + all(r.email_confirmed for r in team.students.all()) and \ + all(r.photo_authorization for r in team.participants.all()) and \ + all(r.health_sheet for r in team.students.all() if r.under_18) and \ + all(r.parental_authorization for r in team.students.all() if r.under_18) + + return context + + def get_form_class(self): + if not self.request.POST: + return RequestValidationForm + elif self.request.POST["_form_type"] == "RequestValidationForm": + return RequestValidationForm + elif self.request.POST["_form_type"] == "ValidateParticipationForm": + return ValidateParticipationForm + + def form_valid(self, form): + self.object = self.get_object() + if isinstance(form, RequestValidationForm): + return self.handle_request_validation(form) + elif isinstance(form, ValidateParticipationForm): + return self.handle_validate_participation(form) + + def handle_request_validation(self, form): + """ + A team requests to be validated + """ + if not self.request.user.registration.participates: + form.add_error(None, _("You don't participate, so you can't request the validation of the team.")) + return self.form_invalid(form) + if self.object.participation.valid is not None: + form.add_error(None, _("The validation of the team is already done or pending.")) + return self.form_invalid(form) + if not self.get_context_data()["can_validate"]: + form.add_error(None, _("The team can't be validated: missing email address confirmations, " + "authorizations, people or the chosen problem is not set.")) + return self.form_invalid(form) + + self.object.participation.valid = False + self.object.participation.save() + + for admin in AdminRegistration.objects.all(): + mail_context = dict(user=admin.user, team=self.object, domain=Site.objects.first().domain) + mail_plain = render_to_string("participation/mails/request_validation.txt", mail_context) + mail_html = render_to_string("participation/mails/request_validation.html", mail_context) + admin.user.email_user("[TFJM²] Validation d'équipe", mail_plain, html_message=mail_html) + return super().form_valid(form) + + def handle_validate_participation(self, form): + """ + An admin validates the team (or not) + """ + if not self.request.user.registration.is_admin: + form.add_error(None, _("You are not an administrator.")) + return self.form_invalid(form) + elif self.object.participation.valid is not False: + form.add_error(None, _("This team has no pending validation.")) + return self.form_invalid(form) + + if "validate" in self.request.POST: + self.object.participation.valid = True + self.object.participation.save() + mail_context = dict(team=self.object, message=form.cleaned_data["message"]) + mail_plain = render_to_string("participation/mails/team_validated.txt", mail_context) + mail_html = render_to_string("participation/mails/team_validated.html", mail_context) + send_mail("[TFJM²] Équipe validée", mail_plain, None, [self.object.email], html_message=mail_html) + + if self.object.participation.tournament.price == 0: + for registration in self.object.participants.all(): + registration.payment.type = "free" + registration.payment.valid = True + registration.payment.save() + else: + for coach in self.object.coaches.all(): + coach.payment.type = "free" + coach.payment.valid = True + coach.payment.save() + elif "invalidate" in self.request.POST: + self.object.participation.valid = None + self.object.participation.save() + mail_context = dict(team=self.object, message=form.cleaned_data["message"]) + mail_plain = render_to_string("participation/mails/team_not_validated.txt", mail_context) + mail_html = render_to_string("participation/mails/team_not_validated.html", mail_context) + send_mail("[TFJM²] Équipe non validée", mail_plain, None, [self.object.email], + html_message=mail_html) + else: + form.add_error(None, _("You must specify if you validate the registration or not.")) + return self.form_invalid(form) + return super().form_valid(form) + + def get_success_url(self): + return self.request.path + + +class TeamUpdateView(LoginRequiredMixin, UpdateView): + """ + Update the detail of a team + """ + model = Team + form_class = TeamForm + template_name = "participation/update_team.html" + + def dispatch(self, request, *args, **kwargs): + user = request.user + if not user.is_authenticated: + return super().handle_no_permission() + if user.registration.is_admin or user.registration.participates and \ + user.registration.team and user.registration.team.pk == kwargs["pk"] \ + or user.registration.is_volunteer \ + and self.object.participation.tournament in user.registration.interesting_tournaments: + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + context["participation_form"] = ParticipationForm(data=self.request.POST or None, + instance=self.object.participation) + context["title"] = _("Update team {trigram}").format(trigram=self.object.trigram) + return context + + @transaction.atomic + def form_valid(self, form): + participation_form = ParticipationForm(data=self.request.POST or None, instance=self.object.participation) + if not participation_form.is_valid(): + return self.form_invalid(form) + + participation_form.save() + return super().form_valid(form) + + +class TeamAuthorizationsView(LoginRequiredMixin, DetailView): + """ + Get as a ZIP archive all the authorizations that are sent + """ + model = Team + + def dispatch(self, request, *args, **kwargs): + user = request.user + if not user.is_authenticated: + return super().handle_no_permission() + if user.registration.is_admin or user.registration.participates and user.registration.team.pk == kwargs["pk"] \ + or user.registration.is_volunteer \ + and self.object.participation.tournament in user.registration.interesting_tournaments: + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def get(self, request, *args, **kwargs): + team = self.get_object() + output = BytesIO() + zf = ZipFile(output, "w") + for participant in team.participants.all(): + magic = Magic(mime=True) + if participant.photo_authorization: + mime_type = magic.from_file("media/" + participant.photo_authorization.name) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + zf.write("media/" + participant.photo_authorization.name, + _("Photo authorization of {participant}.{ext}").format(participant=str(participant), ext=ext)) + + if isinstance(participant, StudentRegistration) and participant.parental_authorization: + mime_type = magic.from_file("media/" + participant.parental_authorization.name) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + zf.write("media/" + participant.parental_authorization.name, + _("Parental authorization of {participant}.{ext}") + .format(participant=str(participant), ext=ext)) + + if participant.health_sheet: + mime_type = magic.from_file("media/" + participant.health_sheet.name) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + zf.write("media/" + participant.health_sheet.name, + _("Health sheet of {participant}.{ext}").format(participant=str(participant), ext=ext)) + zf.close() + response = HttpResponse(content_type="application/zip") + response["Content-Disposition"] = "attachment; filename=\"{filename}\"" \ + .format(filename=_("Photo authorizations of team {trigram}.zip").format(trigram=team.trigram)) + response.write(output.getvalue()) + return response + + +class TeamLeaveView(LoginRequiredMixin, TemplateView): + """ + A team member leaves a team + """ + template_name = "participation/team_leave.html" + extra_context = dict(title=_("Leave team")) + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + if not request.user.registration.participates or not request.user.registration.team: + raise PermissionDenied(_("You are not in a team.")) + if request.user.registration.team.participation.valid: + raise PermissionDenied(_("The team is already validated or the validation is pending.")) + return super().dispatch(request, *args, **kwargs) + + @transaction.atomic() + def post(self, request, *args, **kwargs): + """ + When the team is left, the user is unsubscribed from the team mailing list + and kicked from the team room. + """ + team = request.user.registration.team + request.user.registration.team = None + request.user.registration.save() + get_sympa_client().unsubscribe(request.user.email, f"equipe-{team.trigram.lower()}", False) + Matrix.kick(f"#equipe-{team.trigram.lower()}:tfjm.org", + f"@{request.user.registration.matrix_username}:tfjm.org", + "Équipe quittée") + if team.students.count() + team.coaches.count() == 0: + team.delete() + return redirect(reverse_lazy("index")) + + +class MyParticipationDetailView(LoginRequiredMixin, RedirectView): + """ + Redirects to the detail view of the participation of the team. + """ + def get_redirect_url(self, *args, **kwargs): + user = self.request.user + registration = user.registration + if registration.participates: + if registration.team: + return reverse_lazy("participation:participation_detail", args=(registration.team.participation.id,)) + raise PermissionDenied(_("You are not in a team.")) + raise PermissionDenied(_("You don't participate, so you don't have any team.")) + + +class ParticipationDetailView(LoginRequiredMixin, DetailView): + """ + Display detail about the participation of a team, and manage the solution submission. + """ + model = Participation + + def dispatch(self, request, *args, **kwargs): + user = request.user + if not user.is_authenticated: + return super().handle_no_permission() + if not self.get_object().valid: + raise PermissionDenied(_("The team is not validated yet.")) + if user.registration.is_admin or user.registration.participates \ + and user.registration.team.participation \ + and user.registration.team.participation.pk == kwargs["pk"] \ + or user.registration.is_volunteer \ + and self.object.tournament in user.registration.interesting_tournaments: + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + + context["title"] = lambda: _("Participation of team {trigram}").format(trigram=self.object.team.trigram) + + return context + + +class TournamentListView(SingleTableView): + """ + Display the list of all tournaments. + """ + model = Tournament + table_class = TournamentTable + + +class TournamentCreateView(AdminMixin, CreateView): + """ + Create a new tournament. + """ + model = Tournament + form_class = TournamentForm + + def get_success_url(self): + return reverse_lazy("participation:tournament_detail", args=(self.object.pk,)) + + +class TournamentUpdateView(VolunteerMixin, UpdateView): + """ + Update tournament detail. + """ + model = Tournament + form_class = TournamentForm + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated or not self.request.user.registration.is_admin \ + and not (self.request.user.registration.is_volunteer + and self.request.user.registration.organized_tournaments.all()): + return self.handle_no_permission() + return super().dispatch(request, *args, **kwargs) + + +class TournamentDetailView(DetailView): + """ + Display tournament detail. + """ + model = Tournament + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + context["teams"] = ParticipationTable(self.object.participations.all()) + context["pools"] = PoolTable(self.object.pools.all()) + + notes = dict() + for participation in self.object.participations.all(): + note = sum(pool.average(participation) + for pool in self.object.pools.filter(participations=participation).all()) + if note: + notes[participation] = note + context["notes"] = sorted(notes.items(), key=lambda x: x[1], reverse=True) + + return context + + +class SolutionUploadView(LoginRequiredMixin, FormView): + template_name = "participation/upload_solution.html" + form_class = SolutionForm + + def dispatch(self, request, *args, **kwargs): + qs = Participation.objects.filter(pk=self.kwargs["pk"]) + if not qs.exists(): + raise Http404 + self.participation = qs.get() + if not self.request.user.is_authenticated or not self.request.user.registration.is_admin \ + and not (self.request.user.registration.participates + and self.request.user.registration.team == self.participation.team): + return self.handle_no_permission() + return super().dispatch(request, *args, **kwargs) + + def form_valid(self, form): + """ + When a solution is submitted, it replaces a previous solution if existing, + otherwise it creates a new solution. + It is discriminating whenever the team is selected for the final tournament or not. + """ + form_sol = form.instance + sol_qs = Solution.objects.filter(participation=self.participation, + problem=form_sol.problem, + final_solution=self.participation.final) + + tournament = Tournament.final_tournament() if self.participation.final else self.participation.final + if timezone.now() > tournament.solution_limit and sol_qs.exists(): + form.add_error(None, _("You can't upload a solution after the deadline.")) + return self.form_invalid(form) + + # Drop previous solution if existing + for sol in sol_qs.all(): + sol.file.delete() + sol.delete() + form_sol.participation = self.participation + form_sol.final = self.participation.final + form_sol.save() + return super().form_valid(form) + + def get_success_url(self): + return reverse_lazy("participation:participation_detail", args=(self.participation.pk,)) + + +class PoolCreateView(AdminMixin, CreateView): + model = Pool + form_class = PoolForm + + +class PoolDetailView(LoginRequiredMixin, DetailView): + model = Pool + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + if request.user.registration.is_admin or request.user.registration.participates \ + and request.user.registration.team \ + and request.user.registration.team.participation in self.get_object().participations.all() \ + or request.user.registration.is_volunteer \ + and self.get_object().tournament in request.user.registration.interesting_tournaments: + return super().dispatch(request, *args, **kwargs) + return self.handle_no_permission() + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + + context["passages"] = PassageTable(self.object.passages.all()) + + notes = dict() + for participation in self.object.participations.all(): + note = self.object.average(participation) + if note: + notes[participation] = note + context["notes"] = sorted(notes.items(), key=lambda x: x[1], reverse=True) + + return context + + +class PoolUpdateView(VolunteerMixin, UpdateView): + model = Pool + form_class = PoolForm + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + if request.user.registration.is_admin or request.user.registration.is_volunteer \ + and (self.get_object().tournament in request.user.registration.organized_tournaments.all() + or request.user.registration in self.get_object().juries.all()): + return super().dispatch(request, *args, **kwargs) + return self.handle_no_permission() + + +class PoolUpdateTeamsView(VolunteerMixin, UpdateView): + model = Pool + form_class = PoolTeamsForm + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + if request.user.registration.is_admin or request.user.registration.is_volunteer \ + and (self.get_object().tournament in request.user.registration.organized_tournaments.all() + or request.user.registration in self.get_object().juries.all()): + return super().dispatch(request, *args, **kwargs) + return self.handle_no_permission() + + +class PassageCreateView(VolunteerMixin, CreateView): + model = Passage + form_class = PassageForm + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + + qs = Pool.objects.filter(pk=self.kwargs["pk"]) + if not qs.exists(): + raise Http404 + self.pool = qs.get() + + if request.user.registration.is_admin or request.user.registration.is_volunteer \ + and (self.pool.tournament in request.user.registration.organized_tournaments.all() + or request.user.registration in self.pool.juries.all()): + return super().dispatch(request, *args, **kwargs) + + return self.handle_no_permission() + + def get_form(self, form_class=None): + form = super().get_form(form_class) + form.instance.pool = self.pool + form.fields["defender"].queryset = self.pool.participations.all() + form.fields["opponent"].queryset = self.pool.participations.all() + form.fields["reporter"].queryset = self.pool.participations.all() + return form + + +class PassageDetailView(LoginRequiredMixin, DetailView): + model = Passage + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + if request.user.registration.is_admin or request.user.registration.is_volunteer \ + and (self.get_object().pool.tournament in request.user.registration.organized_tournaments.all() + or request.user.registration in self.get_object().pool.juries.all()) \ + or request.user.registration.participates and request.user.registration.team \ + and request.user.registration.team.participation in [self.get_object().defender, + self.get_object().opponent, + self.get_object().reporter]: + return super().dispatch(request, *args, **kwargs) + return self.handle_no_permission() + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + if self.request.user.registration in self.object.pool.juries.all(): + context["my_note"] = Note.objects.get(passage=self.object, jury=self.request.user.registration) + context["notes"] = NoteTable([note for note in self.object.notes.all() if note]) + return context + + +class PassageUpdateView(VolunteerMixin, UpdateView): + model = Passage + form_class = PassageForm + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + + if request.user.registration.is_admin or request.user.registration.is_volunteer \ + and (self.get_object().pool.tournament in request.user.registration.organized_tournaments.all() + or request.user.registration in self.get_object().pool.juries.all()): + return super().dispatch(request, *args, **kwargs) + + return self.handle_no_permission() + + +class SynthesisUploadView(LoginRequiredMixin, FormView): + template_name = "participation/upload_synthesis.html" + form_class = SynthesisForm + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated or not request.user.registration.participates: + return self.handle_no_permission() + + qs = Passage.objects.filter(pk=self.kwargs["pk"]) + if not qs.exists(): + raise Http404 + self.participation = self.request.user.registration.team.participation + self.passage = qs.get() + + if self.participation not in [self.passage.defender, self.passage.opponent, self.passage.reporter]: + return self.handle_no_permission() + + return super().dispatch(request, *args, **kwargs) + + def form_valid(self, form): + """ + When a solution is submitted, it replaces a previous solution if existing, + otherwise it creates a new solution. + It is discriminating whenever the team is selected for the final tournament or not. + """ + form_syn = form.instance + syn_qs = Synthesis.objects.filter(participation=self.participation, + passage=self.passage, + type=form_syn.type).all() + + deadline = self.passage.pool.tournament.syntheses_first_phase_limit if self.passage.pool.round == 1 \ + else self.passage.pool.tournament.syntheses_second_phase_limit + if syn_qs.exists() and timezone.now() > deadline: + form.add_error(None, _("You can't upload a synthesis after the deadline.")) + return self.form_invalid(form) + + # Drop previous solution if existing + for syn in syn_qs.all(): + syn.file.delete() + syn.delete() + form_syn.participation = self.participation + form_syn.passage = self.passage + form_syn.save() + return super().form_valid(form) + + def get_success_url(self): + return reverse_lazy("participation:passage_detail", args=(self.passage.pk,)) + + +class NoteUpdateView(VolunteerMixin, UpdateView): + model = Note + form_class = NoteForm + + def dispatch(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return self.handle_no_permission() + + if request.user.registration.is_admin or request.user.registration.is_volunteer \ + and self.get_object().jury == request.user.registration: + return super().dispatch(request, *args, **kwargs) + + return self.handle_no_permission() diff --git a/apps/registration/__init__.py b/apps/registration/__init__.py new file mode 100644 index 0000000..6d49a03 --- /dev/null +++ b/apps/registration/__init__.py @@ -0,0 +1,4 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +default_app_config = 'registration.apps.RegistrationConfig' diff --git a/apps/registration/admin.py b/apps/registration/admin.py new file mode 100644 index 0000000..04486cb --- /dev/null +++ b/apps/registration/admin.py @@ -0,0 +1,37 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.contrib import admin +from django.contrib.admin import ModelAdmin +from polymorphic.admin import PolymorphicChildModelAdmin, PolymorphicParentModelAdmin + +from .models import AdminRegistration, CoachRegistration, Payment, Registration, StudentRegistration + + +@admin.register(Registration) +class RegistrationAdmin(PolymorphicParentModelAdmin): + child_models = (StudentRegistration, CoachRegistration, AdminRegistration,) + list_display = ("user", "type", "email_confirmed",) + polymorphic_list = True + + +@admin.register(StudentRegistration) +class StudentRegistrationAdmin(PolymorphicChildModelAdmin): + pass + + +@admin.register(CoachRegistration) +class CoachRegistrationAdmin(PolymorphicChildModelAdmin): + pass + + +@admin.register(AdminRegistration) +class AdminRegistrationAdmin(PolymorphicChildModelAdmin): + pass + + +@admin.register(Payment) +class PaymentAdmin(ModelAdmin): + list_display = ('registration', 'type', 'valid', ) + search_fields = ('registration__user__last_name', 'registration__user__first_name', 'registration__user__email',) + list_filter = ('type', 'valid',) diff --git a/apps/registration/apps.py b/apps/registration/apps.py new file mode 100644 index 0000000..e846ea5 --- /dev/null +++ b/apps/registration/apps.py @@ -0,0 +1,23 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.apps import AppConfig +from django.db.models.signals import post_save, pre_save + + +class RegistrationConfig(AppConfig): + """ + Registration app contains the detail about users only. + """ + name = 'registration' + + def ready(self): + from registration.signals import create_admin_registration, create_payment, \ + set_username, send_email_link + pre_save.connect(set_username, "auth.User") + pre_save.connect(send_email_link, "auth.User") + post_save.connect(create_admin_registration, "auth.User") + post_save.connect(create_payment, "registration.Registration") + post_save.connect(create_payment, "registration.StudentRegistration") + post_save.connect(create_payment, "registration.CoachRegistration") + post_save.connect(create_payment, "registration.AdminRegistration") diff --git a/apps/registration/auth.py b/apps/registration/auth.py new file mode 100644 index 0000000..78b0a84 --- /dev/null +++ b/apps/registration/auth.py @@ -0,0 +1,17 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from cas_server.auth import DjangoAuthUser # pragma: no cover + + +class CustomAuthUser(DjangoAuthUser): # pragma: no cover + """ + Override Django Auth User model to define a custom Matrix username. + """ + + def attributs(self): + d = super().attributs() + if self.user: + d["matrix_username"] = self.user.registration.matrix_username + d["display_name"] = str(self.user.registration) + return d diff --git a/apps/registration/fixtures/initial.json b/apps/registration/fixtures/initial.json new file mode 100644 index 0000000..05c50df --- /dev/null +++ b/apps/registration/fixtures/initial.json @@ -0,0 +1,26 @@ +[ + { + "model": "cas_server.servicepattern", + "pk": 1, + "fields": { + "pos": 100, + "name": "Plateforme du TFJM²", + "pattern": "^https://tfjm.org:8448/.*$", + "user_field": "matrix_username", + "restrict_users": false, + "proxy": true, + "proxy_callback": true, + "single_log_out": true, + "single_log_out_callback": "" + } + }, + { + "model": "cas_server.replaceattributname", + "pk": 1, + "fields": { + "name": "display_name", + "replace": "", + "service_pattern": 1 + } + } +] diff --git a/apps/registration/forms.py b/apps/registration/forms.py new file mode 100644 index 0000000..ac4650b --- /dev/null +++ b/apps/registration/forms.py @@ -0,0 +1,230 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django import forms +from django.contrib.auth.forms import UserCreationForm +from django.contrib.auth.models import User +from django.core.exceptions import ValidationError +from django.forms import FileInput +from django.utils.translation import gettext_lazy as _ + +from .models import AdminRegistration, CoachRegistration, Payment, StudentRegistration, VolunteerRegistration + + +class SignupForm(UserCreationForm): + """ + Signup form to registers participants and coaches + They can choose the role at the registration. + """ + + role = forms.ChoiceField( + label=lambda: _("role").capitalize(), + choices=lambda: [ + ("participant", _("participant").capitalize()), + ("coach", _("coach").capitalize()), + ], + ) + + def clean_email(self): + """ + Ensure that the email address is unique. + """ + email = self.data["email"] + if User.objects.filter(email=email).exists(): + self.add_error("email", _("This email address is already used.")) + return email + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["first_name"].required = True + self.fields["last_name"].required = True + self.fields["email"].required = True + + class Meta: + model = User + fields = ('first_name', 'last_name', 'email', 'password1', 'password2', 'role',) + + +class AddOrganizerForm(forms.ModelForm): + """ + Signup form to registers volunteers + """ + type = forms.ChoiceField( + label=lambda: _("role").capitalize(), + choices=lambda: [ + ("volunteer", _("volunteer").capitalize()), + ("admin", _("admin").capitalize()), + ], + initial="volunteer", + ) + + def clean_email(self): + """ + Ensure that the email address is unique. + """ + email = self.data["email"] + if User.objects.filter(email=email).exists(): + self.add_error("email", _("This email address is already used.")) + return email + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["first_name"].required = True + self.fields["last_name"].required = True + self.fields["email"].required = True + + class Meta: + model = User + fields = ('first_name', 'last_name', 'email', 'type',) + + +class UserForm(forms.ModelForm): + """ + Replace the default user form to require the first name, last name and the email. + The username is always equal to the email. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["first_name"].required = True + self.fields["last_name"].required = True + self.fields["email"].required = True + + class Meta: + model = User + fields = ('first_name', 'last_name', 'email',) + + +class StudentRegistrationForm(forms.ModelForm): + """ + A student can update its class, its school and if it allows Animath to contact him/her later. + """ + class Meta: + model = StudentRegistration + fields = ('team', 'student_class', 'birth_date', 'address', 'phone_number', + 'school', 'responsible_name', 'responsible_phone', 'responsible_email', + 'give_contact_to_animath', 'email_confirmed',) + + +class PhotoAuthorizationForm(forms.ModelForm): + """ + Form to send a photo authorization. + """ + def clean_photo_authorization(self): + if "photo_authorization" in self.files: + file = self.files["photo_authorization"] + if file.size > 2e6: + raise ValidationError(_("The uploaded file size must be under 2 Mo.")) + if file.content_type not in ["application/pdf", "image/png", "image/jpeg"]: + raise ValidationError(_("The uploaded file must be a PDF, PNG of JPEG file.")) + return self.cleaned_data["photo_authorization"] + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["photo_authorization"].widget = FileInput() + + class Meta: + model = StudentRegistration + fields = ('photo_authorization',) + + +class HealthSheetForm(forms.ModelForm): + """ + Form to send a health sheet. + """ + def clean_health_sheet(self): + if "health_sheet" in self.files: + file = self.files["health_sheet"] + if file.size > 2e6: + raise ValidationError(_("The uploaded file size must be under 2 Mo.")) + if file.content_type not in ["application/pdf", "image/png", "image/jpeg"]: + raise ValidationError(_("The uploaded file must be a PDF, PNG of JPEG file.")) + return self.cleaned_data["health_sheet"] + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["health_sheet"].widget = FileInput() + + class Meta: + model = StudentRegistration + fields = ('health_sheet',) + + +class ParentalAuthorizationForm(forms.ModelForm): + """ + Form to send a parental authorization. + """ + def clean_parental_authorization(self): + if "parental_authorization" in self.files: + file = self.files["parental_authorization"] + if file.size > 2e6: + raise ValidationError(_("The uploaded file size must be under 2 Mo.")) + if file.content_type not in ["application/pdf", "image/png", "image/jpeg"]: + raise ValidationError(_("The uploaded file must be a PDF, PNG of JPEG file.")) + return self.cleaned_data["parental_authorization"] + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["parental_authorization"].widget = FileInput() + + class Meta: + model = StudentRegistration + fields = ('parental_authorization',) + + +class CoachRegistrationForm(forms.ModelForm): + """ + A coach can tell its professional activity. + """ + class Meta: + model = CoachRegistration + fields = ('team', 'birth_date', 'address', 'phone_number', 'professional_activity', + 'give_contact_to_animath', 'email_confirmed',) + + +class VolunteerRegistrationForm(forms.ModelForm): + """ + A volunteer can also tell its professional activity. + """ + class Meta: + model = VolunteerRegistration + fields = ('professional_activity', 'give_contact_to_animath', 'email_confirmed',) + + +class AdminRegistrationForm(forms.ModelForm): + """ + Admins can tell everything they want. + """ + class Meta: + model = AdminRegistration + fields = ('role', 'give_contact_to_animath', 'email_confirmed',) + + +class PaymentForm(forms.ModelForm): + """ + Indicate payment information + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["valid"].widget.choices[0] = ('unknown', _("Pending")) + + def clean_scholarship_file(self): + if "scholarship_file" in self.files: + file = self.files["scholarship_file"] + if file.size > 2e6: + raise ValidationError(_("The uploaded file size must be under 2 Mo.")) + if file.content_type not in ["application/pdf", "image/png", "image/jpeg"]: + raise ValidationError(_("The uploaded file must be a PDF, PNG of JPEG file.")) + return self.cleaned_data["scholarship_file"] + + def clean(self): + cleaned_data = super().clean() + + if "type" in cleaned_data and cleaned_data["type"] == "scholarship" \ + and "scholarship" not in cleaned_data and not self.instance.scholarship_file: + self.add_error("scholarship_file", _("You must upload your scholarship attestation.")) + + return cleaned_data + + class Meta: + model = Payment + fields = ('type', 'scholarship_file', 'additional_information', 'valid',) diff --git a/apps/registration/migrations/0001_initial.py b/apps/registration/migrations/0001_initial.py new file mode 100644 index 0000000..d0fd2db --- /dev/null +++ b/apps/registration/migrations/0001_initial.py @@ -0,0 +1,123 @@ +# Generated by Django 3.0.11 on 2021-01-21 21:06 + +import address.models +import datetime +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import phonenumber_field.modelfields +import registration.models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('address', '0003_auto_20200830_1851'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('contenttypes', '0002_remove_content_type_name'), + ('participation', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Registration', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('give_contact_to_animath', models.BooleanField(default=False, verbose_name='Grant Animath to contact me in the future about other actions')), + ('email_confirmed', models.BooleanField(default=False, verbose_name='email confirmed')), + ('polymorphic_ctype', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='polymorphic_registration.registration_set+', to='contenttypes.ContentType')), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user')), + ], + options={ + 'verbose_name': 'registration', + 'verbose_name_plural': 'registrations', + }, + ), + migrations.CreateModel( + name='ParticipantRegistration', + fields=[ + ('registration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.Registration')), + ('birth_date', models.DateField(default=datetime.date.today, verbose_name='birth date')), + ('phone_number', phonenumber_field.modelfields.PhoneNumberField(blank=True, max_length=128, region=None, verbose_name='phone number')), + ('photo_authorization', models.FileField(blank=True, default='', upload_to=registration.models.get_random_photo_filename, verbose_name='photo authorization')), + ('address', address.models.AddressField(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='address.Address', verbose_name='address')), + ('team', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='participants', to='participation.Team', verbose_name='team')), + ], + options={ + 'abstract': False, + 'base_manager_name': 'objects', + }, + bases=('registration.registration',), + ), + migrations.CreateModel( + name='VolunteerRegistration', + fields=[ + ('registration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.Registration')), + ('professional_activity', models.TextField(verbose_name='professional activity')), + ], + options={ + 'abstract': False, + 'base_manager_name': 'objects', + }, + bases=('registration.registration',), + ), + migrations.CreateModel( + name='AdminRegistration', + fields=[ + ('volunteerregistration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.VolunteerRegistration')), + ('role', models.TextField(verbose_name='role of the administrator')), + ], + options={ + 'verbose_name': 'admin registration', + 'verbose_name_plural': 'admin registrations', + }, + bases=('registration.volunteerregistration',), + ), + migrations.CreateModel( + name='CoachRegistration', + fields=[ + ('participantregistration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.ParticipantRegistration')), + ('professional_activity', models.TextField(verbose_name='professional activity')), + ], + options={ + 'verbose_name': 'coach registration', + 'verbose_name_plural': 'coach registrations', + }, + bases=('registration.participantregistration',), + ), + migrations.CreateModel( + name='StudentRegistration', + fields=[ + ('participantregistration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.ParticipantRegistration')), + ('student_class', models.IntegerField(choices=[(12, '12th grade'), (11, '11th grade'), (10, '10th grade or lower')], verbose_name='student class')), + ('school', models.CharField(max_length=255, verbose_name='school')), + ('responsible_name', models.CharField(default='', max_length=255, verbose_name='responsible name')), + ('responsible_phone', phonenumber_field.modelfields.PhoneNumberField(blank=True, max_length=128, region=None, verbose_name='responsible phone number')), + ('responsible_email', models.EmailField(default='', max_length=254, verbose_name='responsible email address')), + ('parental_authorization', models.FileField(blank=True, default='', upload_to=registration.models.get_random_parental_filename, verbose_name='parental authorization')), + ('health_sheet', models.FileField(blank=True, default='', upload_to=registration.models.get_random_health_filename, verbose_name='health sheet')), + ], + options={ + 'verbose_name': 'student registration', + 'verbose_name_plural': 'student registrations', + }, + bases=('registration.participantregistration',), + ), + migrations.CreateModel( + name='Payment', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('type', models.CharField(blank=True, choices=[('', 'No payment'), ('helloasso', 'Hello Asso'), ('scholarship', 'Scholarship'), ('bank_transfer', 'Bank transfer'), ('free', 'The tournament is free')], default='', max_length=16, verbose_name='type')), + ('scholarship_file', models.FileField(blank=True, default='', help_text='only if you have a scholarship.', upload_to=registration.models.get_scholarship_filename, verbose_name='scholarship file')), + ('additional_information', models.TextField(blank=True, default='', help_text='To help us to find your payment.', verbose_name='additional information')), + ('valid', models.BooleanField(default=False, null=True, verbose_name='valid')), + ('registration', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='payment', to='registration.ParticipantRegistration', verbose_name='registration')), + ], + options={ + 'verbose_name': 'payment', + 'verbose_name_plural': 'payments', + }, + ), + ] diff --git a/apps/registration/migrations/__init__.py b/apps/registration/migrations/__init__.py new file mode 100644 index 0000000..dfc9706 --- /dev/null +++ b/apps/registration/migrations/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later diff --git a/apps/registration/models.py b/apps/registration/models.py new file mode 100644 index 0000000..4cf4416 --- /dev/null +++ b/apps/registration/models.py @@ -0,0 +1,348 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from datetime import date + +from address.models import AddressField +from django.contrib.sites.models import Site +from django.db import models +from django.template import loader +from django.urls import reverse_lazy +from django.utils import timezone +from django.utils.crypto import get_random_string +from django.utils.encoding import force_bytes +from django.utils.http import urlsafe_base64_encode +from django.utils.translation import gettext_lazy as _ +from phonenumber_field.modelfields import PhoneNumberField +from polymorphic.models import PolymorphicModel +from tfjm.tokens import email_validation_token + + +class Registration(PolymorphicModel): + """ + Registrations store extra content that are not asked in the User Model. + This is specific to the role of the user, see StudentRegistration, + ClassRegistration or AdminRegistration.. + """ + user = models.OneToOneField( + "auth.User", + on_delete=models.CASCADE, + verbose_name=_("user"), + ) + + give_contact_to_animath = models.BooleanField( + default=False, + verbose_name=_("Grant Animath to contact me in the future about other actions"), + ) + + email_confirmed = models.BooleanField( + default=False, + verbose_name=_("email confirmed"), + ) + + def send_email_validation_link(self): + """ + The account got created or the email got changed. + Send an email that contains a link to validate the address. + """ + subject = "[TFJM²] " + str(_("Activate your TFJM² account")) + token = email_validation_token.make_token(self.user) + uid = urlsafe_base64_encode(force_bytes(self.user.pk)) + site = Site.objects.first() + message = loader.render_to_string('registration/mails/email_validation_email.txt', + { + 'user': self.user, + 'domain': site.domain, + 'token': token, + 'uid': uid, + }) + html = loader.render_to_string('registration/mails/email_validation_email.html', + { + 'user': self.user, + 'domain': site.domain, + 'token': token, + 'uid': uid, + }) + self.user.email_user(subject, message, html_message=html) + + @property + def type(self): # pragma: no cover + raise NotImplementedError + + @property + def form_class(self): # pragma: no cover + raise NotImplementedError + + @property + def participates(self): + return isinstance(self, ParticipantRegistration) + + @property + def is_admin(self): + return isinstance(self, AdminRegistration) or self.user.is_superuser + + @property + def is_volunteer(self): + return isinstance(self, VolunteerRegistration) + + @property + def matrix_username(self): + return f"tfjm_{self.user.pk}" + + def get_absolute_url(self): + return reverse_lazy("registration:user_detail", args=(self.user_id,)) + + def __str__(self): + return f"{self.user.first_name} {self.user.last_name}" + + class Meta: + verbose_name = _("registration") + verbose_name_plural = _("registrations") + + +def get_random_photo_filename(instance, filename): + return "authorization/photo/" + get_random_string(64) + + +def get_random_health_filename(instance, filename): + return "authorization/health/" + get_random_string(64) + + +def get_random_parental_filename(instance, filename): + return "authorization/parental/" + get_random_string(64) + + +class ParticipantRegistration(Registration): + team = models.ForeignKey( + "participation.Team", + related_name="participants", + on_delete=models.PROTECT, + blank=True, + null=True, + default=None, + verbose_name=_("team"), + ) + + birth_date = models.DateField( + verbose_name=_("birth date"), + default=date.today, + ) + + address = AddressField( + verbose_name=_("address"), + null=True, + default=None, + ) + + phone_number = PhoneNumberField( + verbose_name=_("phone number"), + blank=True, + ) + + photo_authorization = models.FileField( + verbose_name=_("photo authorization"), + upload_to=get_random_photo_filename, + blank=True, + default="", + ) + + @property + def under_18(self): + return (timezone.now().date() - self.birth_date).days < 18 * 365.24 + + @property + def type(self): # pragma: no cover + raise NotImplementedError + + @property + def form_class(self): # pragma: no cover + raise NotImplementedError + + +class StudentRegistration(ParticipantRegistration): + """ + Specific registration for students. + They have a team, a student class and a school. + """ + student_class = models.IntegerField( + choices=[ + (12, _("12th grade")), + (11, _("11th grade")), + (10, _("10th grade or lower")), + ], + verbose_name=_("student class"), + ) + + school = models.CharField( + max_length=255, + verbose_name=_("school"), + ) + + responsible_name = models.CharField( + max_length=255, + verbose_name=_("responsible name"), + default="", + ) + + responsible_phone = PhoneNumberField( + verbose_name=_("responsible phone number"), + blank=True, + ) + + responsible_email = models.EmailField( + verbose_name=_("responsible email address"), + default="", + ) + + parental_authorization = models.FileField( + verbose_name=_("parental authorization"), + upload_to=get_random_parental_filename, + blank=True, + default="", + ) + + health_sheet = models.FileField( + verbose_name=_("health sheet"), + upload_to=get_random_health_filename, + blank=True, + default="", + ) + + @property + def type(self): + return _("student") + + @property + def form_class(self): + from registration.forms import StudentRegistrationForm + return StudentRegistrationForm + + class Meta: + verbose_name = _("student registration") + verbose_name_plural = _("student registrations") + + +class CoachRegistration(ParticipantRegistration): + """ + Specific registration for coaches. + They have a team and a professional activity. + """ + professional_activity = models.TextField( + verbose_name=_("professional activity"), + ) + + @property + def type(self): + return _("coach") + + @property + def form_class(self): + from registration.forms import CoachRegistrationForm + return CoachRegistrationForm + + class Meta: + verbose_name = _("coach registration") + verbose_name_plural = _("coach registrations") + + +class VolunteerRegistration(Registration): + """ + Specific registration for organizers and juries. + """ + professional_activity = models.TextField( + verbose_name=_("professional activity"), + ) + + @property + def interesting_tournaments(self) -> set: + return set(self.organized_tournaments.all()).union(map(lambda pool: pool.tournament, self.jury_in.all())) + + @property + def type(self): + return _('volunteer') + + @property + def form_class(self): + from registration.forms import VolunteerRegistrationForm + return VolunteerRegistrationForm + + +class AdminRegistration(VolunteerRegistration): + """ + Specific registration for admins. + They have a field to justify they status. + """ + role = models.TextField( + verbose_name=_("role of the administrator"), + ) + + @property + def type(self): + return _("admin") + + @property + def form_class(self): + from registration.forms import AdminRegistrationForm + return AdminRegistrationForm + + class Meta: + verbose_name = _("admin registration") + verbose_name_plural = _("admin registrations") + + +def get_scholarship_filename(instance, filename): + return f"authorization/scholarship/scholarship_{instance.registration.pk}" + + +class Payment(models.Model): + registration = models.OneToOneField( + ParticipantRegistration, + on_delete=models.CASCADE, + related_name="payment", + verbose_name=_("registration"), + ) + + type = models.CharField( + verbose_name=_("type"), + max_length=16, + choices=[ + ('', _("No payment")), + ('helloasso', "Hello Asso"), + ('scholarship', _("Scholarship")), + ('bank_transfer', _("Bank transfer")), + ('free', _("The tournament is free")), + ], + blank=True, + default="", + ) + + scholarship_file = models.FileField( + verbose_name=_("scholarship file"), + help_text=_("only if you have a scholarship."), + upload_to=get_scholarship_filename, + blank=True, + default="", + ) + + additional_information = models.TextField( + verbose_name=_("additional information"), + help_text=_("To help us to find your payment."), + blank=True, + default="", + ) + + valid = models.BooleanField( + verbose_name=_("valid"), + null=True, + default=False, + ) + + def get_absolute_url(self): + return reverse_lazy("registration:user_detail", args=(self.registration.user.id,)) + + def __str__(self): + return _("Payment of {registration}").format(registration=self.registration) + + class Meta: + verbose_name = _("payment") + verbose_name_plural = _("payments") diff --git a/apps/registration/search_indexes.py b/apps/registration/search_indexes.py new file mode 100644 index 0000000..3457298 --- /dev/null +++ b/apps/registration/search_indexes.py @@ -0,0 +1,16 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from haystack import indexes + +from .models import Registration + + +class RegistrationIndex(indexes.ModelSearchIndex, indexes.Indexable): + """ + Registrations are indexed by the user detail. + """ + text = indexes.NgramField(document=True, use_template=True) + + class Meta: + model = Registration diff --git a/apps/registration/signals.py b/apps/registration/signals.py new file mode 100644 index 0000000..b8f6a12 --- /dev/null +++ b/apps/registration/signals.py @@ -0,0 +1,56 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.contrib.auth.models import User +from tfjm.lists import get_sympa_client + +from .models import AdminRegistration, Payment, Registration + + +def set_username(instance, **_): + """ + Ensure that the user username is always equal to the user email address. + """ + instance.username = instance.email + + +def send_email_link(instance, **_): + """ + If the email address got changed, send a new validation link + and update the registration status in the team mailing list. + """ + if instance.pk: + old_instance = User.objects.get(pk=instance.pk) + if old_instance.email != instance.email: + registration = Registration.objects.get(user=instance) + registration.email_confirmed = False + registration.save() + registration.user = instance + registration.send_email_validation_link() + + if registration.participates and registration.team: + get_sympa_client().unsubscribe(old_instance.email, f"equipe-{registration.team.trigram.lower()}", False) + get_sympa_client().subscribe(instance.email, f"equipe-{registration.team.trigram.lower()}", False, + f"{instance.first_name} {instance.last_name}") + + +def create_admin_registration(instance, **_): + """ + When a super user got created through console, + ensure that an admin registration is created. + """ + if instance.is_superuser: + AdminRegistration.objects.get_or_create(user=instance) + + +def create_payment(instance: Registration, **_): + """ + When a user is saved, create the associated payment. + For a free tournament, the payment is valid. + """ + if instance.participates: + payment = Payment.objects.get_or_create(registration=instance)[0] + if instance.team and instance.team.participation.valid and instance.team.participation.tournament.price == 0: + payment.valid = True + payment.type = "free" + payment.save() diff --git a/apps/registration/tables.py b/apps/registration/tables.py new file mode 100644 index 0000000..31e39c0 --- /dev/null +++ b/apps/registration/tables.py @@ -0,0 +1,32 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.utils.translation import gettext_lazy as _ +import django_tables2 as tables + +from .models import Registration + + +class RegistrationTable(tables.Table): + """ + Table of all registrations. + """ + last_name = tables.LinkColumn( + 'registration:user_detail', + args=[tables.A("user_id")], + verbose_name=lambda: _("last name").capitalize(), + accessor="user__last_name", + ) + + def order_type(self, queryset, desc): + types = ["volunteerregistration__adminregistration", "volunteerregistration", "participantregistration"] + return queryset.order_by(*(("-" if desc else "") + t for t in types)), True + + class Meta: + attrs = { + 'class': 'table table-condensed table-striped', + } + model = Registration + fields = ('last_name', 'user__first_name', 'user__email', 'type',) + order_by = ('type', 'last_name', 'first_name',) + template_name = 'django_tables2/bootstrap4.html' diff --git a/apps/registration/templates/registration/add_organizer.html b/apps/registration/templates/registration/add_organizer.html new file mode 100644 index 0000000..aee2ffd --- /dev/null +++ b/apps/registration/templates/registration/add_organizer.html @@ -0,0 +1,43 @@ + +{% extends 'base.html' %} +{% load crispy_forms_filters %} +{% load i18n %} +{% block title %}{% trans "Add organizer" %}{% endblock %} + +{% block extracss %} + {{ volunteer_registration_form.media }} +{% endblock %} + +{% block content %} +

{% trans "Add organizer" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+ +
+ {{ volunteer_registration_form|crispy }} +
+
+ {{ admin_registration_form|crispy }} +
+{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/registration/templates/registration/email_validation_complete.html b/apps/registration/templates/registration/email_validation_complete.html new file mode 100644 index 0000000..4039e0b --- /dev/null +++ b/apps/registration/templates/registration/email_validation_complete.html @@ -0,0 +1,31 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n %} + +{% block content %} +
+

+ {{ title }} +

+
+ {% if validlink %} +

+ {% trans "Your email have successfully been validated." %} +

+

+ {% blocktrans %}You can now log in.{% endblocktrans %} +

+ {% else %} +

+ {% if user.is_authenticated and user.registration.email_confirmed %} + {% trans "The link was invalid. The token may have expired, or your account is already activated. However, your account seems to be already valid." %} + {% else %} + {% trans "The link was invalid. The token may have expired, or your account is already activated. Please send us an email to activate your account." %} + {% endif %} +

+ {% endif %} +
+
+{% endblock %} diff --git a/apps/registration/templates/registration/email_validation_email_sent.html b/apps/registration/templates/registration/email_validation_email_sent.html new file mode 100644 index 0000000..adc0c02 --- /dev/null +++ b/apps/registration/templates/registration/email_validation_email_sent.html @@ -0,0 +1,18 @@ +{% extends "base.html" %} +{% comment %} +SPDX-License-Identifier: GPL-3.0-or-later +{% endcomment %} +{% load i18n %} + +{% block content %} +
+

+ {% trans "Account activation" %} +

+
+

+ {% trans "An email has been sent. Please click on the link to activate your account." %} +

+
+
+{% endblock %} diff --git a/apps/registration/templates/registration/mails/add_organizer.html b/apps/registration/templates/registration/mails/add_organizer.html new file mode 100644 index 0000000..37b1645 --- /dev/null +++ b/apps/registration/templates/registration/mails/add_organizer.html @@ -0,0 +1,38 @@ +{% load i18n %} + + + + + + + + + +

+ Bonjour {{ user.registration }}, +

+ +

+ Vous avez été invités par {{ inviter }} à rejoindre la plateforme du TFJM², accessible à l'adresse + https://{{ domain }}/. Vous disposez d'un compte d'organisateur. +

+ +

+ Un mot de passe aléatoire a été défini : {{ password }}. + Par sécurité, merci de le changer dès votre connexion. +

+ +

+ En cas de problème, merci de nous contacter soit par mail à l'adresse + contact@tfjm.org, soit sur la plateforme de chat accessible sur + https://element.tfjm.org/ en vous connectant avec les mêmes identifiants. +

+ +

+ Bien cordialement, +

+ +-- +

+ {% trans "The TFJM² team." %}
+

diff --git a/apps/registration/templates/registration/mails/add_organizer.txt b/apps/registration/templates/registration/mails/add_organizer.txt new file mode 100644 index 0000000..a8ba63e --- /dev/null +++ b/apps/registration/templates/registration/mails/add_organizer.txt @@ -0,0 +1,17 @@ +{% load i18n %} + +Bonjour {{ user.registration }}, + +Vous avez été invités par {{ inviter }} à rejoindre la plateforme du TFJM², accessible à l'adresse +https://{{ domain }}/. Vous disposez d'un compte d'organisateur. + +Un mot de passe aléatoire a été défini : {{ password }}. +Par sécurité, merci de le changer dès votre connexion. + +En cas de problème, merci de nous contacter soit par mail à l'adresse contact@tfjm.org, soit sur la plateforme +de chat accessible sur https://element.tfjm.org/ en vous connectant avec les mêmes identifiants. + +Bien cordialement, + +-- +{% trans "The TFJM² team." %} diff --git a/apps/registration/templates/registration/mails/email_validation_email.html b/apps/registration/templates/registration/mails/email_validation_email.html new file mode 100644 index 0000000..34ce507 --- /dev/null +++ b/apps/registration/templates/registration/mails/email_validation_email.html @@ -0,0 +1,36 @@ +{% load i18n %} + + + + + + + + + +

+ {% trans "Hi" %} {{ user.registration }}, +

+ +

+ {% trans "You recently registered on the TFJM² platform. Please click on the link below to confirm your registration." %} +

+ +

+ + https://{{ domain }}{% url 'registration:email_validation' uidb64=uid token=token %} + +

+ +

+ {% trans "This link is only valid for a couple of days, after that you will need to contact us to validate your email." %} +

+ +

+ {% trans "Thanks" %}, +

+ +-- +

+ {% trans "The TFJM² team." %}
+

diff --git a/apps/registration/templates/registration/mails/email_validation_email.txt b/apps/registration/templates/registration/mails/email_validation_email.txt new file mode 100644 index 0000000..f70e1bb --- /dev/null +++ b/apps/registration/templates/registration/mails/email_validation_email.txt @@ -0,0 +1,13 @@ +{% load i18n %} + +{% trans "Hi" %} {{ user.registration }}, + +{% trans "You recently registered on the TFJM² platform. Please click on the link below to confirm your registration." %} + +https://{{ domain }}{% url 'registration:email_validation' uidb64=uid token=token %} + +{% trans "This link is only valid for a couple of days, after that you will need to contact us to validate your email." %} + +{% trans "Thanks" %}, + +{% trans "The TFJM² team." %} diff --git a/templates/registration/password_change_done.html b/apps/registration/templates/registration/password_change_done.html similarity index 100% rename from templates/registration/password_change_done.html rename to apps/registration/templates/registration/password_change_done.html diff --git a/templates/registration/password_change_form.html b/apps/registration/templates/registration/password_change_form.html similarity index 100% rename from templates/registration/password_change_form.html rename to apps/registration/templates/registration/password_change_form.html diff --git a/templates/registration/password_reset_complete.html b/apps/registration/templates/registration/password_reset_complete.html similarity index 74% rename from templates/registration/password_reset_complete.html rename to apps/registration/templates/registration/password_reset_complete.html index bb91a3c..dec34f6 100644 --- a/templates/registration/password_reset_complete.html +++ b/apps/registration/templates/registration/password_reset_complete.html @@ -5,7 +5,7 @@ SPDX-License-Identifier: GPL-3.0-or-later {% load i18n %} {% block content %} -

{% trans "Your password has been set. You may go ahead and log in now." %}

+

{% trans "Your password has been set. You may go ahead and log in now." %}

{% trans 'Log in' %}

diff --git a/templates/registration/password_reset_confirm.html b/apps/registration/templates/registration/password_reset_confirm.html similarity index 87% rename from templates/registration/password_reset_confirm.html rename to apps/registration/templates/registration/password_reset_confirm.html index 5db0e81..6432872 100644 --- a/templates/registration/password_reset_confirm.html +++ b/apps/registration/templates/registration/password_reset_confirm.html @@ -12,6 +12,6 @@ SPDX-License-Identifier: GPL-3.0-or-later {% else %} -

{% trans "The password reset link was invalid, possibly because it has already been used. Please request a new password reset." %}

+

{% trans "The password reset link was invalid, possibly because it has already been used. Please request a new password reset." %}

{% endif %} {% endblock %} diff --git a/templates/registration/password_reset_done.html b/apps/registration/templates/registration/password_reset_done.html similarity index 100% rename from templates/registration/password_reset_done.html rename to apps/registration/templates/registration/password_reset_done.html diff --git a/templates/registration/password_reset_form.html b/apps/registration/templates/registration/password_reset_form.html similarity index 100% rename from templates/registration/password_reset_form.html rename to apps/registration/templates/registration/password_reset_form.html diff --git a/apps/registration/templates/registration/payment_form.html b/apps/registration/templates/registration/payment_form.html new file mode 100644 index 0000000..b84c495 --- /dev/null +++ b/apps/registration/templates/registration/payment_form.html @@ -0,0 +1,52 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block content %} +
+
+
+

+ {% blocktrans trimmed with price=payment.registration.team.participation.tournament.price %} + The price of the tournament is {{ price }} €. The participation fee is offered for coaches + and for students who have a scholarship. If so, please send us your scholarship attestation. + {% endblocktrans %} +

+ +

+ {% blocktrans trimmed %} + You can pay with a credit card through + our Hello Asso page. + To make the validation of the payment easier, please use the same e-mail + address that you use on this platform. The payment verification will be checked automatically + under 10 minutes, you don't necessary need to fill this form. + {% endblocktrans %} +

+ +

+ {% blocktrans trimmed %} + You can also send a bank transfer to the bank account of Animath. You must put in the reference of the + transfer the mention "TFJMpu" followed by the last name and the first name of the student. + {% endblocktrans %} +

+ +

+ IBAN : FR76 1027 8065 0000 0206 4290 127
+ BIC : CMCIFR2A +

+ +

+ {% blocktrans trimmed %} + If any payment mean is available to you, please contact us at contact@tfjm.org + to find a solution to your difficulties. + {% endblocktrans %} +

+
+ + {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/registration/templates/registration/signup.html b/apps/registration/templates/registration/signup.html new file mode 100644 index 0000000..f64fcc6 --- /dev/null +++ b/apps/registration/templates/registration/signup.html @@ -0,0 +1,43 @@ + +{% extends 'base.html' %} +{% load crispy_forms_filters %} +{% load i18n %} +{% block title %}{% trans "Sign up" %}{% endblock %} + +{% block extracss %} + {{ student_registration_form.media }} +{% endblock %} + +{% block content %} +

{% trans "Sign up" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+ +
+ {{ student_registration_form|crispy }} +
+
+ {{ coach_registration_form|crispy }} +
+{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/registration/templates/registration/tex/Autorisation_droit_image_majeur.tex b/apps/registration/templates/registration/tex/Autorisation_droit_image_majeur.tex new file mode 100644 index 0000000..82956d0 --- /dev/null +++ b/apps/registration/templates/registration/tex/Autorisation_droit_image_majeur.tex @@ -0,0 +1,127 @@ +\documentclass[a4paper,french,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{lmodern} +\usepackage[french]{babel} + +\usepackage{fancyhdr} +\usepackage{graphicx} +\usepackage{amsmath} +\usepackage{amssymb} +%\usepackage{anyfontsize} +\usepackage{fancybox} +\usepackage{eso-pic,graphicx} +\usepackage{xcolor} + + +% Specials +\newcommand{\writingsep}{\vrule height 4ex width 0pt} + +% Page formating +\hoffset -1in +\voffset -1in +\textwidth 180 mm +\textheight 250 mm +\oddsidemargin 15mm +\evensidemargin 15mm +\pagestyle{fancy} + +% Headers and footers +\fancyfoot{} +\lhead{} +\rhead{} +\renewcommand{\headrulewidth}{0pt} +\lfoot{\footnotesize 11 rue Pierre et Marie Curie, 75231 Paris Cedex 05\\ Numéro siret 431 598 366 00018} +\rfoot{\footnotesize Association agréée par\\le Ministère de l'éducation nationale.} + +\begin{document} + +\includegraphics[height=2cm]{/code/static/logo_animath.png}\hfill{\fontsize{55pt}{55pt}{$\mathbb{TFJM}^2$}} + +\vfill + +\begin{center} + + +\LARGE +Autorisation d'enregistrement et de diffusion de l'image ({{ tournament.name }}) +\end{center} +\normalsize + + +\thispagestyle{empty} + +\bigskip + + + +Je soussign\'e {{ registration|safe|default:"\dotfill" }}\\ +demeurant au {{ registration.address|safe|default:"\dotfill" }} + +\medskip +Cochez la/les cases correspondantes.\\ +\medskip + +\fbox{\textcolor{white}{A}} Autorise l'association Animath, \`a l'occasion du $\mathbb{TFJM}^2$ de {{ tournament.name }} +du {{ tournament.date_start }} au {{ tournament.date_end }} à : {{ tournament.place }}, \`a me photographier ou \`a me +filmer et \`a diffuser les photos et/ou les vid\'eos r\'ealis\'ees \`a cette occasion sur son site et sur les sites +partenaires. D\'eclare c\'eder \`a titre gracieux \`a Animath le droit d’utiliser mon image sur tous ses supports +d'information : brochures, sites web, r\'eseaux sociaux. Animath devient, par la pr\'esente, cessionnaire des droits +pendant toute la dur\'ee pour laquelle ont \'et\'e acquis les droits d'auteur de ces photographies.\\ + +\medskip +Animath s'engage, conform\'ement aux dispositions l\'egales en vigueur relatives au droit \`a l'image, \`a ce que la +publication et la diffusion de l'image ainsi que des commentaires l'accompagnant ne portent pas atteinte \`a la vie +priv\'ee, \`a la dignit\'e et \`a la r\'eputation de la personne photographiée.\\ + +\medskip + \fbox{\textcolor{white}{A}} Autorise la diffusion dans les medias (Presse, T\'el\'evision, Internet) de photographies + prises \`a l'occasion d’une \'eventuelle m\'ediatisation de cet événement.\\ + + \medskip + +Conform\'ement \`a la loi informatique et libert\'es du 6 janvier 1978, vous disposez d'un droit de libre acc\`es, +de rectification, de modification et de suppression des donn\'ees qui vous concernent. +Cette autorisation est donc r\'evocable \`a tout moment sur volont\'e express\'ement manifest\'ee par lettre +recommand\'ee avec accus\'e de r\'eception adress\'ee \`a +Animath, IHP, 11 rue Pierre et Marie Curie, 75231 Paris cedex 05.\\ + +\medskip + \fbox{\textcolor{white}{A}} Autorise Animath à conserver mes données personnelles, dans le cadre défini par + la loi n 78-17 du 6 janvier 1978 relative à l'informatique, aux fichiers et aux libertés et les textes la modifiant, + pendant une durée de quatre ans à compter de ma dernière participation à un événement organisé par Animath.\\ + + \medskip + \fbox{\textcolor{white}{A}} J'accepte d'être tenu informé d'autres activités organisées par l'association et ses + partenaires. + +\bigskip + +Signature pr\'ec\'ed\'ee de la mention \og lu et approuv\'e \fg{} + +\medskip + + + +\begin{minipage}[c]{0.5\textwidth} + +\underline{Le participant :}\\ + +Fait \`a :\\ +le +\end{minipage} + + +\vfill +\vfill +\begin{minipage}[c]{0.5\textwidth} +\footnotesize 11 rue Pierre et Marie Curie, 75231 Paris Cedex 05\\ Numéro siret 431 598 366 00018 +\end{minipage} +\begin{minipage}[c]{0.5\textwidth} +\footnotesize +\begin{flushright} +Association agréée par\\le Ministère de l'éducation nationale. +\end{flushright} +\end{minipage} +\end{document} diff --git a/assets/Autorisation_droit_image_mineur.tex b/apps/registration/templates/registration/tex/Autorisation_droit_image_mineur.tex similarity index 52% rename from assets/Autorisation_droit_image_mineur.tex rename to apps/registration/templates/registration/tex/Autorisation_droit_image_mineur.tex index 4f14a43..52c06eb 100644 --- a/assets/Autorisation_droit_image_mineur.tex +++ b/apps/registration/templates/registration/tex/Autorisation_droit_image_mineur.tex @@ -3,7 +3,7 @@ \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \usepackage{lmodern} -\usepackage[frenchb]{babel} +\usepackage[french]{babel} \usepackage{fancyhdr} \usepackage{graphicx} @@ -37,7 +37,7 @@ \begin{document} -\includegraphics[height=2cm]{assets/logo_animath.png}\hfill{\fontsize{55pt}{55pt}{$\mathbb{TFJM}^2$}} +\includegraphics[height=2cm]{/code/static/logo_animath.png}\hfill{\fontsize{55pt}{55pt}{$\mathbb{TFJM}^2$}} \vfill @@ -46,7 +46,7 @@ \LARGE Autorisation d'enregistrement et de diffusion de l'image -({TOURNAMENT_NAME}) +({{ tournament.name }}) \end{center} \normalsize @@ -58,31 +58,45 @@ Autorisation d'enregistrement et de diffusion de l'image Je soussign\'e \dotfill (p\`ere, m\`ere, responsable l\'egal) \\ -agissant en qualit\'e de repr\'esentant de {PARTICIPANT_NAME}\\ -demeurant au {ADDRESS} +agissant en qualit\'e de repr\'esentant de {{ registration|safe|default:"\dotfill" }}\\ +demeurant au {{ registration.address|safe|default:"\dotfill" }} \medskip Cochez la/les cases correspondantes.\\ \medskip - \fbox{\textcolor{white}{A}} Autorise l'association Animath, \`a l'occasion du $\mathbb{TFJM}^2$ du {START_DATE} au {END_DATE} {YEAR} à : {PLACE}, \`a photographier ou \`a filmer l'enfant et \`a diffuser les photos et/ou les vid\'eos r\'ealis\'ees \`a cette occasion sur son site et sur les sites partenaires. D\'eclare c\'eder \`a titre gracieux \`a Animath le droit d’utiliser l'image de l'enfant sur tous ses supports d'information : brochures, sites web, r\'eseaux sociaux. Animath devient, par la pr\'esente, cessionnaire des droits pendant toute la dur\'ee pour laquelle ont \'et\'e acquis les droits d'auteur de ces photographies.\\ + \fbox{\textcolor{white}{A}} Autorise l'association Animath, \`a l'occasion du $\mathbb{TFJM}^2$ de {{ tournament.name }} + du {{ tournament.date_start }} au {{ tournament.date_end }} à : {{ tournament.place }}, \`a photographier ou \`a filmer + l'enfant et \`a diffuser les photos et/ou les vid\'eos r\'ealis\'ees \`a cette occasion sur son site et sur les sites + partenaires. D\'eclare c\'eder \`a titre gracieux \`a Animath le droit d’utiliser l'image de l'enfant sur tous ses + supports d'information : brochures, sites web, r\'eseaux sociaux. Animath devient, par la pr\'esente, cessionnaire des + droits pendant toute la dur\'ee pour laquelle ont \'et\'e acquis les droits d'auteur de ces photographies.\\ \medskip -Animath s'engage, conform\'ement aux dispositions l\'egales en vigueur relatives au droit \`a l'image, \`a ce que la publication et la diffusion de l'image de l'enfant ainsi que des commentaires l'accompagnant ne portent pas atteinte \`a la vie priv\'ee, \`a la dignit\'e et \`a la r\'eputation de l’enfant.\\ +Animath s'engage, conform\'ement aux dispositions l\'egales en vigueur relatives au droit \`a l'image, \`a ce que la +publication et la diffusion de l'image de l'enfant ainsi que des commentaires l'accompagnant ne portent pas atteinte +\`a la vie priv\'ee, \`a la dignit\'e et \`a la r\'eputation de l’enfant.\\ \medskip - \fbox{\textcolor{white}{A}} Autorise la diffusion dans les medias (Presse, T\'el\'evision, Internet) de photographies de mon enfant prises \`a l'occasion d’une \'eventuelle m\'ediatisation de cet événement.\\ + \fbox{\textcolor{white}{A}} Autorise la diffusion dans les medias (Presse, T\'el\'evision, Internet) de + photographies de mon enfant prises \`a l'occasion d’une \'eventuelle m\'ediatisation de cet événement.\\ \medskip -Conform\'ement \`a la loi informatique et libert\'es du 6 janvier 1978, vous disposez d'un droit de libre acc\`es, de rectification, de modification et de suppression des donn\'ees qui vous concernent. -Cette autorisation est donc r\'evocable \`a tout moment sur volont\'e express\'ement manifest\'ee par lettre recommand\'ee avec accus\'e de r\'eception adress\'ee \`a Animath, IHP, 11 rue Pierre et Marie Curie, 75231 Paris cedex 05.\\ +Conform\'ement \`a la loi informatique et libert\'es du 6 janvier 1978, vous disposez d'un droit de libre acc\`es, de +rectification, de modification et de suppression des donn\'ees qui vous concernent. +Cette autorisation est donc r\'evocable \`a tout moment sur volont\'e express\'ement manifest\'ee par lettre +recommand\'ee avec accus\'e de r\'eception adress\'ee \`a +Animath, IHP, 11 rue Pierre et Marie Curie, 75231 Paris cedex 05.\\ \medskip - \fbox{\textcolor{white}{A}} Autorise Animath à conserver mes données personnelles, dans le cadre défini par la loi n 78-17 du 6 janvier 1978 relative à l'informatique, aux fichiers et aux libertés et les textes la modifiant, pendant une durée de quatre ans à compter de ma dernière participation à un événement organisé par Animath.\\ + \fbox{\textcolor{white}{A}} Autorise Animath à conserver mes données personnelles, dans le cadre défini par + la loi n 78-17 du 6 janvier 1978 relative à l'informatique, aux fichiers et aux libertés et les textes la modifiant, + pendant une durée de quatre ans à compter de ma dernière participation à un événement organisé par Animath.\\ \medskip - \fbox{\textcolor{white}{A}} J'accepte d'être tenu informé d'autres activités organisées par l'association et ses partenaires. + \fbox{\textcolor{white}{A}} J'accepte d'être tenu informé d'autres activités organisées par l'association et ses + partenaires. \bigskip diff --git a/static/Autorisation_parentale.tex b/apps/registration/templates/registration/tex/Autorisation_parentale.tex similarity index 64% rename from static/Autorisation_parentale.tex rename to apps/registration/templates/registration/tex/Autorisation_parentale.tex index 6c56ac4..b357694 100644 --- a/static/Autorisation_parentale.tex +++ b/apps/registration/templates/registration/tex/Autorisation_parentale.tex @@ -37,28 +37,30 @@ \begin{document} -\includegraphics[height=2cm]{assets/logo_animath.png}\hfill{\fontsize{55pt}{55pt}{$\mathbb{TFJM}^2$}} +\includegraphics[height=2cm]{/code/static/logo_animath.png}\hfill{\fontsize{55pt}{55pt}{$\mathbb{TFJM}^2$}} \vfill \begin{center} -\Large \bf Autorisation parentale pour les mineurs ({TOURNAMENT_NAME}) +\Large \bf Autorisation parentale pour les mineurs ({{ tournament.name }}) \end{center} Je soussigné(e) \hrulefill,\\ responsable légal, demeurant \writingsep\hrulefill\\ \writingsep\hrulefill,\\ -\writingsep autorise {PARTICIPANT_NAME},\\ -né(e) le {BIRTHDAY}, -à participer au Tournoi Français des Jeunes Mathématiciennes et Mathématiciens ($\mathbb{TFJM}^2$) organisé \`a : {PLACE}, du {START_DATE} au {END_DATE} {YEAR}. +\writingsep autorise {{ registration|default:"\hrulefill" }},\\ +né(e) le {{ registration.birth_date }}, +à participer au Tournoi Français des Jeunes Mathématiciennes et Mathématiciens ($\mathbb{TFJM}^2$) organisé \`a : +{{ tournament.place }}, du {{ tournament.date_start }} au {{ tournament.date_end }}. -{PRONOUN} se rendra au lieu indiqu\'e ci-dessus le vendredi matin et quittera les lieux l'après-midi du dimanche par ses propres moyens et sous la responsabilité du représentant légal. +Iel se rendra au lieu indiqu\'e ci-dessus le vendredi matin et quittera les lieux l'après-midi du dimanche par +ses propres moyens et sous la responsabilité du représentant légal. \vspace{8ex} -Fait à \vrule width 10cm height 0pt depth 0.4pt, le \phantom{232323}/\phantom{XXX}/{YEAR}, +Fait à \vrule width 10cm height 0pt depth 0.4pt, le \phantom{232323}/\phantom{XXX}/{% now "Y" %}, \vfill \vfill diff --git a/assets/Instructions.tex b/apps/registration/templates/registration/tex/Instructions.tex similarity index 60% rename from assets/Instructions.tex rename to apps/registration/templates/registration/tex/Instructions.tex index da293ef..e865897 100644 --- a/assets/Instructions.tex +++ b/apps/registration/templates/registration/tex/Instructions.tex @@ -38,12 +38,12 @@ \begin{document} -\includegraphics[height=2cm]{assets/logo_animath.png}\hfill{\fontsize{50pt}{50pt}{$\mathbb{TFJM}^2$}} +\includegraphics[height=2cm]{/code/static/logo_animath.png}\hfill{\fontsize{50pt}{50pt}{$\mathbb{TFJM}^2$}} \begin{center} -\Large \bf Instructions ({TOURNAMENT_NAME}) +\Large \bf Instructions ({{ tournament.name }}) \end{center} \section{Documents} @@ -51,7 +51,8 @@ Elle est nécessaire si l'élève est mineur au moment du tournoi (y compris si son anniversaire est pendant le tournoi). \subsection{Autorisation de prise de vue} -Si l'élève est mineur \textbf{au moment de la signature}, il convient de remplir l'autorisation pour les mineurs. En revanche, s'il est majeur \textbf{au moment de la signature}, il convient de remplir la fiche pour majeur. +Si l'élève est mineur \textbf{au moment de la signature}, il convient de remplir l'autorisation pour les mineurs. +En revanche, s'il est majeur \textbf{au moment de la signature}, il convient de remplir la fiche pour majeur. \subsection{Fiche sanitaire} Elle est nécessaire si l'élève est mineur au moment du tournoi (y compris si son anniversaire est pendant le tournoi). @@ -59,20 +60,27 @@ Elle est nécessaire si l'élève est mineur au moment du tournoi (y compris si \section{Paiement} +{% if tournament.price %} \subsection{Montant} -Les frais d'inscription sont fixés à {PRICE} euros. Vous devez vous en acquitter \textbf{avant le {END_PAYMENT_DATE} {YEAR}}. Si l'élève est boursier, il en est dispensé, vous devez alors fournir une copie de sa notification de bourse directement sur la plateforme \textbf{avant le {END_PAYMENT_DATE} {YEAR}}. +Les frais d'inscription sont fixés à {{ tournament.price }} euros. Vous devez vous en acquitter +\textbf{avant le {{ tournament.inscription_limit.date }}}. Si l'élève est boursier, il en est dispensé, vous devez alors +fournir une copie de sa notification de bourse directement sur la plateforme +\textbf{avant le {{ tournament.inscription_limit.date }}}. \subsection{Procédure} -Si le paiement de plusieurs élèves est fait en une seule opération, merci de contacter \href{mailto: contact@tfjm.org}{contact@tfjm.org} \textbf{avant le paiement} pour garantir l'identification de ce dernier +Si le paiement de plusieurs élèves est fait en une seule opération, merci de contacter +\href{mailto: contact@tfjm.org}{contact@tfjm.org} \textbf{avant le paiement} pour garantir l'identification de ce dernier. \subsubsection*{Carte bancaire (uniquement les cartes françaises)} -Le paiement s'effectue en ligne via la plateforme à l'adresse : \url{https://www.helloasso.com/associations/animath/evenements/tfjm-2020} +Le paiement s'effectue en ligne via la plateforme à l'adresse : \url{https://www.helloasso.com/associations/animath/evenements/tfjmm-2021} Vous devez impérativement indiquer dans le champ "Référence" la mention "TFJMpu" suivie des noms et prénoms \textbf{de l'élève}. \subsubsection*{Virement} -\textbf{Si vous ne pouvez pas utiliser le paiement par carte}, vous pouvez faire un virement sur le compte ci-dessous en indiquant bien dans le champ "motif" (ou autre champ propre à votre banque dont le contenu est communiqué au destinataire) la mention "TFJMpu" suivie des noms et prénoms \textbf{de l'élève}. +\textbf{Si vous ne pouvez pas utiliser le paiement par carte}, vous pouvez faire un virement sur le compte ci-dessous en +indiquant bien dans le champ "motif" (ou autre champ propre à votre banque dont le contenu est communiqué au destinataire) +la mention "TFJMpu" suivie des noms et prénoms \textbf{de l'élève}. IBAN FR76 1027 8065 0000 0206 4290 127 @@ -80,7 +88,12 @@ BIC CMCIFR2A \subsubsection*{Autre} -Si aucune de ces procédures n'est possible pour vous, envoyez un mail à \href{mailto: contact@tfjm.org}{contact@tfjm.org} pour que nous trouvions une solution à vos difficultés. +Si aucune de ces procédures n'est possible pour vous, envoyez un mail à \href{mailto: contact@tfjm.org}{contact@tfjm.org} +pour que nous trouvions une solution à vos difficultés. + +{% else %} +Le tournoi est gratuit, vous n'avez aucun frais à avoir. +{% endif %} diff --git a/apps/registration/templates/registration/update_user.html b/apps/registration/templates/registration/update_user.html new file mode 100644 index 0000000..05533b8 --- /dev/null +++ b/apps/registration/templates/registration/update_user.html @@ -0,0 +1,19 @@ +{% extends "base.html" %} + +{% load crispy_forms_filters i18n %} + +{% block extracss %} + {{ registration_form.media }} +{% endblock %} + +{% block content %} +
+
+ {% csrf_token %} + {{ form|crispy }} + {{ registration_form|crispy }} +
+ +
+{% endblock content %} + diff --git a/apps/registration/templates/registration/upload_health_sheet.html b/apps/registration/templates/registration/upload_health_sheet.html new file mode 100644 index 0000000..0c4415b --- /dev/null +++ b/apps/registration/templates/registration/upload_health_sheet.html @@ -0,0 +1,19 @@ +{% extends "base.html" %} + +{% load i18n static crispy_forms_filters %} + +{% block content %} + {% trans "Back to the user detail" %} +
+
+
+
+ {% trans "Health sheet template:" %} + {% trans "Download" %} +
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock %} diff --git a/apps/registration/templates/registration/upload_parental_authorization.html b/apps/registration/templates/registration/upload_parental_authorization.html new file mode 100644 index 0000000..a758830 --- /dev/null +++ b/apps/registration/templates/registration/upload_parental_authorization.html @@ -0,0 +1,19 @@ +{% extends "base.html" %} + +{% load i18n static crispy_forms_filters %} + +{% block content %} + {% trans "Back to the user detail" %} +
+
+
+
+ {% trans "Authorization template:" %} + {% trans "Download" %} +
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock %} diff --git a/apps/registration/templates/registration/upload_photo_authorization.html b/apps/registration/templates/registration/upload_photo_authorization.html new file mode 100644 index 0000000..fb2823b --- /dev/null +++ b/apps/registration/templates/registration/upload_photo_authorization.html @@ -0,0 +1,20 @@ +{% extends "base.html" %} + +{% load i18n static crispy_forms_filters %} + +{% block content %} + {% trans "Back to the user detail" %} +
+
+
+
+ {% trans "Authorization templates:" %} + {% trans "Adult" %} — + {% trans "Child" %} +
+ {% csrf_token %} + {{ form|crispy }} +
+ +
+{% endblock %} diff --git a/apps/registration/templates/registration/user_detail.html b/apps/registration/templates/registration/user_detail.html new file mode 100644 index 0000000..cdc6017 --- /dev/null +++ b/apps/registration/templates/registration/user_detail.html @@ -0,0 +1,224 @@ +{% extends "base.html" %} + +{% load i18n %} + +{% block content %} +{% trans "any" as any %} + +
+
+

{{ user_object.first_name }} {{ user_object.last_name }}

+
+
+
+
{% trans "Last name:" %}
+
{{ user_object.last_name }}
+ +
{% trans "First name:" %}
+
{{ user_object.first_name }}
+ +
{% trans "Email:" %}
+
{{ user_object.email }} + {% if not user_object.registration.email_confirmed %} ({% trans "Not confirmed" %}, {% trans "resend the validation link" %}){% endif %}
+ + {% if user_object == user %} +
{% trans "Password:" %}
+
+ + {% trans "Change password" %} + +
+ {% endif %} + + {% if user_object.registration.participates %} +
{% trans "Team:" %}
+ {% trans "any" as any %} +
+ + {{ user_object.registration.team|default:any }} + +
+ +
{% trans "Birth date:" %}
+
{{ user_object.registration.birth_date }}
+ +
{% trans "Address:" %}
+
{{ user_object.registration.address }}
+ +
{% trans "Phone number:" %}
+
{{ user_object.registration.phone_number }}
+ +
{% trans "Photo authorization:" %}
+
+ {% if user_object.registration.photo_authorization %} + {% trans "Download" %} + {% endif %} + {% if user_object.registration.team and not user_object.registration.team.participation.valid %} + + {% endif %} +
+ {% endif %} + + {% if user_object.registration.studentregistration %} + {% if user_object.registration.under_18 %} +
{% trans "Health sheet:" %}
+
+ {% if user_object.registration.health_sheet %} + {% trans "Download" %} + {% endif %} + {% if user_object.registration.team and not user_object.registration.team.participation.valid %} + + {% endif %} +
+ +
{% trans "Parental authorization:" %}
+
+ {% if user_object.registration.parental_authorization %} + {% trans "Download" %} + {% endif %} + {% if user_object.registration.team and not user_object.registration.team.participation.valid %} + + {% endif %} +
+ {% endif %} + +
{% trans "Student class:" %}
+
{{ user_object.registration.get_student_class_display }}
+ +
{% trans "School:" %}
+
{{ user_object.registration.school }}
+ +
{% trans "Responsible name:" %}
+
{{ user_object.registration.responsible_name }}
+ +
{% trans "Responsible phone number:" %}
+
{{ user_object.registration.responsible_phone }}
+ +
{% trans "Responsible email address:" %}
+ {% with user_object.registration.responsible_email as email %} +
{{ email }}
+ {% endwith %} + {% elif user_object.registration.is_admin %} +
{% trans "Role:" %}
+
{{ user_object.registration.role }}
+ {% elif user_object.registration.coachregistration or user_object.registration.is_volunteer %} +
{% trans "Profesional activity:" %}
+
{{ user_object.registration.professional_activity }}
+ {% endif %} + +
{% trans "Grant Animath to contact me in the future about other actions:" %}
+
{{ user_object.registration.give_contact_to_animath|yesno }}
+
+ + {% if user_object.registration.participates and user_object.registration.team.participation.valid %} +
+ +
+
{% trans "Payment information:" %}
+
+ {% trans "yes,no,pending" as yesnodefault %} + {% with info=user_object.registration.payment.additional_information %} + {% if info %} + + {{ user_object.registration.payment.get_type_display }}, {% trans "valid:" %} {{ user_object.registration.payment.valid|yesno:yesnodefault }} + + {% else %} + {{ user_object.registration.payment.get_type_display }}, {% trans "valid:" %} {{ user_object.registration.payment.valid|yesno:yesnodefault }} + {% endif %} + {% if user.registration.is_admin or user_object.registration.payment.valid is False %} + + {% endif %} + {% if user_object.registration.payment.type == "scholarship" %} + {% if user.registration.is_admin or user == user_object %} + + {% trans "Download scholarship attestation" %} + + {% endif %} + {% endif %} + {% endwith %} +
+
+ {% endif %} +
+ {% if user.pk == user_object.pk or user.registration.is_admin %} + + {% endif %} +
+ + {% trans "Update user" as modal_title %} + {% trans "Update" as modal_button %} + {% url "registration:update_user" pk=user_object.pk as modal_action %} + {% include "base_modal.html" with modal_id="updateUser" %} + + {% if user_object.registration.team and not user_object.registration.team.participation.valid %} + {% trans "Upload photo authorization" as modal_title %} + {% trans "Upload" as modal_button %} + {% url "registration:upload_user_photo_authorization" pk=user_object.registration.pk as modal_action %} + {% include "base_modal.html" with modal_id="uploadPhotoAuthorization" modal_enctype="multipart/form-data" %} + + {% trans "Upload health sheet" as modal_title %} + {% trans "Upload" as modal_button %} + {% url "registration:upload_user_health_sheet" pk=user_object.registration.pk as modal_action %} + {% include "base_modal.html" with modal_id="uploadHealthSheet" modal_enctype="multipart/form-data" %} + + {% trans "Upload parental authorization" as modal_title %} + {% trans "Upload" as modal_button %} + {% url "registration:upload_user_parental_authorization" pk=user_object.registration.pk as modal_action %} + {% include "base_modal.html" with modal_id="uploadParentalAuthorization" modal_enctype="multipart/form-data" %} + + {% trans "Upload parental authorization" as modal_title %} + {% trans "Upload" as modal_button %} + {% url "registration:upload_user_parental_authorization" pk=user_object.registration.pk as modal_action %} + {% include "base_modal.html" with modal_id="uploadParentalAuthorization" modal_enctype="multipart/form-data" %} + {% endif %} + + {% if user_object.registration.team.participation.valid %} + {% trans "Update payment" as modal_title %} + {% trans "Update" as modal_button %} + {% url "registration:update_payment" pk=user_object.registration.payment.pk as modal_action %} + {% include "base_modal.html" with modal_id="updatePayment" modal_additional_class="modal-xl" modal_enctype="multipart/form-data" %} + {% endif %} +{% endblock %} + +{% block extrajavascript %} + +{% endblock %} diff --git a/apps/registration/templates/registration/user_list.html b/apps/registration/templates/registration/user_list.html new file mode 100644 index 0000000..78f3cbe --- /dev/null +++ b/apps/registration/templates/registration/user_list.html @@ -0,0 +1,14 @@ +{% extends "base.html" %} + +{% load django_tables2 i18n %} + +{% block content %} + {% if user.registration.is_admin %} + + {% trans "Add organizer" %} + +
+ {% endif %} + + {% render_table table %} +{% endblock %} diff --git a/apps/registration/templates/search/indexes/registration/adminregistration_text.txt b/apps/registration/templates/search/indexes/registration/adminregistration_text.txt new file mode 100644 index 0000000..a5077ab --- /dev/null +++ b/apps/registration/templates/search/indexes/registration/adminregistration_text.txt @@ -0,0 +1,5 @@ +{{ object.user.last_name }} +{{ object.user.first_name }} +{{ object.user.email }} +{{ object.type }} +{{ object.role }} diff --git a/apps/registration/templates/search/indexes/registration/coachregistration_text.txt b/apps/registration/templates/search/indexes/registration/coachregistration_text.txt new file mode 100644 index 0000000..e08b187 --- /dev/null +++ b/apps/registration/templates/search/indexes/registration/coachregistration_text.txt @@ -0,0 +1,10 @@ +{{ object.user.first_name }} +{{ object.user.last_name }} +{{ object.user.email }} +{{ object.type }} +{{ object.professional_activity }} +{{ object.birth_date }} +{{ object.address }} +{{ object.phone_number }} +{{ object.team.name }} +{{ object.team.trigram }} diff --git a/apps/registration/templates/search/indexes/registration/studentregistration_text.txt b/apps/registration/templates/search/indexes/registration/studentregistration_text.txt new file mode 100644 index 0000000..9eefe38 --- /dev/null +++ b/apps/registration/templates/search/indexes/registration/studentregistration_text.txt @@ -0,0 +1,14 @@ +{{ object.user.first_name }} +{{ object.user.last_name }} +{{ object.user.email }} +{{ object.type }} +{{ object.get_student_class_display }} +{{ object.school }} +{{ object.birth_date }} +{{ object.address }} +{{ object.phone_number }} +{{ object.responsible_name }} +{{ object.reponsible_phone }} +{{ object.reponsible_email }} +{{ object.team.name }} +{{ object.team.trigram }} diff --git a/apps/registration/templates/search/indexes/registration/volunteerregistration_text.txt b/apps/registration/templates/search/indexes/registration/volunteerregistration_text.txt new file mode 100644 index 0000000..02ad2a3 --- /dev/null +++ b/apps/registration/templates/search/indexes/registration/volunteerregistration_text.txt @@ -0,0 +1,5 @@ +{{ object.user.last_name }} +{{ object.user.first_name }} +{{ object.user.email }} +{{ object.type }} +{{ object.professional_activity }} diff --git a/apps/registration/templatetags/__init__.py b/apps/registration/templatetags/__init__.py new file mode 100644 index 0000000..dfc9706 --- /dev/null +++ b/apps/registration/templatetags/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later diff --git a/apps/registration/templatetags/getconfig.py b/apps/registration/templatetags/getconfig.py new file mode 100644 index 0000000..e0ce73a --- /dev/null +++ b/apps/registration/templatetags/getconfig.py @@ -0,0 +1,14 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +import os + +from django import template + + +def get_env(key: str) -> str: + return os.getenv(key) + + +register = template.Library() +register.filter("get_env", get_env) diff --git a/apps/registration/templatetags/search_results_tables.py b/apps/registration/templatetags/search_results_tables.py new file mode 100644 index 0000000..b9b7a32 --- /dev/null +++ b/apps/registration/templatetags/search_results_tables.py @@ -0,0 +1,28 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django import template +from django_tables2 import Table +from participation.models import Participation, Team, Tournament +from participation.tables import ParticipationTable, TeamTable, TournamentTable + +from ..models import Registration +from ..tables import RegistrationTable + + +def search_table(results): + model_class = results[0].object.__class__ + table_class = Table + if issubclass(model_class, Registration): + table_class = RegistrationTable + elif issubclass(model_class, Team): + table_class = TeamTable + elif issubclass(model_class, Participation): + table_class = ParticipationTable + elif issubclass(model_class, Tournament): + table_class = TournamentTable + return table_class([result.object for result in results], prefix=model_class._meta.model_name) + + +register = template.Library() +register.filter("search_table", search_table) diff --git a/apps/registration/tests.py b/apps/registration/tests.py new file mode 100644 index 0000000..ffa7955 --- /dev/null +++ b/apps/registration/tests.py @@ -0,0 +1,406 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +import os + +from django.contrib.auth.models import User +from django.contrib.contenttypes.models import ContentType +from django.contrib.sites.models import Site +from django.core.files.uploadedfile import SimpleUploadedFile +from django.core.management import call_command +from django.test import TestCase +from django.urls import reverse +from django.utils.encoding import force_bytes +from django.utils.http import urlsafe_base64_encode +from participation.models import Team +from tfjm.tokens import email_validation_token + +from .models import AdminRegistration, CoachRegistration, StudentRegistration + + +class TestIndexPage(TestCase): + def test_index(self) -> None: + """ + Display the index page, without any right. + """ + response = self.client.get(reverse("index")) + self.assertEqual(response.status_code, 200) + + def test_not_authenticated(self): + """ + Try to load some pages without being authenticated. + """ + response = self.client.get(reverse("registration:reset_admin")) + self.assertRedirects(response, reverse("login") + "?next=" + reverse("registration:reset_admin"), 302, 200) + + User.objects.create() + response = self.client.get(reverse("registration:user_detail", args=(1,))) + self.assertRedirects(response, reverse("login") + "?next=" + reverse("registration:user_detail", args=(1,))) + + Team.objects.create() + response = self.client.get(reverse("participation:team_detail", args=(1,))) + self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:team_detail", args=(1,))) + response = self.client.get(reverse("participation:update_team", args=(1,))) + self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:update_team", args=(1,))) + response = self.client.get(reverse("participation:create_team")) + self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:create_team")) + response = self.client.get(reverse("participation:join_team")) + self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:join_team")) + response = self.client.get(reverse("participation:team_authorizations", args=(1,))) + self.assertRedirects(response, reverse("login") + "?next=" + + reverse("participation:team_authorizations", args=(1,))) + response = self.client.get(reverse("participation:participation_detail", args=(1,))) + self.assertRedirects(response, reverse("login") + "?next=" + + reverse("participation:participation_detail", args=(1,))) + + +class TestRegistration(TestCase): + def setUp(self) -> None: + self.user = User.objects.create_superuser( + username="admin", + password="admin", + email="admin@example.com", + ) + self.client.force_login(self.user) + + self.student = User.objects.create(email="student@example.com") + StudentRegistration.objects.create(user=self.student, student_class=11, school="Earth") + self.coach = User.objects.create(email="coach@example.com") + CoachRegistration.objects.create(user=self.coach, professional_activity="Teacher") + + def test_admin_pages(self): + """ + Check that admin pages are rendering successfully. + """ + response = self.client.get(reverse("admin:index") + "registration/registration/") + self.assertEqual(response.status_code, 200) + + response = self.client.get(reverse("admin:index") + + f"registration/registration/{self.user.registration.pk}/change/") + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("admin:index") + + f"r/{ContentType.objects.get_for_model(AdminRegistration).id}/" + f"{self.user.registration.pk}/") + self.assertRedirects(response, "http://" + Site.objects.get().domain + + str(self.user.registration.get_absolute_url()), 302, 200) + + response = self.client.get(reverse("admin:index") + + f"registration/registration/{self.student.registration.pk}/change/") + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("admin:index") + + f"r/{ContentType.objects.get_for_model(StudentRegistration).id}/" + f"{self.student.registration.pk}/") + self.assertRedirects(response, "http://" + Site.objects.get().domain + + str(self.student.registration.get_absolute_url()), 302, 200) + + response = self.client.get(reverse("admin:index") + + f"registration/registration/{self.coach.registration.pk}/change/") + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse("admin:index") + + f"r/{ContentType.objects.get_for_model(CoachRegistration).id}/" + f"{self.coach.registration.pk}/") + self.assertRedirects(response, "http://" + Site.objects.get().domain + + str(self.coach.registration.get_absolute_url()), 302, 200) + + def test_registration(self): + """ + Ensure that the signup form is working successfully. + """ + response = self.client.get(reverse("registration:signup")) + self.assertEqual(response.status_code, 200) + + # Incomplete form + response = self.client.post(reverse("registration:signup"), data=dict( + last_name="Toto", + first_name="Toto", + email="toto@example.com", + password1="azertyuiopazertyuiop", + password2="azertyuiopazertyuiop", + role="participant", + )) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("registration:signup"), data=dict( + last_name="Toto", + first_name="Toto", + email="toto@example.com", + password1="azertyuiopazertyuiop", + password2="azertyuiopazertyuiop", + role="participant", + student_class=12, + school="God", + birth_date="2000-01-01", + address="1 Rue de Rivoli, 75001 Paris, France", + phone_number="0123456789", + responsible_name="Toto", + responsible_phone="0123456789", + responsible_email="toto@example.com", + give_contact_to_animath=False, + )) + self.assertRedirects(response, reverse("registration:email_validation_sent"), 302, 200) + self.assertTrue(User.objects.filter( + email="toto@example.com", + registration__participantregistration__studentregistration__responsible_name="Toto").exists()) + + # Email is already used + response = self.client.post(reverse("registration:signup"), data=dict( + last_name="Toto", + first_name="Toto", + email="toto@example.com", + password1="azertyuiopazertyuiop", + password2="azertyuiopazertyuiop", + role="participant", + student_class=12, + school="God", + birth_date="2000-01-01", + address="1 Rue de Rivoli, 75001 Paris, France", + phone_number="0123456789", + responsible_name="Toto", + responsible_phone="0123456789", + responsible_email="toto@example.com", + give_contact_to_animath=False, + )) + self.assertEqual(response.status_code, 200) + + response = self.client.get(reverse("registration:email_validation_sent")) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("registration:signup"), data=dict( + last_name="Toto", + first_name="Coach", + email="coachtoto@example.com", + password1="azertyuiopazertyuiop", + password2="azertyuiopazertyuiop", + role="coach", + birth_date="1980-01-01", + address="1 Rue de Rivoli, 75001 Paris, France", + phone_number="0123456789", + professional_activity="God", + give_contact_to_animath=True, + )) + self.assertRedirects(response, reverse("registration:email_validation_sent"), 302, 200) + self.assertTrue(User.objects.filter(email="coachtoto@example.com").exists()) + + user = User.objects.get(email="coachtoto@example.com") + token = email_validation_token.make_token(user) + uid = urlsafe_base64_encode(force_bytes(user.pk)) + response = self.client.get(reverse("registration:email_validation", kwargs=dict(uidb64=uid, token=token))) + self.assertEqual(response.status_code, 200) + user.registration.refresh_from_db() + self.assertTrue(user.registration.email_confirmed) + + # Token has expired + response = self.client.get(reverse("registration:email_validation", kwargs=dict(uidb64=uid, token=token))) + self.assertEqual(response.status_code, 400) + + # Uid does not exist + response = self.client.get(reverse("registration:email_validation", kwargs=dict(uidb64=0, token="toto"))) + self.assertEqual(response.status_code, 400) + + response = self.client.get(reverse("registration:email_validation_resend", args=(user.pk,))) + self.assertRedirects(response, reverse("registration:email_validation_sent"), 302, 200) + + def test_login(self): + """ + With a registered user, try to log in + """ + response = self.client.get(reverse("login")) + self.assertEqual(response.status_code, 200) + + self.client.logout() + + response = self.client.post(reverse("login"), data=dict( + username="admin", + password="toto", + )) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("login"), data=dict( + username="admin@example.com", + password="admin", + )) + self.assertRedirects(response, reverse("index"), 302, 200) + + def test_user_detail(self): + """ + Load a user detail page. + """ + response = self.client.get(reverse("registration:my_account_detail")) + self.assertRedirects(response, reverse("registration:user_detail", args=(self.user.pk,))) + + response = self.client.get(reverse("registration:user_detail", args=(self.user.pk,))) + self.assertEqual(response.status_code, 200) + + def test_user_list(self): + """ + Display the list of all users. + """ + response = self.client.get(reverse("registration:user_list")) + self.assertEqual(response.status_code, 200) + + def test_update_user(self): + """ + Update the user information, for each type of user. + """ + # To test the modification of mailing lists + from participation.models import Team + self.student.registration.team = Team.objects.create( + name="toto", + trigram="TOT", + ) + self.student.registration.save() + + for user, data in [(self.user, dict(role="Bot")), + (self.student, dict(student_class=11, school="Sky", birth_date="2001-01-01", + address="1 Rue de Rivoli, 75001 Paris, France", responsible_name="Toto", + responsible_email="toto@example.com")), + (self.coach, dict(professional_activity="God", birth_date="2001-01-01", + address="1 Rue de Rivoli, 75001 Paris, France"))]: + response = self.client.get(reverse("registration:update_user", args=(user.pk,))) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse("registration:update_user", args=(user.pk,)), data=dict( + first_name="Changed", + last_name="Name", + email="new_" + user.email, + give_contact_to_animath=True, + email_confirmed=True, + team_id="", + )) + self.assertEqual(response.status_code, 200) + + data.update( + first_name="Changed", + last_name="Name", + email="new_" + user.email, + give_contact_to_animath=True, + email_confirmed=True, + team_id="", + ) + response = self.client.post(reverse("registration:update_user", args=(user.pk,)), data=data) + self.assertRedirects(response, reverse("registration:user_detail", args=(user.pk,)), 302, 200) + user.refresh_from_db() + self.assertEqual(user.email, user.username) + self.assertFalse(user.registration.email_confirmed) + self.assertEqual(user.first_name, "Changed") + + def test_upload_photo_authorization(self): + """ + Try to upload a photo authorization. + """ + for auth_type in ["photo_authorization", "health_sheet", "parental_authorization"]: + response = self.client.get(reverse("registration:upload_user_photo_authorization", + args=(self.student.registration.pk,))) + self.assertEqual(response.status_code, 200) + + # README is not a valid PDF file + response = self.client.post(reverse(f"registration:upload_user_{auth_type}", + args=(self.student.registration.pk,)), data={ + auth_type: open("README.md", "rb"), + }) + self.assertEqual(response.status_code, 200) + + # Don't send too large files + response = self.client.post(reverse(f"registration:upload_user_{auth_type}", + args=(self.student.registration.pk,)), data={ + auth_type: SimpleUploadedFile("file.pdf", content=int(0).to_bytes(2000001, "big"), + content_type="application/pdf"), + }) + self.assertEqual(response.status_code, 200) + + response = self.client.post(reverse(f"registration:upload_user_{auth_type}", + args=(self.student.registration.pk,)), data={ + auth_type: open("tfjm/static/Fiche_sanitaire.pdf", "rb"), + }) + self.assertRedirects(response, reverse("registration:user_detail", args=(self.student.pk,)), 302, 200) + + self.student.registration.refresh_from_db() + self.assertTrue(getattr(self.student.registration, auth_type)) + + response = self.client.get(reverse( + auth_type, args=(getattr(self.student.registration, auth_type).name.split('/')[-1],))) + self.assertEqual(response.status_code, 200) + + from participation.models import Team + team = Team.objects.create(name="Test", trigram="TES") + self.student.registration.team = team + self.student.registration.save() + response = self.client.get(reverse("participation:team_authorizations", args=(team.pk,))) + self.assertEqual(response.status_code, 200) + self.assertEqual(response["content-type"], "application/zip") + + # Do it twice, ensure that the previous authorization got deleted + old_authoratization = self.student.registration.photo_authorization.path + response = self.client.post(reverse("registration:upload_user_photo_authorization", + args=(self.student.registration.pk,)), data=dict( + photo_authorization=open("tfjm/static/Fiche_sanitaire.pdf", "rb"), + )) + self.assertRedirects(response, reverse("registration:user_detail", args=(self.student.pk,)), 302, 200) + self.assertFalse(os.path.isfile(old_authoratization)) + + self.student.registration.refresh_from_db() + self.student.registration.photo_authorization.delete() + + def test_user_detail_forbidden(self): + """ + Create a new user and ensure that it can't see the detail of another user. + """ + self.client.force_login(self.coach) + + response = self.client.get(reverse("registration:user_detail", args=(self.user.pk,))) + self.assertEqual(response.status_code, 403) + + response = self.client.get(reverse("registration:update_user", args=(self.user.pk,))) + self.assertEqual(response.status_code, 403) + + response = self.client.get(reverse("registration:upload_user_photo_authorization", + args=(self.student.registration.pk,))) + self.assertEqual(response.status_code, 403) + + response = self.client.get(reverse("photo_authorization", args=("inexisting-authorization",))) + self.assertEqual(response.status_code, 404) + + with open("media/authorization/photo/example", "w") as f: + f.write("I lost the game.") + self.student.registration.photo_authorization = "authorization/photo/example" + self.student.registration.save() + response = self.client.get(reverse("photo_authorization", args=("example",))) + self.assertEqual(response.status_code, 403) + os.remove("media/authorization/photo/example") + + def test_impersonate(self): + """ + Admin can impersonate other people to act as them. + """ + response = self.client.get(reverse("registration:user_impersonate", args=(0x7ffff42ff,))) + self.assertEqual(response.status_code, 404) + + # Impersonate student account + response = self.client.get(reverse("registration:user_impersonate", args=(self.student.pk,))) + self.assertRedirects(response, reverse("registration:user_detail", args=(self.student.pk,)), 302, 200) + self.assertEqual(self.client.session["_fake_user_id"], self.student.id) + + # Reset admin view + response = self.client.get(reverse("registration:reset_admin")) + self.assertRedirects(response, reverse("index"), 302, 200) + self.assertFalse("_fake_user_id" in self.client.session) + + def test_research(self): + """ + Try to search some things. + """ + call_command("rebuild_index", "--noinput", "-v", 0) + + response = self.client.get(reverse("haystack_search") + "?q=" + self.user.email) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context["object_list"]) + + response = self.client.get(reverse("haystack_search") + "?q=" + + str(self.coach.registration.professional_activity)) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context["object_list"]) + + response = self.client.get(reverse("haystack_search") + "?q=" + + self.student.registration.get_student_class_display()) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context["object_list"]) diff --git a/apps/registration/urls.py b/apps/registration/urls.py new file mode 100644 index 0000000..457614a --- /dev/null +++ b/apps/registration/urls.py @@ -0,0 +1,41 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.urls import path + +from .views import AddOrganizerView, AdultPhotoAuthorizationTemplateView, ChildPhotoAuthorizationTemplateView, \ + InstructionsTemplateView, MyAccountDetailView, ParentalAuthorizationTemplateView, PaymentUpdateView, \ + ResetAdminView, SignupView, UserDetailView, UserImpersonateView, UserListView, UserResendValidationEmailView, \ + UserUpdateView, UserUploadHealthSheetView, UserUploadParentalAuthorizationView, UserUploadPhotoAuthorizationView, \ + UserValidateView, UserValidationEmailSentView + +app_name = "registration" + +urlpatterns = [ + path("signup/", SignupView.as_view(), name="signup"), + path("add-organizer/", AddOrganizerView.as_view(), name="add_organizer"), + path('validate_email/sent/', UserValidationEmailSentView.as_view(), name='email_validation_sent'), + path('validate_email/resend//', UserResendValidationEmailView.as_view(), + name='email_validation_resend'), + path('validate_email///', UserValidateView.as_view(), name='email_validation'), + path("user/", MyAccountDetailView.as_view(), name="my_account_detail"), + path("user//", UserDetailView.as_view(), name="user_detail"), + path("user//update/", UserUpdateView.as_view(), name="update_user"), + path("user//upload-photo-authorization/", UserUploadPhotoAuthorizationView.as_view(), + name="upload_user_photo_authorization"), + path("parental-authorization-template/", ParentalAuthorizationTemplateView.as_view(), + name="parental_authorization_template"), + path("photo-authorization-template/adult/", AdultPhotoAuthorizationTemplateView.as_view(), + name="photo_authorization_adult_template"), + path("photo-authorization-template/child/", ChildPhotoAuthorizationTemplateView.as_view(), + name="photo_authorization_child_template"), + path("instructions-template/", InstructionsTemplateView.as_view(), name="instructions_template"), + path("user//upload-health-sheet/", UserUploadHealthSheetView.as_view(), + name="upload_user_health_sheet"), + path("user//upload-parental-authorization/", UserUploadParentalAuthorizationView.as_view(), + name="upload_user_parental_authorization"), + path("update-payment//", PaymentUpdateView.as_view(), name="update_payment"), + path("user//impersonate/", UserImpersonateView.as_view(), name="user_impersonate"), + path("user/list/", UserListView.as_view(), name="user_list"), + path("reset-admin/", ResetAdminView.as_view(), name="reset_admin"), +] diff --git a/apps/registration/views.py b/apps/registration/views.py new file mode 100644 index 0000000..e8c621f --- /dev/null +++ b/apps/registration/views.py @@ -0,0 +1,638 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +import os +import subprocess +from tempfile import mkdtemp + +from django.conf import settings +from django.contrib.auth.mixins import LoginRequiredMixin +from django.contrib.auth.models import User +from django.contrib.sites.models import Site +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction +from django.db.models import Q +from django.http import FileResponse, Http404 +from django.shortcuts import redirect, resolve_url +from django.template.loader import render_to_string +from django.urls import reverse_lazy +from django.utils import timezone +from django.utils.crypto import get_random_string +from django.utils.http import urlsafe_base64_decode +from django.utils.translation import gettext_lazy as _ +from django.views.generic import CreateView, DetailView, RedirectView, TemplateView, UpdateView, View +from django_tables2 import SingleTableView +from magic import Magic +from participation.models import Passage, Solution, Synthesis, Tournament +from tfjm.tokens import email_validation_token +from tfjm.views import AdminMixin, UserMixin, VolunteerMixin + +from .forms import AddOrganizerForm, AdminRegistrationForm, CoachRegistrationForm, HealthSheetForm, \ + ParentalAuthorizationForm, PaymentForm, PhotoAuthorizationForm, SignupForm, StudentRegistrationForm, UserForm, \ + VolunteerRegistrationForm +from .models import ParticipantRegistration, Payment, Registration, StudentRegistration +from .tables import RegistrationTable + + +class SignupView(CreateView): + """ + Signup, as a participant or a coach. + """ + model = User + form_class = SignupForm + template_name = "registration/signup.html" + extra_context = dict(title=_("Sign up")) + + def get_context_data(self, **kwargs): + context = super().get_context_data() + + context["student_registration_form"] = StudentRegistrationForm(self.request.POST or None) + context["coach_registration_form"] = CoachRegistrationForm(self.request.POST or None) + + del context["student_registration_form"].fields["team"] + del context["student_registration_form"].fields["email_confirmed"] + del context["coach_registration_form"].fields["team"] + del context["coach_registration_form"].fields["email_confirmed"] + + return context + + @transaction.atomic + def form_valid(self, form): + role = form.cleaned_data["role"] + if role == "participant": + registration_form = StudentRegistrationForm(self.request.POST) + else: + registration_form = CoachRegistrationForm(self.request.POST) + del registration_form.fields["team"] + del registration_form.fields["email_confirmed"] + + if not registration_form.is_valid(): + return self.form_invalid(form) + + ret = super().form_valid(form) + registration = registration_form.instance + registration.user = form.instance + registration.save() + registration.send_email_validation_link() + + return ret + + def get_success_url(self): + return reverse_lazy("registration:email_validation_sent") + + +class AddOrganizerView(VolunteerMixin, CreateView): + model = User + form_class = AddOrganizerForm + template_name = "registration/add_organizer.html" + extra_context = dict(title=_("Add organizer")) + + def get_context_data(self, **kwargs): + context = super().get_context_data() + + context["volunteer_registration_form"] = VolunteerRegistrationForm(self.request.POST or None) + context["admin_registration_form"] = AdminRegistrationForm(self.request.POST or None) + + del context["volunteer_registration_form"].fields["email_confirmed"] + del context["admin_registration_form"].fields["email_confirmed"] + + if not self.request.user.registration.is_admin: + del context["form"].fields["type"] + del context["admin_registration_form"] + + return context + + @transaction.atomic + def form_valid(self, form): + role = form.cleaned_data["type"] + if role == "admin": + registration_form = AdminRegistrationForm(self.request.POST) + else: + registration_form = VolunteerRegistrationForm(self.request.POST) + del registration_form.fields["email_confirmed"] + + if not registration_form.is_valid(): + return self.form_invalid(form) + + ret = super().form_valid(form) + registration = registration_form.instance + registration.user = form.instance + registration.save() + registration.send_email_validation_link() + + password = get_random_string(16) + form.instance.set_password(password) + form.instance.save() + + subject = "[TFJM²] " + str(_("New TFJM² organizer account")) + site = Site.objects.first() + message = render_to_string('registration/mails/add_organizer.txt', dict(user=registration.user, + inviter=self.request.user, + password=password, + domain=site.domain)) + html = render_to_string('registration/mails/add_organizer.html', dict(user=registration.user, + inviter=self.request.user, + password=password, + domain=site.domain)) + registration.user.email_user(subject, message, html_message=html) + + return ret + + def get_success_url(self): + return reverse_lazy("registration:email_validation_sent") + + +class UserValidateView(TemplateView): + """ + A view to validate the email address. + """ + title = _("Email validation") + template_name = 'registration/email_validation_complete.html' + extra_context = dict(title=_("Validate email")) + + def get(self, *args, **kwargs): + """ + With a given token and user id (in params), validate the email address. + """ + assert 'uidb64' in kwargs and 'token' in kwargs + + self.validlink = False + user = self.get_user(kwargs['uidb64']) + token = kwargs['token'] + + # Validate the token + if user is not None and email_validation_token.check_token(user, token): + self.validlink = True + user.registration.email_confirmed = True + user.registration.save() + return self.render_to_response(self.get_context_data(), status=200 if self.validlink else 400) + + def get_user(self, uidb64): + """ + Get user from the base64-encoded string. + """ + try: + # urlsafe_base64_decode() decodes to bytestring + uid = urlsafe_base64_decode(uidb64).decode() + user = User.objects.get(pk=uid) + except (TypeError, ValueError, OverflowError, User.DoesNotExist, ValidationError): + user = None + return user + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + context['user_object'] = self.get_user(self.kwargs["uidb64"]) + context['login_url'] = resolve_url(settings.LOGIN_URL) + if self.validlink: + context['validlink'] = True + else: + context.update({ + 'title': _('Email validation unsuccessful'), + 'validlink': False, + }) + return context + + +class UserValidationEmailSentView(TemplateView): + """ + Display the information that the validation link has been sent. + """ + template_name = 'registration/email_validation_email_sent.html' + extra_context = dict(title=_('Email validation email sent')) + + +class UserResendValidationEmailView(LoginRequiredMixin, DetailView): + """ + Rensend the email validation link. + """ + model = User + extra_context = dict(title=_("Resend email validation link")) + + def get(self, request, *args, **kwargs): + user = self.get_object() + user.registration.send_email_validation_link() + return redirect('registration:email_validation_sent') + + +class MyAccountDetailView(LoginRequiredMixin, RedirectView): + """ + Redirect to our own profile detail page. + """ + def get_redirect_url(self, *args, **kwargs): + return reverse_lazy("registration:user_detail", args=(self.request.user.pk,)) + + +class UserDetailView(UserMixin, DetailView): + """ + Display the detail about a user. + """ + + model = User + context_object_name = "user_object" + template_name = "registration/user_detail.html" + + def dispatch(self, request, *args, **kwargs): + me = request.user + if not me.is_authenticated: + return self.handle_no_permission() + user = self.get_object() + if user == me or me.registration.is_admin or me.registration.is_volunteer \ + and user.registration.participates and user.registration.team \ + and user.registration.team.participation.tournament in user.registration.organized_tournaments.all() \ + or user.registration.is_volunteer and me.registration.is_volunteer \ + and me.registration.interesting_tournaments.intersection(user.registration.intersting_tournaments): + return super().dispatch(request, *args, **kwargs) + raise PermissionDenied + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + context["title"] = _("Detail of user {user}").format(user=str(self.object.registration)) + return context + + +class UserListView(AdminMixin, SingleTableView): + """ + Display the list of all registered users. + """ + model = Registration + table_class = RegistrationTable + template_name = "registration/user_list.html" + + +class UserUpdateView(UserMixin, UpdateView): + """ + Update the detail about a user and its registration. + """ + model = User + form_class = UserForm + template_name = "registration/update_user.html" + + def dispatch(self, request, *args, **kwargs): + if not self.request.user.is_authenticated or \ + not self.request.user.registration.is_admin and self.request.user != self.get_object(): + return self.handle_no_permission() + return super().dispatch(request, *args, **kwargs) + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + user = self.get_object() + context["title"] = _("Update user {user}").format(user=str(self.object.registration)) + context["registration_form"] = user.registration.form_class(data=self.request.POST or None, + instance=self.object.registration) + if not self.request.user.registration.is_admin: + if "team" in context["registration_form"].fields: + del context["registration_form"].fields["team"] + del context["registration_form"].fields["email_confirmed"] + return context + + @transaction.atomic + def form_valid(self, form): + user = form.instance + registration_form = user.registration.form_class(data=self.request.POST or None, + instance=self.object.registration) + if not self.request.user.registration.is_admin: + if "team" in registration_form.fields: + del registration_form.fields["team"] + del registration_form.fields["email_confirmed"] + + if not registration_form.is_valid(): + return self.form_invalid(form) + + registration_form.save() + return super().form_valid(form) + + def get_success_url(self): + return reverse_lazy("registration:user_detail", args=(self.object.pk,)) + + +class UserUploadPhotoAuthorizationView(UserMixin, UpdateView): + """ + A participant can send its photo authorization. + """ + model = StudentRegistration + form_class = PhotoAuthorizationForm + template_name = "registration/upload_photo_authorization.html" + extra_context = dict(title=_("Upload photo authorization")) + + def dispatch(self, request, *args, **kwargs): + if not self.request.user.is_authenticated or \ + not self.request.user.registration.is_admin and self.request.user != self.get_object().user: + return self.handle_no_permission() + return super().dispatch(request, *args, **kwargs) + + @transaction.atomic + def form_valid(self, form): + old_instance = StudentRegistration.objects.get(pk=self.object.pk) + if old_instance.photo_authorization: + old_instance.photo_authorization.delete() + return super().form_valid(form) + + def get_success_url(self): + return reverse_lazy("registration:user_detail", args=(self.object.user.pk,)) + + +class UserUploadHealthSheetView(UserMixin, UpdateView): + """ + A participant can send its health sheet. + """ + model = StudentRegistration + form_class = HealthSheetForm + template_name = "registration/upload_health_sheet.html" + extra_context = dict(title=_("Upload health sheet")) + + def dispatch(self, request, *args, **kwargs): + if not self.request.user.is_authenticated or \ + not self.request.user.registration.is_admin and self.request.user != self.get_object().user: + return self.handle_no_permission() + return super().dispatch(request, *args, **kwargs) + + @transaction.atomic + def form_valid(self, form): + old_instance = StudentRegistration.objects.get(pk=self.object.pk) + if old_instance.health_sheet: + old_instance.health_sheet.delete() + return super().form_valid(form) + + def get_success_url(self): + return reverse_lazy("registration:user_detail", args=(self.object.user.pk,)) + + +class UserUploadParentalAuthorizationView(UserMixin, UpdateView): + """ + A participant can send its parental authorization. + """ + model = StudentRegistration + form_class = ParentalAuthorizationForm + template_name = "registration/upload_parental_authorization.html" + extra_context = dict(title=_("Upload parental authorization")) + + def dispatch(self, request, *args, **kwargs): + if not self.request.user.is_authenticated or \ + not self.request.user.registration.is_admin and self.request.user != self.get_object().user: + return self.handle_no_permission() + return super().dispatch(request, *args, **kwargs) + + @transaction.atomic + def form_valid(self, form): + old_instance = StudentRegistration.objects.get(pk=self.object.pk) + if old_instance.parental_authorization: + old_instance.parental_authorization.delete() + return super().form_valid(form) + + def get_success_url(self): + return reverse_lazy("registration:user_detail", args=(self.object.user.pk,)) + + +class AuthorizationTemplateView(TemplateView): + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + + if "registration_id" in self.request.GET: + registration = Registration.objects.get(pk=self.request.GET.get("registration_id")) + # Don't get unwanted information + if registration.user == self.request.user \ + or self.request.user.is_authenticated and self.request.user.registration.is_admin: + context["registration"] = registration + if "tournament_id" in self.request.GET: + context["tournament"] = Tournament.objects.get(pk=self.request.GET.get("tournament_id")) + else: + raise ValueError("Merci d'indiquer un tournoi.") + + return context + + def render_to_response(self, context, **response_kwargs): + tex = render_to_string(self.template_name, context=context, request=self.request) + temp_dir = mkdtemp() + with open(os.path.join(temp_dir, "texput.tex"), "w") as f: + f.write(tex) + process = subprocess.Popen(["pdflatex", "-interaction=nonstopmode", f"-output-directory={temp_dir}", + os.path.join(temp_dir, "texput.tex"), ]) + process.wait() + return FileResponse(open(os.path.join(temp_dir, "texput.pdf"), "rb"), + content_type="application/pdf", + filename=self.template_name.split("/")[-1][:-3] + "pdf") + + +class AdultPhotoAuthorizationTemplateView(AuthorizationTemplateView): + template_name = "registration/tex/Autorisation_droit_image_majeur.tex" + + +class ChildPhotoAuthorizationTemplateView(AuthorizationTemplateView): + template_name = "registration/tex/Autorisation_droit_image_mineur.tex" + + +class ParentalAuthorizationTemplateView(AuthorizationTemplateView): + template_name = "registration/tex/Autorisation_parentale.tex" + + +class InstructionsTemplateView(AuthorizationTemplateView): + template_name = "registration/tex/Instructions.tex" + + +class PaymentUpdateView(LoginRequiredMixin, UpdateView): + model = Payment + form_class = PaymentForm + + def dispatch(self, request, *args, **kwargs): + if not self.request.user.is_authenticated or \ + not self.request.user.registration.is_admin \ + and (self.request.user != self.get_object().registration.user + or self.get_object().valid is not False): + return self.handle_no_permission() + return super().dispatch(request, *args, **kwargs) + + def get_form(self, form_class=None): + form = super().get_form(form_class) + if not self.request.user.registration.is_admin: + del form.fields["type"].widget.choices[-1] + del form.fields["valid"] + return form + + def form_valid(self, form): + if not self.request.user.registration.is_admin: + form.instance.valid = None + return super().form_valid(form) + + +class PhotoAuthorizationView(LoginRequiredMixin, View): + """ + Display the sent photo authorization. + """ + def get(self, request, *args, **kwargs): + filename = kwargs["filename"] + path = f"media/authorization/photo/{filename}" + if not os.path.exists(path): + raise Http404 + student = ParticipantRegistration.objects.get(photo_authorization__endswith=filename) + user = request.user + if not (student.user == user or user.registration.is_admin or user.registration.is_volunteer and student.team + and student.team.participation.tournament in user.registration.organized_tournaments.all()): + raise PermissionDenied + # Guess mime type of the file + mime = Magic(mime=True) + mime_type = mime.from_file(path) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + # Replace file name + true_file_name = _("Photo authorization of {student}.{ext}").format(student=str(student), ext=ext) + return FileResponse(open(path, "rb"), content_type=mime_type, filename=true_file_name) + + +class HealthSheetView(LoginRequiredMixin, View): + """ + Display the sent health sheet. + """ + def get(self, request, *args, **kwargs): + filename = kwargs["filename"] + path = f"media/authorization/health/{filename}" + if not os.path.exists(path): + raise Http404 + student = StudentRegistration.objects.get(health_sheet__endswith=filename) + user = request.user + if not (student.user == user or user.registration.is_admin or user.registration.is_volunteer and student.team + and student.team.participation.tournament in user.registration.organized_tournaments.all()): + raise PermissionDenied + # Guess mime type of the file + mime = Magic(mime=True) + mime_type = mime.from_file(path) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + # Replace file name + true_file_name = _("Health sheet of {student}.{ext}").format(student=str(student), ext=ext) + return FileResponse(open(path, "rb"), content_type=mime_type, filename=true_file_name) + + +class ParentalAuthorizationView(LoginRequiredMixin, View): + """ + Display the sent parental authorization. + """ + def get(self, request, *args, **kwargs): + filename = kwargs["filename"] + path = f"media/authorization/parental/{filename}" + if not os.path.exists(path): + raise Http404 + student = StudentRegistration.objects.get(parental_authorization__endswith=filename) + user = request.user + if not (student.user == user or user.registration.is_admin or user.registration.is_volunteer and student.team + and student.team.participation.tournament in user.registration.organized_tournaments.all()): + raise PermissionDenied + # Guess mime type of the file + mime = Magic(mime=True) + mime_type = mime.from_file(path) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + # Replace file name + true_file_name = _("Parental authorization of {student}.{ext}").format(student=str(student), ext=ext) + return FileResponse(open(path, "rb"), content_type=mime_type, filename=true_file_name) + + +class ScholarshipView(LoginRequiredMixin, View): + """ + Display the sent scholarship paper. + """ + def get(self, request, *args, **kwargs): + filename = kwargs["filename"] + path = f"media/authorization/scholarship/{filename}" + if not os.path.exists(path): + raise Http404 + payment = Payment.objects.get(scholarship_file__endswith=filename) + user = request.user + if not (payment.registration.user == user or user.registration.is_admin): + raise PermissionDenied + # Guess mime type of the file + mime = Magic(mime=True) + mime_type = mime.from_file(path) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + # Replace file name + true_file_name = _("Scholarship attestation of {user}.{ext}").format(user=str(user.registration), ext=ext) + return FileResponse(open(path, "rb"), content_type=mime_type, filename=true_file_name) + + +class SolutionView(LoginRequiredMixin, View): + """ + Display the sent solution. + """ + def get(self, request, *args, **kwargs): + filename = kwargs["filename"] + path = f"media/solutions/{filename}" + if not os.path.exists(path): + raise Http404 + solution = Solution.objects.get(file__endswith=filename) + user = request.user + passage_participant_qs = Passage.objects.filter(Q(defender=user.registration.team.participation) + | Q(opponent=user.registration.team.participation) + | Q(reporter=user.registration.team.participation), + defender=solution.participation, + solution_number=solution.problem) + if not (user.registration.is_admin or user.registration.is_volunteer + and Passage.objects.filter(Q(pool__juries=user.registration) + | Q(pool__tournament__in=user.registration.organized_tournaments.all()), + defender=solution.participation, + solution_number=solution.problem).exists() + or user.registration.participates and user.registration.team + and (solution.participation.team == user.registration.team or + any(passage.pool.round == 1 + or timezone.now() >= passage.pool.tournament.solutions_available_second_phase + for passage in passage_participant_qs.all()))): + raise PermissionDenied + # Guess mime type of the file + mime = Magic(mime=True) + mime_type = mime.from_file(path) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + # Replace file name + true_file_name = str(solution) + f".{ext}" + return FileResponse(open(path, "rb"), content_type=mime_type, filename=true_file_name) + + +class SynthesisView(LoginRequiredMixin, View): + """ + Display the sent synthesis. + """ + def get(self, request, *args, **kwargs): + filename = kwargs["filename"] + path = f"media/syntheses/{filename}" + if not os.path.exists(path): + raise Http404 + synthesis = Synthesis.objects.get(file__endswith=filename) + user = request.user + if not (user.registration.is_admin or user.registration.is_volunteer + and (user.registration in synthesis.passage.pool.juries.all() + or user.registration in synthesis.passage.pool.tournament.organizers.all()) + or user.registration.participates and user.registration.team == synthesis.participation.team): + raise PermissionDenied + # Guess mime type of the file + mime = Magic(mime=True) + mime_type = mime.from_file(path) + ext = mime_type.split("/")[1].replace("jpeg", "jpg") + # Replace file name + true_file_name = str(synthesis) + f".{ext}" + return FileResponse(open(path, "rb"), content_type=mime_type, filename=true_file_name) + + +class UserImpersonateView(LoginRequiredMixin, RedirectView): + """ + An administrator can log in through this page as someone else, and act as this other person. + """ + + def dispatch(self, request, *args, **kwargs): + if self.request.user.registration.is_admin: + if not User.objects.filter(pk=kwargs["pk"]).exists(): + raise Http404 + session = request.session + session["admin"] = request.user.pk + session["_fake_user_id"] = kwargs["pk"] + return super().dispatch(request, *args, **kwargs) + + def get_redirect_url(self, *args, **kwargs): + return reverse_lazy("registration:user_detail", args=(kwargs["pk"],)) + + +class ResetAdminView(LoginRequiredMixin, View): + """ + Return to admin view, clear the session field that let an administrator to log in as someone else. + """ + + def dispatch(self, request, *args, **kwargs): + user = request.user + if not user.is_authenticated: + return self.handle_no_permission() + if "_fake_user_id" in request.session: + del request.session["_fake_user_id"] + return redirect(request.GET.get("path", reverse_lazy("index"))) diff --git a/apps/tournament/__init__.py b/apps/tournament/__init__.py deleted file mode 100644 index 9868b56..0000000 --- a/apps/tournament/__init__.py +++ /dev/null @@ -1 +0,0 @@ -default_app_config = 'tournament.apps.TournamentConfig' diff --git a/apps/tournament/admin.py b/apps/tournament/admin.py deleted file mode 100644 index c55cc4b..0000000 --- a/apps/tournament/admin.py +++ /dev/null @@ -1,31 +0,0 @@ -from django.contrib.auth.admin import admin - -from .models import Team, Tournament, Pool, Payment - - -@admin.register(Team) -class TeamAdmin(admin.ModelAdmin): - """ - Django admin page for teams. - """ - - -@admin.register(Tournament) -class TournamentAdmin(admin.ModelAdmin): - """ - Django admin page for tournaments. - """ - - -@admin.register(Pool) -class PoolAdmin(admin.ModelAdmin): - """ - Django admin page for pools. - """ - - -@admin.register(Payment) -class PaymentAdmin(admin.ModelAdmin): - """ - Django admin page for payments. - """ diff --git a/apps/tournament/apps.py b/apps/tournament/apps.py deleted file mode 100644 index 66a212b..0000000 --- a/apps/tournament/apps.py +++ /dev/null @@ -1,10 +0,0 @@ -from django.apps import AppConfig -from django.utils.translation import gettext_lazy as _ - - -class TournamentConfig(AppConfig): - """ - The tournament app handles all that is related to the tournaments. - """ - name = 'tournament' - verbose_name = _('tournament') diff --git a/apps/tournament/forms.py b/apps/tournament/forms.py deleted file mode 100644 index 901b97a..0000000 --- a/apps/tournament/forms.py +++ /dev/null @@ -1,262 +0,0 @@ -import os -import re - -from django import forms -from django.db.models import Q -from django.template.defaultfilters import filesizeformat -from django.utils import timezone -from django.utils.translation import gettext_lazy as _ - -from member.models import TFJMUser, Solution, Synthesis -from tfjm.inputs import DatePickerInput, DateTimePickerInput, AmountInput -from tournament.models import Tournament, Team, Pool - - -class TournamentForm(forms.ModelForm): - """ - Create and update tournaments. - """ - - # Only organizers can organize tournaments. Well, that's pretty normal... - organizers = forms.ModelMultipleChoiceField( - TFJMUser.objects.filter(Q(role="0admin") | Q(role="1volunteer")).order_by('role'), - label=_("Organizers"), - ) - - def clean(self): - cleaned_data = super().clean() - - if not self.instance.pk: - if Tournament.objects.filter(name=cleaned_data["data"], year=os.getenv("TFJM_YEAR")): - self.add_error("name", _("This tournament already exists.")) - if cleaned_data["final"] and Tournament.objects.filter(final=True, year=os.getenv("TFJM_YEAR")): - self.add_error("name", _("The final tournament was already defined.")) - - return cleaned_data - - class Meta: - model = Tournament - exclude = ('year',) - widgets = { - "price": AmountInput(), - "date_start": DatePickerInput(), - "date_end": DatePickerInput(), - "date_inscription": DateTimePickerInput(), - "date_solutions": DateTimePickerInput(), - "date_syntheses": DateTimePickerInput(), - "date_solutions_2": DateTimePickerInput(), - "date_syntheses_2": DateTimePickerInput(), - } - - -class OrganizerForm(forms.ModelForm): - """ - Register an organizer in the website. - """ - - class Meta: - model = TFJMUser - fields = ('last_name', 'first_name', 'email', 'is_superuser',) - - def clean(self): - cleaned_data = super().clean() - - if TFJMUser.objects.filter(email=cleaned_data["email"], year=os.getenv("TFJM_YEAR")).exists(): - self.add_error("email", _("This organizer already exist.")) - - return cleaned_data - - def save(self, commit=True): - user = self.instance - user.role = '0admin' if user.is_superuser else '1volunteer' - user.save() - super().save(commit) - - -class TeamForm(forms.ModelForm): - """ - Add and update a team. - """ - tournament = forms.ModelChoiceField( - Tournament.objects.filter(date_inscription__gte=timezone.now(), final=False), - ) - - class Meta: - model = Team - fields = ('name', 'trigram', 'tournament',) - - def clean(self): - cleaned_data = super().clean() - - cleaned_data["trigram"] = cleaned_data["trigram"].upper() - - if not re.match("[A-Z]{3}", cleaned_data["trigram"]): - self.add_error("trigram", _("The trigram must be composed of three upcase letters.")) - - if not self.instance.pk: - if Team.objects.filter(trigram=cleaned_data["trigram"], year=os.getenv("TFJM_YEAR")).exists(): - self.add_error("trigram", _("This trigram is already used.")) - - if Team.objects.filter(name=cleaned_data["name"], year=os.getenv("TFJM_YEAR")).exists(): - self.add_error("name", _("This name is already used.")) - - if cleaned_data["tournament"].date_inscription < timezone.now: - self.add_error("tournament", _("This tournament is already closed.")) - - return cleaned_data - - -class JoinTeam(forms.Form): - """ - Form to join a team with an access code. - """ - - access_code = forms.CharField( - label=_("Access code"), - max_length=6, - ) - - def clean(self): - cleaned_data = super().clean() - - if not re.match("[a-z0-9]{6}", cleaned_data["access_code"]): - self.add_error('access_code', _("The access code must be composed of 6 alphanumeric characters.")) - - team = Team.objects.filter(access_code=cleaned_data["access_code"]) - if not team.exists(): - self.add_error('access_code', _("This access code is invalid.")) - team = team.get() - if not team.invalid: - self.add_error('access_code', _("The team is already validated.")) - cleaned_data["team"] = team - - return cleaned_data - - -class SolutionForm(forms.ModelForm): - """ - Form to upload a solution. - """ - - problem = forms.ChoiceField( - label=_("Problem"), - choices=[(str(i), _("Problem #%(problem)d") % {"problem": i}) for i in range(1, 9)], - ) - - def clean_file(self): - content = self.cleaned_data['file'] - content_type = content.content_type - if content_type in ["application/pdf"]: - if content.size > 5 * 2 ** 20: - raise forms.ValidationError( - _('Please keep filesize under %(max_size)s. Current filesize %(current_size)s') % { - "max_size": filesizeformat(2 * 2 ** 20), - "current_size": filesizeformat(content.size) - }) - else: - raise forms.ValidationError(_('The file should be a PDF file.')) - return content - - class Meta: - model = Solution - fields = ('file', 'problem',) - - -class SynthesisForm(forms.ModelForm): - """ - Form to upload a synthesis. - """ - - def clean_file(self): - content = self.cleaned_data['file'] - content_type = content.content_type - if content_type in ["application/pdf"]: - if content.size > 5 * 2 ** 20: - raise forms.ValidationError( - _('Please keep filesize under %(max_size)s. Current filesize %(current_size)s') % { - "max_size": filesizeformat(2 * 2 ** 20), - "current_size": filesizeformat(content.size) - }) - else: - raise forms.ValidationError(_('The file should be a PDF file.')) - return content - - class Meta: - model = Synthesis - fields = ('file', 'source', 'round',) - - -class PoolForm(forms.ModelForm): - """ - Form to add a pool. - Should not be used: prefer to pass by API and auto-add pools with the results of the draw. - """ - - team1 = forms.ModelChoiceField( - Team.objects.filter(validation_status="2valid").all(), - empty_label=_("Choose a team..."), - label=_("Team 1"), - ) - - problem1 = forms.IntegerField( - min_value=1, - max_value=8, - initial=1, - label=_("Problem defended by team 1"), - ) - - team2 = forms.ModelChoiceField( - Team.objects.filter(validation_status="2valid").all(), - empty_label=_("Choose a team..."), - label=_("Team 2"), - ) - - problem2 = forms.IntegerField( - min_value=1, - max_value=8, - initial=2, - label=_("Problem defended by team 2"), - ) - - team3 = forms.ModelChoiceField( - Team.objects.filter(validation_status="2valid").all(), - empty_label=_("Choose a team..."), - label=_("Team 3"), - ) - - problem3 = forms.IntegerField( - min_value=1, - max_value=8, - initial=3, - label=_("Problem defended by team 3"), - ) - - def clean(self): - cleaned_data = super().clean() - - team1, pb1 = cleaned_data["team1"], cleaned_data["problem1"] - team2, pb2 = cleaned_data["team2"], cleaned_data["problem2"] - team3, pb3 = cleaned_data["team3"], cleaned_data["problem3"] - - sol1 = Solution.objects.get(team=team1, problem=pb1, final=team1.selected_for_final) - sol2 = Solution.objects.get(team=team2, problem=pb2, final=team2.selected_for_final) - sol3 = Solution.objects.get(team=team3, problem=pb3, final=team3.selected_for_final) - - cleaned_data["teams"] = [team1, team2, team3] - cleaned_data["solutions"] = [sol1, sol2, sol3] - - return cleaned_data - - def save(self, commit=True): - pool = super().save(commit) - - pool.refresh_from_db() - pool.teams.set(self.cleaned_data["teams"]) - pool.solutions.set(self.cleaned_data["solutions"]) - pool.save() - - return pool - - class Meta: - model = Pool - fields = ('round', 'juries',) diff --git a/apps/tournament/migrations/__init__.py b/apps/tournament/migrations/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/apps/tournament/models.py b/apps/tournament/models.py deleted file mode 100644 index 11d5886..0000000 --- a/apps/tournament/models.py +++ /dev/null @@ -1,432 +0,0 @@ -import os -import random - -from django.core.mail import send_mail -from django.db import models -from django.template.loader import render_to_string -from django.urls import reverse_lazy -from django.utils import timezone -from django.utils.translation import gettext_lazy as _ - - -class Tournament(models.Model): - """ - Store the information of a tournament. - """ - - name = models.CharField( - max_length=255, - verbose_name=_("name"), - ) - - organizers = models.ManyToManyField( - 'member.TFJMUser', - related_name="organized_tournaments", - verbose_name=_("organizers"), - help_text=_("List of all organizers that can see and manipulate data of the tournament and the teams."), - ) - - size = models.PositiveSmallIntegerField( - verbose_name=_("size"), - help_text=_("Number of teams that are allowed to join the tournament."), - ) - - place = models.CharField( - max_length=255, - verbose_name=_("place"), - ) - - price = models.PositiveSmallIntegerField( - verbose_name=_("price"), - help_text=_("Price asked to participants. Free with a scholarship."), - ) - - description = models.TextField( - verbose_name=_("description"), - ) - - date_start = models.DateField( - default=timezone.now, - verbose_name=_("date start"), - ) - - date_end = models.DateField( - default=timezone.now, - verbose_name=_("date end"), - ) - - date_inscription = models.DateTimeField( - default=timezone.now, - verbose_name=_("date of registration closing"), - ) - - date_solutions = models.DateTimeField( - default=timezone.now, - verbose_name=_("date of maximal solution submission"), - ) - - date_syntheses = models.DateTimeField( - default=timezone.now, - verbose_name=_("date of maximal syntheses submission for the first round"), - ) - - date_solutions_2 = models.DateTimeField( - default=timezone.now, - verbose_name=_("date when solutions of round 2 are available"), - ) - - date_syntheses_2 = models.DateTimeField( - default=timezone.now, - verbose_name=_("date of maximal syntheses submission for the second round"), - ) - - final = models.BooleanField( - verbose_name=_("final tournament"), - help_text=_("It should be only one final tournament."), - ) - - year = models.PositiveIntegerField( - default=os.getenv("TFJM_YEAR", timezone.now().year), - verbose_name=_("year"), - ) - - @property - def teams(self): - """ - Get all teams that are registered to this tournament, with a distinction for the final tournament. - """ - return self._teams if not self.final else Team.objects.filter(selected_for_final=True) - - @property - def linked_organizers(self): - """ - Display a list of the organizers with links to their personal page. - """ - return [''.format(url=reverse_lazy("member:information", args=(user.pk,))) + str(user) + '' - for user in self.organizers.all()] - - @property - def solutions(self): - """ - Get all sent solutions for this tournament. - """ - from member.models import Solution - return Solution.objects.filter(final=self.final) if self.final \ - else Solution.objects.filter(team__tournament=self, final=False) - - @property - def syntheses(self): - """ - Get all sent syntheses for this tournament. - """ - from member.models import Synthesis - return Synthesis.objects.filter(final=self.final) if self.final \ - else Synthesis.objects.filter(team__tournament=self, final=False) - - @classmethod - def get_final(cls): - """ - Get the final tournament. - This should exist and be unique. - """ - return cls.objects.get(year=os.getenv("TFJM_YEAR"), final=True) - - class Meta: - verbose_name = _("tournament") - verbose_name_plural = _("tournaments") - - def send_mail_to_organizers(self, template_name, subject="Contact TFJM²", **kwargs): - """ - Send a mail to all organizers of the tournament. - The template of the mail should be found either in templates/mail_templates/.html for the HTML - version and in templates/mail_templates/.txt for the plain text version. - The context of the template contains the tournament and the user. Extra context can be given through the kwargs. - """ - context = kwargs - context["tournament"] = self - for user in self.organizers.all(): - context["user"] = user - message = render_to_string("mail_templates/" + template_name + ".txt", context=context) - message_html = render_to_string("mail_templates/" + template_name + ".html", context=context) - send_mail(subject, message, "contact@tfjm.org", [user.email], html_message=message_html) - from member.models import TFJMUser - for user in TFJMUser.objects.get(is_superuser=True).all(): - context["user"] = user - message = render_to_string("mail_templates/" + template_name + ".txt", context=context) - message_html = render_to_string("mail_templates/" + template_name + ".html", context=context) - send_mail(subject, message, "contact@tfjm.org", [user.email], html_message=message_html) - - def __str__(self): - return self.name - - -class Team(models.Model): - """ - Store information about a registered team. - """ - - name = models.CharField( - max_length=255, - verbose_name=_("name"), - ) - - trigram = models.CharField( - max_length=3, - verbose_name=_("trigram"), - help_text=_("The trigram should be composed of 3 capitalize letters, that is a funny acronym for the team."), - ) - - tournament = models.ForeignKey( - Tournament, - on_delete=models.PROTECT, - related_name="_teams", - verbose_name=_("tournament"), - help_text=_("The tournament where the team is registered."), - ) - - inscription_date = models.DateTimeField( - auto_now_add=True, - verbose_name=_("inscription date"), - ) - - validation_status = models.CharField( - max_length=8, - choices=[ - ("0invalid", _("Registration not validated")), - ("1waiting", _("Waiting for validation")), - ("2valid", _("Registration validated")), - ], - verbose_name=_("validation status"), - ) - - selected_for_final = models.BooleanField( - default=False, - verbose_name=_("selected for final"), - ) - - access_code = models.CharField( - max_length=6, - unique=True, - verbose_name=_("access code"), - ) - - year = models.PositiveIntegerField( - default=os.getenv("TFJM_YEAR", timezone.now().year), - verbose_name=_("year"), - ) - - @property - def valid(self): - return self.validation_status == "2valid" - - @property - def waiting(self): - return self.validation_status == "1waiting" - - @property - def invalid(self): - return self.validation_status == "0invalid" - - @property - def coaches(self): - """ - Get all coaches of a team. - """ - return self.users.all().filter(role="2coach") - - @property - def linked_coaches(self): - """ - Get a list of the coaches of a team with html links to their pages. - """ - return [''.format(url=reverse_lazy("member:information", args=(user.pk,))) + str(user) + '' - for user in self.coaches] - - @property - def participants(self): - """ - Get all particpants of a team, coaches excluded. - """ - return self.users.all().filter(role="3participant") - - @property - def linked_participants(self): - """ - Get a list of the participants of a team with html links to their pages. - """ - return [''.format(url=reverse_lazy("member:information", args=(user.pk,))) + str(user) + '' - for user in self.participants] - - @property - def future_tournament(self): - """ - Get the last tournament where the team is registered. - Only matters if the team is selected for final: if this is the case, we return the final tournament. - Useful for deadlines. - """ - return Tournament.get_final() if self.selected_for_final else self.tournament - - @property - def can_validate(self): - """ - Check if a given team is able to ask for validation. - A team can validate if: - * All participants filled the photo consent - * Minor participants filled the parental consent - * Minor participants filled the sanitary plug - * Teams sent their motivation letter - * The team contains at least 4 participants - * The team contains at least 1 coach - """ - # TODO In a normal time, team needs a motivation letter and authorizations. - return self.coaches.exists() and self.participants.count() >= 4\ - and self.tournament.date_inscription <= timezone.now() - - class Meta: - verbose_name = _("team") - verbose_name_plural = _("teams") - unique_together = (('name', 'year',), ('trigram', 'year',),) - - def send_mail(self, template_name, subject="Contact TFJM²", **kwargs): - """ - Send a mail to all members of a team with a given template. - The template of the mail should be found either in templates/mail_templates/.html for the HTML - version and in templates/mail_templates/.txt for the plain text version. - The context of the template contains the team and the user. Extra context can be given through the kwargs. - """ - context = kwargs - context["team"] = self - for user in self.users.all(): - context["user"] = user - message = render_to_string("mail_templates/" + template_name + ".txt", context=context) - message_html = render_to_string("mail_templates/" + template_name + ".html", context=context) - send_mail(subject, message, "contact@tfjm.org", [user.email], html_message=message_html) - - def __str__(self): - return self.trigram + " — " + self.name - - -class Pool(models.Model): - """ - Store information of a pool. - A pool is only a list of accessible solutions to some teams and some juries. - TODO: check that the set of teams is equal to the set of the teams that have a solution in this set. - TODO: Moreover, a team should send only one solution. - """ - teams = models.ManyToManyField( - Team, - related_name="pools", - verbose_name=_("teams"), - ) - - solutions = models.ManyToManyField( - "member.Solution", - related_name="pools", - verbose_name=_("solutions"), - ) - - round = models.PositiveIntegerField( - choices=[ - (1, _("Round 1")), - (2, _("Round 2")), - ], - verbose_name=_("round"), - ) - - juries = models.ManyToManyField( - "member.TFJMUser", - related_name="pools", - verbose_name=_("juries"), - ) - - extra_access_token = models.CharField( - max_length=64, - default="", - verbose_name=_("extra access token"), - help_text=_("Let other users access to the pool data without logging in."), - ) - - @property - def problems(self): - """ - Get problem numbers of the sent solutions as a list of integers. - """ - return list(d["problem"] for d in self.solutions.values("problem").all()) - - @property - def tournament(self): - """ - Get the concerned tournament. - We assume that the pool is correct, so all solutions belong to the same tournament. - """ - return self.solutions.first().tournament - - @property - def syntheses(self): - """ - Get the syntheses of the teams that are in this pool, for the correct round. - """ - from member.models import Synthesis - return Synthesis.objects.filter(team__in=self.teams.all(), round=self.round, final=self.tournament.final) - - def save(self, **kwargs): - if not self.extra_access_token: - alphabet = "0123456789abcdefghijklmnopqrstuvwxyz0123456789" - code = "".join(random.choice(alphabet) for _ in range(64)) - self.extra_access_token = code - super().save(**kwargs) - - class Meta: - verbose_name = _("pool") - verbose_name_plural = _("pools") - - -class Payment(models.Model): - """ - Store some information about payments, to recover data. - TODO: handle it... - """ - user = models.OneToOneField( - 'member.TFJMUser', - on_delete=models.CASCADE, - related_name="payment", - verbose_name=_("user"), - ) - - team = models.ForeignKey( - Team, - on_delete=models.CASCADE, - related_name="payments", - verbose_name=_("team"), - ) - - method = models.CharField( - max_length=16, - choices=[ - ("not_paid", _("Not paid")), - ("credit_card", _("Credit card")), - ("check", _("Bank check")), - ("transfer", _("Bank transfer")), - ("cash", _("Cash")), - ("scholarship", _("Scholarship")), - ], - default="not_paid", - verbose_name=_("payment method"), - ) - - validation_status = models.CharField( - max_length=8, - choices=[ - ("0invalid", _("Registration not validated")), - ("1waiting", _("Waiting for validation")), - ("2valid", _("Registration validated")), - ], - verbose_name=_("validation status"), - ) - - class Meta: - verbose_name = _("payment") - verbose_name_plural = _("payments") - - def __str__(self): - return _("Payment of {user}").format(str(self.user)) diff --git a/apps/tournament/tables.py b/apps/tournament/tables.py deleted file mode 100644 index 33e39a1..0000000 --- a/apps/tournament/tables.py +++ /dev/null @@ -1,164 +0,0 @@ -import django_tables2 as tables -from django.urls import reverse_lazy -from django.utils.html import format_html -from django.utils.translation import gettext_lazy as _ -from django_tables2 import A - -from member.models import Solution, Synthesis -from .models import Tournament, Team, Pool - - -class TournamentTable(tables.Table): - """ - List all tournaments. - """ - - name = tables.LinkColumn( - "tournament:detail", - args=[A("pk")], - ) - - date_start = tables.Column( - verbose_name=_("dates").capitalize(), - ) - - def render_date_start(self, record): - return _("From {start:%b %d %Y} to {end:%b %d %Y}").format(start=record.date_start, end=record.date_end) - - class Meta: - model = Tournament - fields = ("name", "date_start", "date_inscription", "date_solutions", "size", ) - attrs = { - 'class': 'table table-condensed table-striped table-hover' - } - order_by = ('date_start', 'name',) - - -class TeamTable(tables.Table): - """ - Table of some teams. Can be filtered with a queryset (for example, teams of a tournament) - """ - - name = tables.LinkColumn( - "tournament:team_detail", - args=[A("pk")], - ) - - class Meta: - model = Team - fields = ("name", "trigram", "validation_status", ) - attrs = { - 'class': 'table table-condensed table-striped table-hover' - } - order_by = ('-validation_status', 'trigram',) - - -class SolutionTable(tables.Table): - """ - Display a table of some solutions. - """ - - team = tables.LinkColumn( - "tournament:team_detail", - args=[A("team.pk")], - ) - - tournament = tables.LinkColumn( - "tournament:detail", - args=[A("tournament.pk")], - accessor=A("tournament"), - order_by=("team__tournament__date_start", "team__tournament__name",), - verbose_name=_("Tournament"), - ) - - file = tables.LinkColumn( - "document", - args=[A("file")], - attrs={ - "a": { - "data-turbolinks": "false", - } - } - ) - - def render_file(self): - return _("Download") - - class Meta: - model = Solution - fields = ("team", "tournament", "problem", "uploaded_at", "file", ) - attrs = { - 'class': 'table table-condensed table-striped table-hover' - } - - -class SynthesisTable(tables.Table): - """ - Display a table of some syntheses. - """ - - team = tables.LinkColumn( - "tournament:team_detail", - args=[A("team.pk")], - ) - - tournament = tables.LinkColumn( - "tournament:detail", - args=[A("tournament.pk")], - accessor=A("tournament"), - order_by=("team__tournament__date_start", "team__tournament__name",), - verbose_name=_("tournament"), - ) - - file = tables.LinkColumn( - "document", - args=[A("file")], - attrs={ - "a": { - "data-turbolinks": "false", - } - } - ) - - def render_file(self): - return _("Download") - - class Meta: - model = Synthesis - fields = ("team", "tournament", "round", "source", "uploaded_at", "file", ) - attrs = { - 'class': 'table table-condensed table-striped table-hover' - } - - -class PoolTable(tables.Table): - """ - Display a table of some pools. - """ - - problems = tables.Column( - verbose_name=_("Problems"), - orderable=False, - ) - - tournament = tables.LinkColumn( - "tournament:detail", - args=[A("tournament.pk")], - verbose_name=_("Tournament"), - order_by=("teams__tournament__date_start", "teams__tournament__name",), - ) - - def render_teams(self, record, value): - return format_html('{trigrams}', - url=reverse_lazy('tournament:pool_detail', args=(record.pk,)), - trigrams=", ".join(team.trigram for team in value.all())) - - def render_problems(self, value): - return ", ".join([str(pb) for pb in value]) - - class Meta: - model = Pool - fields = ("teams", "tournament", "problems", "round", ) - attrs = { - 'class': 'table table-condensed table-striped table-hover' - } diff --git a/apps/tournament/urls.py b/apps/tournament/urls.py deleted file mode 100644 index 364f23d..0000000 --- a/apps/tournament/urls.py +++ /dev/null @@ -1,24 +0,0 @@ -from django.urls import path - -from .views import TournamentListView, TournamentCreateView, TournamentDetailView, TournamentUpdateView, \ - TeamDetailView, TeamUpdateView, AddOrganizerView, SolutionsView, SolutionsOrgaListView, SynthesesView, \ - SynthesesOrgaListView, PoolListView, PoolCreateView, PoolDetailView - -app_name = "tournament" - -urlpatterns = [ - path('list/', TournamentListView.as_view(), name="list"), - path("add/", TournamentCreateView.as_view(), name="add"), - path('/', TournamentDetailView.as_view(), name="detail"), - path('/update/', TournamentUpdateView.as_view(), name="update"), - path('team//', TeamDetailView.as_view(), name="team_detail"), - path('team//update/', TeamUpdateView.as_view(), name="team_update"), - path("add-organizer/", AddOrganizerView.as_view(), name="add_organizer"), - path("solutions/", SolutionsView.as_view(), name="solutions"), - path("all-solutions/", SolutionsOrgaListView.as_view(), name="all_solutions"), - path("syntheses/", SynthesesView.as_view(), name="syntheses"), - path("all_syntheses/", SynthesesOrgaListView.as_view(), name="all_syntheses"), - path("pools/", PoolListView.as_view(), name="pools"), - path("pool/add/", PoolCreateView.as_view(), name="create_pool"), - path("pool//", PoolDetailView.as_view(), name="pool_detail"), -] diff --git a/apps/tournament/views.py b/apps/tournament/views.py deleted file mode 100644 index 450351f..0000000 --- a/apps/tournament/views.py +++ /dev/null @@ -1,662 +0,0 @@ -import random -import zipfile -from datetime import timedelta -from io import BytesIO - -from django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin -from django.core.exceptions import PermissionDenied -from django.core.mail import send_mail -from django.db.models import Q -from django.http import HttpResponse -from django.shortcuts import redirect -from django.template.loader import render_to_string -from django.urls import reverse_lazy -from django.utils import timezone -from django.utils.translation import gettext_lazy as _ -from django.views.generic import DetailView, CreateView, UpdateView -from django.views.generic.edit import BaseFormView -from django_tables2.views import SingleTableView -from member.models import TFJMUser, Solution, Synthesis - -from .forms import TournamentForm, OrganizerForm, SolutionForm, SynthesisForm, TeamForm, PoolForm -from .models import Tournament, Team, Pool -from .tables import TournamentTable, TeamTable, SolutionTable, SynthesisTable, PoolTable - - -class AdminMixin(LoginRequiredMixin): - """ - If a view extends this mixin, then the view will be only accessible to administrators. - """ - - def dispatch(self, request, *args, **kwargs): - if not request.user.is_authenticated or not request.user.admin: - raise PermissionDenied - return super().dispatch(request, *args, **kwargs) - - -class OrgaMixin(AccessMixin): - """ - If a view extends this mixin, then the view will be only accessible to administrators or organizers. - """ - - def dispatch(self, request, *args, **kwargs): - if not request.user.is_authenticated and not request.session["extra_access_token"]: - return self.handle_no_permission() - elif request.user.is_authenticated and not request.user.organizes: - raise PermissionDenied - return super().dispatch(request, *args, **kwargs) - - -class TeamMixin(LoginRequiredMixin): - """ - If a view extends this mixin, then the view will be only accessible to users that are registered in a team. - """ - - def dispatch(self, request, *args, **kwargs): - if not request.user.is_authenticated or not request.user.team: - raise PermissionDenied - return super().dispatch(request, *args, **kwargs) - - -class TournamentListView(SingleTableView): - """ - Display the list of all tournaments, ordered by start date then name. - """ - - model = Tournament - table_class = TournamentTable - extra_context = dict(title=_("Tournaments list"),) - - def get_context_data(self, **kwargs): - context = super().get_context_data(**kwargs) - - team_users = TFJMUser.objects.filter(Q(team__isnull=False) | Q(role="admin") | Q(role="organizer"))\ - .order_by('-role') - valid_team_users = team_users.filter( - Q(team__validation_status="2valid") | Q(role="admin") | Q(role="organizer")) - - context["team_users_emails"] = [user.email for user in team_users] - context["valid_team_users_emails"] = [user.email for user in valid_team_users] - - return context - - -class TournamentCreateView(AdminMixin, CreateView): - """ - Create a tournament. Only accessible to admins. - """ - - model = Tournament - form_class = TournamentForm - extra_context = dict(title=_("Add tournament"),) - - def get_success_url(self): - return reverse_lazy('tournament:detail', args=(self.object.pk,)) - - -class TournamentDetailView(DetailView): - """ - Display the detail of a tournament. - Accessible to all, including not authenticated users. - """ - - model = Tournament - - def get_context_data(self, **kwargs): - context = super().get_context_data(**kwargs) - - context["title"] = _("Tournament of {name}").format(name=self.object.name) - - if self.object.final: - team_users = TFJMUser.objects.filter(team__selected_for_final=True) - valid_team_users = team_users - else: - team_users = TFJMUser.objects.filter( - Q(team__tournament=self.object) - | Q(organized_tournaments=self.object)).order_by('role') - valid_team_users = team_users.filter( - Q(team__validation_status="2valid") - | Q(role="admin") - | Q(organized_tournaments=self.object)) - - context["team_users_emails"] = [user.email for user in team_users] - context["valid_team_users_emails"] = [user.email for user in valid_team_users] - - context["teams"] = TeamTable(self.object.teams.all()) - - return context - - -class TournamentUpdateView(OrgaMixin, UpdateView): - """ - Update the data of a tournament. - Reserved to admins and organizers of the tournament. - """ - - def dispatch(self, request, *args, **kwargs): - """ - Restrict the view to organizers of tournaments, then process the request. - """ - if self.request.user.role == "1volunteer" and self.request.user not in self.get_object().organizers.all(): - raise PermissionDenied - return super().dispatch(request, *args, **kwargs) - - model = Tournament - form_class = TournamentForm - extra_context = dict(title=_("Update tournament"),) - - def get_success_url(self): - return reverse_lazy('tournament:detail', args=(self.object.pk,)) - - -class TeamDetailView(LoginRequiredMixin, DetailView): - """ - View the detail of a team. - Restricted to this team, admins and organizers of its tournament. - """ - model = Team - - def dispatch(self, request, *args, **kwargs): - """ - Protect the page and process the request. - """ - if not request.user.is_authenticated or \ - (not request.user.admin and self.request.user not in self.get_object().tournament.organizers.all() - and not (self.get_object().selected_for_final - and request.user in Tournament.get_final().organizers.all()) - and self.get_object() != request.user.team): - raise PermissionDenied - return super().dispatch(request, *args, **kwargs) - - def post(self, request, *args, **kwargs): - """ - Process POST requests. Supported requests: - - get the solutions of the team as a ZIP archive - - a user leaves its team (if the composition is not validated yet) - - the team requests the validation - - Organizers can validate or invalidate the request - - Admins can delete teams - - Admins can select teams for the final tournament - """ - team = self.get_object() - if "zip" in request.POST: - solutions = team.solutions.all() - - out = BytesIO() - zf = zipfile.ZipFile(out, "w") - - for solution in solutions: - zf.write(solution.file.path, str(solution) + ".pdf") - - zf.close() - - resp = HttpResponse(out.getvalue(), content_type="application/x-zip-compressed") - resp['Content-Disposition'] = 'attachment; filename={}'\ - .format(_("Solutions for team {team}.zip") - .format(team=str(team)).replace(" ", "%20")) - return resp - elif "leave" in request.POST and request.user.participates: - request.user.team = None - request.user.save() - if not team.users.exists(): - team.delete() - return redirect('tournament:detail', pk=team.tournament.pk) - elif "request_validation" in request.POST and request.user.participates and team.can_validate: - team.validation_status = "1waiting" - team.save() - team.tournament.send_mail_to_organizers("request_validation", "Demande de validation TFJM²", team=team) - return redirect('tournament:team_detail', pk=team.pk) - elif "validate" in request.POST and request.user.organizes: - team.validation_status = "2valid" - team.save() - team.send_mail("validate_team", "Équipe validée TFJM²") - return redirect('tournament:team_detail', pk=team.pk) - elif "invalidate" in request.POST and request.user.organizes: - team.validation_status = "0invalid" - team.save() - team.send_mail("unvalidate_team", "Équipe non validée TFJM²") - return redirect('tournament:team_detail', pk=team.pk) - elif "delete" in request.POST and request.user.organizes: - team.delete() - return redirect('tournament:detail', pk=team.tournament.pk) - elif "select_final" in request.POST and request.user.admin and not team.selected_for_final and team.pools: - # We copy all solutions for solutions for the final - for solution in team.solutions.all(): - alphabet = "0123456789abcdefghijklmnopqrstuvwxyz0123456789" - id = "" - for i in range(64): - id += random.choice(alphabet) - with solution.file.open("rb") as source: - with open("/code/media/" + id, "wb") as dest: - for chunk in source.chunks(): - dest.write(chunk) - new_sol = Solution( - file=id, - team=team, - problem=solution.problem, - final=True, - ) - new_sol.save() - team.selected_for_final = True - team.save() - team.send_mail("select_for_final", "Sélection pour la finale, félicitations ! - TFJM²", - final=Tournament.get_final()) - return redirect('tournament:team_detail', pk=team.pk) - - return self.get(request, *args, **kwargs) - - def get_context_data(self, **kwargs): - context = super().get_context_data(**kwargs) - - context["title"] = _("Information about team") - context["ordered_solutions"] = self.object.solutions.order_by('final', 'problem',).all() - context["team_users_emails"] = [user.email for user in self.object.users.all()] - - return context - - -class TeamUpdateView(LoginRequiredMixin, UpdateView): - """ - Update the information about a team. - Team members, admins and organizers are allowed to do this. - """ - - model = Team - form_class = TeamForm - extra_context = dict(title=_("Update team"),) - - def dispatch(self, request, *args, **kwargs): - if not request.user.admin and self.request.user not in self.get_object().tournament.organizers.all() \ - and self.get_object() != self.request.user.team: - raise PermissionDenied - return super().dispatch(request, *args, **kwargs) - - -class AddOrganizerView(AdminMixin, CreateView): - """ - Add a new organizer account. No password is created, the user should reset its password using the link - sent by mail. Only name and email are requested. - Only admins are granted to do this. - """ - - model = TFJMUser - form_class = OrganizerForm - extra_context = dict(title=_("Add organizer"),) - template_name = "tournament/add_organizer.html" - - def form_valid(self, form): - user = form.instance - msg = render_to_string("mail_templates/add_organizer.txt", context=dict(user=user)) - msg_html = render_to_string("mail_templates/add_organizer.html", context=dict(user=user)) - send_mail('Organisateur du TFJM² 2020', msg, 'contact@tfjm.org', [user.email], html_message=msg_html) - return super().form_valid(form) - - def get_success_url(self): - return reverse_lazy('index') - - -class SolutionsView(TeamMixin, BaseFormView, SingleTableView): - """ - Upload and view solutions for a team. - """ - - model = Solution - table_class = SolutionTable - form_class = SolutionForm - template_name = "tournament/solutions_list.html" - extra_context = dict(title=_("Solutions")) - - def post(self, request, *args, **kwargs): - if "zip" in request.POST: - solutions = request.user.team.solutions - - out = BytesIO() - zf = zipfile.ZipFile(out, "w") - - for solution in solutions: - zf.write(solution.file.path, str(solution) + ".pdf") - - zf.close() - - resp = HttpResponse(out.getvalue(), content_type="application/x-zip-compressed") - resp['Content-Disposition'] = 'attachment; filename={}'\ - .format(_("Solutions for team {team}.zip") - .format(team=str(request.user.team)).replace(" ", "%20")) - return resp - - return super().post(request, *args, **kwargs) - - def get_context_data(self, **kwargs): - self.object_list = self.get_queryset() - context = super().get_context_data(**kwargs) - context["now"] = timezone.now() - context["real_deadline"] = self.request.user.team.future_tournament.date_solutions + timedelta(minutes=30) - return context - - def get_queryset(self): - qs = super().get_queryset().filter(team=self.request.user.team) - return qs.order_by('final', 'team__tournament__date_start', 'team__tournament__name', 'team__trigram', - 'problem',) - - def form_valid(self, form): - solution = form.instance - solution.team = self.request.user.team - solution.final = solution.team.selected_for_final - - if timezone.now() > solution.tournament.date_solutions + timedelta(minutes=30): - form.add_error('file', _("You can't publish your solution anymore. Deadline: {date:%m-%d-%Y %H:%M}.") - .format(date=timezone.localtime(solution.tournament.date_solutions))) - return super().form_invalid(form) - - prev_sol = Solution.objects.filter(problem=solution.problem, team=solution.team, final=solution.final) - for sol in prev_sol.all(): - sol.delete() - alphabet = "0123456789abcdefghijklmnopqrstuvwxyz0123456789" - id = "" - for i in range(64): - id += random.choice(alphabet) - solution.file.name = id - solution.save() - - return super().form_valid(form) - - def get_success_url(self): - return reverse_lazy("tournament:solutions") - - -class SolutionsOrgaListView(OrgaMixin, SingleTableView): - """ - View all solutions sent by teams for the organized tournaments. Juries can view solutions of their pools. - Organizers can download a ZIP archive for each organized tournament. - """ - - model = Solution - table_class = SolutionTable - template_name = "tournament/solutions_orga_list.html" - extra_context = dict(title=_("All solutions")) - - def post(self, request, *args, **kwargs): - if "tournament_zip" in request.POST: - tournament = Tournament.objects.get(pk=int(request.POST["tournament_zip"])) - solutions = tournament.solutions - if not request.user.admin and request.user not in tournament.organizers.all(): - raise PermissionDenied - - out = BytesIO() - zf = zipfile.ZipFile(out, "w") - - for solution in solutions: - zf.write(solution.file.path, str(solution) + ".pdf") - - zf.close() - - resp = HttpResponse(out.getvalue(), content_type="application/x-zip-compressed") - resp['Content-Disposition'] = 'attachment; filename={}'\ - .format(_("Solutions for tournament {tournament}.zip") - .format(tournament=str(tournament)).replace(" ", "%20")) - return resp - - return self.get(request, *args, **kwargs) - - def get_context_data(self, **kwargs): - context = super().get_context_data(**kwargs) - - if self.request.user.is_authenticated: - context["tournaments"] = \ - Tournament.objects if self.request.user.admin else self.request.user.organized_tournaments - - return context - - def get_queryset(self): - qs = super().get_queryset() - if self.request.user.is_authenticated and not self.request.user.admin: - if self.request.user in Tournament.get_final().organizers.all(): - qs = qs.filter(Q(team__tournament__organizers=self.request.user) | Q(pools__juries=self.request.user) - | Q(final=True)) - else: - qs = qs.filter(Q(team__tournament__organizers=self.request.user) | Q(pools__juries=self.request.user)) - elif not self.request.user.is_authenticated: - qs = qs.filter(pools__extra_access_token=self.request.session["extra_access_token"]) - return qs.order_by('final', 'team__tournament__date_start', 'team__tournament__name', 'team__trigram', - 'problem',).distinct() - - -class SynthesesView(TeamMixin, BaseFormView, SingleTableView): - """ - Upload and view syntheses for a team. - """ - model = Synthesis - table_class = SynthesisTable - form_class = SynthesisForm - template_name = "tournament/syntheses_list.html" - extra_context = dict(title=_("Syntheses")) - - def post(self, request, *args, **kwargs): - if "zip" in request.POST: - syntheses = request.user.team.syntheses - - out = BytesIO() - zf = zipfile.ZipFile(out, "w") - - for synthesis in syntheses: - zf.write(synthesis.file.path, str(synthesis) + ".pdf") - - zf.close() - - resp = HttpResponse(out.getvalue(), content_type="application/x-zip-compressed") - resp['Content-Disposition'] = 'attachment; filename={}'\ - .format(_("Syntheses for team {team}.zip") - .format(team=str(request.user.team)).replace(" ", "%20")) - return resp - - return super().post(request, *args, **kwargs) - - def get_queryset(self): - qs = super().get_queryset().filter(team=self.request.user.team) - return qs.order_by('final', 'team__tournament__date_start', 'team__tournament__name', 'team__trigram', - 'round', 'source',) - - def get_context_data(self, **kwargs): - self.object_list = self.get_queryset() - context = super().get_context_data(**kwargs) - context["now"] = timezone.now() - context["real_deadline_1"] = self.request.user.team.future_tournament.date_syntheses + timedelta(minutes=30) - context["real_deadline_2"] = self.request.user.team.future_tournament.date_syntheses_2 + timedelta(minutes=30) - return context - - def form_valid(self, form): - synthesis = form.instance - synthesis.team = self.request.user.team - synthesis.final = synthesis.team.selected_for_final - - if synthesis.round == '1' and timezone.now() > (synthesis.tournament.date_syntheses + timedelta(minutes=30)): - form.add_error('file', _("You can't publish your synthesis anymore for the first round." - " Deadline: {date:%m-%d-%Y %H:%M}.") - .format(date=timezone.localtime(synthesis.tournament.date_syntheses))) - return super().form_invalid(form) - - if synthesis.round == '2' and timezone.now() > synthesis.tournament.date_syntheses_2 + timedelta(minutes=30): - form.add_error('file', _("You can't publish your synthesis anymore for the second round." - " Deadline: {date:%m-%d-%Y %H:%M}.") - .format(date=timezone.localtime(synthesis.tournament.date_syntheses_2))) - return super().form_invalid(form) - - prev_syn = Synthesis.objects.filter(team=synthesis.team, round=synthesis.round, source=synthesis.source, - final=synthesis.final) - for syn in prev_syn.all(): - syn.delete() - alphabet = "0123456789abcdefghijklmnopqrstuvwxyz0123456789" - id = "" - for i in range(64): - id += random.choice(alphabet) - synthesis.file.name = id - synthesis.save() - - return super().form_valid(form) - - def get_success_url(self): - return reverse_lazy("tournament:syntheses") - - -class SynthesesOrgaListView(OrgaMixin, SingleTableView): - """ - View all syntheses sent by teams for the organized tournaments. Juries can view syntheses of their pools. - Organizers can download a ZIP archive for each organized tournament. - """ - model = Synthesis - table_class = SynthesisTable - template_name = "tournament/syntheses_orga_list.html" - extra_context = dict(title=_("All syntheses")) - - def post(self, request, *args, **kwargs): - if "tournament_zip" in request.POST: - tournament = Tournament.objects.get(pk=request.POST["tournament_zip"]) - syntheses = tournament.syntheses - if not request.user.admin and request.user not in tournament.organizers.all(): - raise PermissionDenied - - out = BytesIO() - zf = zipfile.ZipFile(out, "w") - - for synthesis in syntheses: - zf.write(synthesis.file.path, str(synthesis) + ".pdf") - - zf.close() - - resp = HttpResponse(out.getvalue(), content_type="application/x-zip-compressed") - resp['Content-Disposition'] = 'attachment; filename={}'\ - .format(_("Syntheses for tournament {tournament}.zip") - .format(tournament=str(tournament)).replace(" ", "%20")) - return resp - - return self.get(request, *args, **kwargs) - - def get_context_data(self, **kwargs): - context = super().get_context_data(**kwargs) - - if self.request.user.is_authenticated: - context["tournaments"] = \ - Tournament.objects if self.request.user.admin else self.request.user.organized_tournaments - - return context - - def get_queryset(self): - qs = super().get_queryset() - if self.request.user.is_authenticated and not self.request.user.admin: - if self.request.user in Tournament.get_final().organizers.all(): - qs = qs.filter(Q(team__tournament__organizers=self.request.user) - | Q(team__pools__juries=self.request.user) - | Q(final=True)) - else: - qs = qs.filter(Q(team__tournament__organizers=self.request.user) - | Q(team__pools__juries=self.request.user)) - elif not self.request.user.is_authenticated: - pool = Pool.objects.filter(extra_access_token=self.request.session["extra_access_token"]) - if pool.exists(): - pool = pool.get() - qs = qs.filter(team__pools=pool, final=pool.tournament.final) - else: - qs = qs.none() - return qs.order_by('final', 'team__tournament__date_start', 'team__tournament__name', 'team__trigram', - 'round', 'source',).distinct() - - -class PoolListView(SingleTableView): - """ - View the list of visible pools. - Admins see all, juries see their own pools, organizers see the pools of their tournaments. - """ - model = Pool - table_class = PoolTable - extra_context = dict(title=_("Pools")) - - def get_queryset(self): - qs = super().get_queryset() - user = self.request.user - if user.is_authenticated: - if not user.admin and user.organizes: - qs = qs.filter(Q(juries=user) | Q(teams__tournament__organizers=user)) - elif user.participates: - qs = qs.filter(teams=user.team) - else: - qs = qs.filter(extra_access_token=self.request.session["extra_access_token"]) - qs = qs.distinct().order_by('id') - return qs - - -class PoolCreateView(AdminMixin, CreateView): - """ - Create a pool manually. - This page should not be used: prefer send automatically data from the drawing bot. - """ - model = Pool - form_class = PoolForm - extra_context = dict(title=_("Create pool")) - - def get_success_url(self): - return reverse_lazy("tournament:pools") - - -class PoolDetailView(DetailView): - """ - See the detail of a pool. - Teams and juries can download here defended solutions of the pool. - If this is the second round, teams can't download solutions of the other teams before the date when they - should be available. - Juries see also syntheses. They see of course solutions immediately. - This is also true for organizers and admins. - All can be downloaded as a ZIP archive. - """ - model = Pool - extra_context = dict(title=_("Pool detail")) - - def get_queryset(self): - qs = super().get_queryset() - user = self.request.user - if user.is_authenticated: - if not user.admin and user.organizes: - qs = qs.filter(Q(juries=user) | Q(teams__tournament__organizers=user)) - elif user.participates: - qs = qs.filter(teams=user.team) - else: - qs = qs.filter(extra_access_token=self.request.session["extra_access_token"]) - return qs.distinct() - - def post(self, request, *args, **kwargs): - user = request.user - pool = self.get_object() - - if "solutions_zip" in request.POST: - if user.is_authenticated and user.participates and pool.round == 2\ - and pool.tournament.date_solutions_2 > timezone.now(): - raise PermissionDenied - - out = BytesIO() - zf = zipfile.ZipFile(out, "w") - - for solution in pool.solutions.all(): - zf.write(solution.file.path, str(solution) + ".pdf") - - zf.close() - - resp = HttpResponse(out.getvalue(), content_type="application/x-zip-compressed") - resp['Content-Disposition'] = 'attachment; filename={}' \ - .format(_("Solutions of a pool for the round {round} of the tournament {tournament}.zip") - .format(round=pool.round, tournament=str(pool.tournament)).replace(" ", "%20")) - return resp - elif "syntheses_zip" in request.POST and (not user.is_authenticated or user.organizes): - out = BytesIO() - zf = zipfile.ZipFile(out, "w") - - for synthesis in pool.syntheses.all(): - zf.write(synthesis.file.path, str(synthesis) + ".pdf") - - zf.close() - - resp = HttpResponse(out.getvalue(), content_type="application/x-zip-compressed") - resp['Content-Disposition'] = 'attachment; filename={}' \ - .format(_("Syntheses of a pool for the round {round} of the tournament {tournament}.zip") - .format(round=pool.round, tournament=str(pool.tournament)).replace(" ", "%20")) - return resp - - return self.get(request, *args, **kwargs) diff --git a/assets/Autorisation_droit_image_majeur.tex b/assets/Autorisation_droit_image_majeur.tex deleted file mode 100644 index 7cb1727..0000000 --- a/assets/Autorisation_droit_image_majeur.tex +++ /dev/null @@ -1,113 +0,0 @@ -\documentclass[a4paper,french,11pt]{article} - -\usepackage[T1]{fontenc} -\usepackage[utf8]{inputenc} -\usepackage{lmodern} -\usepackage[frenchb]{babel} - -\usepackage{fancyhdr} -\usepackage{graphicx} -\usepackage{amsmath} -\usepackage{amssymb} -%\usepackage{anyfontsize} -\usepackage{fancybox} -\usepackage{eso-pic,graphicx} -\usepackage{xcolor} - - -% Specials -\newcommand{\writingsep}{\vrule height 4ex width 0pt} - -% Page formating -\hoffset -1in -\voffset -1in -\textwidth 180 mm -\textheight 250 mm -\oddsidemargin 15mm -\evensidemargin 15mm -\pagestyle{fancy} - -% Headers and footers -\fancyfoot{} -\lhead{} -\rhead{} -\renewcommand{\headrulewidth}{0pt} -\lfoot{\footnotesize 11 rue Pierre et Marie Curie, 75231 Paris Cedex 05\\ Numéro siret 431 598 366 00018} -\rfoot{\footnotesize Association agréée par\\le Ministère de l'éducation nationale.} - -\begin{document} - -\includegraphics[height=2cm]{assets/logo_animath.png}\hfill{\fontsize{55pt}{55pt}{$\mathbb{TFJM}^2$}} - -\vfill - -\begin{center} - - -\LARGE -Autorisation d'enregistrement et de diffusion de l'image ({TOURNAMENT_NAME}) -\end{center} -\normalsize - - -\thispagestyle{empty} - -\bigskip - - - -Je soussign\'e {PARTICIPANT_NAME}\\ -demeurant au {ADDRESS} - -\medskip -Cochez la/les cases correspondantes.\\ -\medskip - - \fbox{\textcolor{white}{A}} Autorise l'association Animath, \`a l'occasion du $\mathbb{TFJM}^2$ du {START_DATE} au {END_DATE} {YEAR} à : {PLACE}, \`a me photographier ou \`a me filmer et \`a diffuser les photos et/ou les vid\'eos r\'ealis\'ees \`a cette occasion sur son site et sur les sites partenaires. D\'eclare c\'eder \`a titre gracieux \`a Animath le droit d’utiliser mon image sur tous ses supports d'information : brochures, sites web, r\'eseaux sociaux. Animath devient, par la pr\'esente, cessionnaire des droits pendant toute la dur\'ee pour laquelle ont \'et\'e acquis les droits d'auteur de ces photographies.\\ - -\medskip -Animath s'engage, conform\'ement aux dispositions l\'egales en vigueur relatives au droit \`a l'image, \`a ce que la publication et la diffusion de l'image ainsi que des commentaires l'accompagnant ne portent pas atteinte \`a la vie priv\'ee, \`a la dignit\'e et \`a la r\'eputation de la personne photographiée.\\ - -\medskip - \fbox{\textcolor{white}{A}} Autorise la diffusion dans les medias (Presse, T\'el\'evision, Internet) de photographies prises \`a l'occasion d’une \'eventuelle m\'ediatisation de cet événement.\\ - - \medskip - -Conform\'ement \`a la loi informatique et libert\'es du 6 janvier 1978, vous disposez d'un droit de libre acc\`es, de rectification, de modification et de suppression des donn\'ees qui vous concernent. -Cette autorisation est donc r\'evocable \`a tout moment sur volont\'e express\'ement manifest\'ee par lettre recommand\'ee avec accus\'e de r\'eception adress\'ee \`a Animath, IHP, 11 rue Pierre et Marie Curie, 75231 Paris cedex 05.\\ - -\medskip - \fbox{\textcolor{white}{A}} Autorise Animath à conserver mes données personnelles, dans le cadre défini par la loi n 78-17 du 6 janvier 1978 relative à l'informatique, aux fichiers et aux libertés et les textes la modifiant, pendant une durée de quatre ans à compter de ma dernière participation à un événement organisé par Animath.\\ - - \medskip - \fbox{\textcolor{white}{A}} J'accepte d'être tenu informé d'autres activités organisées par l'association et ses partenaires. - -\bigskip - -Signature pr\'ec\'ed\'ee de la mention \og lu et approuv\'e \fg{} - -\medskip - - - -\begin{minipage}[c]{0.5\textwidth} - -\underline{L'\'el\`eve :}\\ - -Fait \`a :\\ -le -\end{minipage} - - -\vfill -\vfill -\begin{minipage}[c]{0.5\textwidth} -\footnotesize 11 rue Pierre et Marie Curie, 75231 Paris Cedex 05\\ Numéro siret 431 598 366 00018 -\end{minipage} -\begin{minipage}[c]{0.5\textwidth} -\footnotesize -\begin{flushright} -Association agréée par\\le Ministère de l'éducation nationale. -\end{flushright} -\end{minipage} -\end{document} diff --git a/assets/Autorisation_parentale.tex b/assets/Autorisation_parentale.tex deleted file mode 100644 index 6c56ac4..0000000 --- a/assets/Autorisation_parentale.tex +++ /dev/null @@ -1,66 +0,0 @@ -\documentclass[a4paper,french,11pt]{article} - -\usepackage[T1]{fontenc} -\usepackage[utf8]{inputenc} -\usepackage{lmodern} -\usepackage[french]{babel} - -\usepackage{fancyhdr} -\usepackage{graphicx} -\usepackage{amsmath} -\usepackage{amssymb} -%\usepackage{anyfontsize} -\usepackage{fancybox} -\usepackage{eso-pic,graphicx} -\usepackage{xcolor} - - -% Specials -\newcommand{\writingsep}{\vrule height 4ex width 0pt} - -% Page formating -\hoffset -1in -\voffset -1in -\textwidth 180 mm -\textheight 250 mm -\oddsidemargin 15mm -\evensidemargin 15mm -\pagestyle{fancy} - -% Headers and footers -\fancyfoot{} -\lhead{} -\rhead{} -\renewcommand{\headrulewidth}{0pt} -\lfoot{\footnotesize 11 rue Pierre et Marie Curie, 75231 Paris Cedex 05\\ Numéro siret 431 598 366 00018} -\rfoot{\footnotesize Association agréée par\\le Ministère de l'éducation nationale.} - -\begin{document} - -\includegraphics[height=2cm]{assets/logo_animath.png}\hfill{\fontsize{55pt}{55pt}{$\mathbb{TFJM}^2$}} - -\vfill - -\begin{center} -\Large \bf Autorisation parentale pour les mineurs ({TOURNAMENT_NAME}) -\end{center} - -Je soussigné(e) \hrulefill,\\ -responsable légal, demeurant \writingsep\hrulefill\\ -\writingsep\hrulefill,\\ -\writingsep autorise {PARTICIPANT_NAME},\\ -né(e) le {BIRTHDAY}, -à participer au Tournoi Français des Jeunes Mathématiciennes et Mathématiciens ($\mathbb{TFJM}^2$) organisé \`a : {PLACE}, du {START_DATE} au {END_DATE} {YEAR}. - -{PRONOUN} se rendra au lieu indiqu\'e ci-dessus le vendredi matin et quittera les lieux l'après-midi du dimanche par ses propres moyens et sous la responsabilité du représentant légal. - - - -\vspace{8ex} - -Fait à \vrule width 10cm height 0pt depth 0.4pt, le \phantom{232323}/\phantom{XXX}/{YEAR}, - -\vfill -\vfill - -\end{document} diff --git a/assets/Fiche_sanitaire.pdf b/assets/Fiche_sanitaire.pdf deleted file mode 100644 index b828b9d..0000000 Binary files a/assets/Fiche_sanitaire.pdf and /dev/null differ diff --git a/assets/favicon.ico b/assets/favicon.ico deleted file mode 100644 index 97757d3..0000000 Binary files a/assets/favicon.ico and /dev/null differ diff --git a/assets/style.css b/assets/style.css deleted file mode 100644 index 5c8d3ff..0000000 --- a/assets/style.css +++ /dev/null @@ -1,47 +0,0 @@ -html, body { - height: 100%; - margin: 0; -} - -:root { - --navbar-height: 32px; -} - -.container { - min-height: 78%; -} - -.inner { - margin: 20px; -} - -.alert { - text-align: justify; -} - - -footer .alert { - text-align: center; -} - -#navbar-logo { - height: var(--navbar-height); - display: block; -} - -ul .deroule { - display: none; - position: absolute; - background: #f8f9fa !important; - list-style-type: none; - padding: 20px; - z-index: 42; -} - -li:hover ul.deroule { - display:block; -} - -a.nav-link:hover { - background-color: #d8d9da; -} diff --git a/dispatcher.php b/dispatcher.php deleted file mode 100644 index 1f4106f..0000000 --- a/dispatcher.php +++ /dev/null @@ -1,92 +0,0 @@ - $file) { - if (preg_match('#' . $route . '#', $path, $matches)) { - for ($i = 1; $i < sizeof($file); ++$i) - $_GET[$file[$i]] = $matches[$i]; - - if (!preg_match("#php$#", $file[0])) { - header("Content-Type: " . $file[1]); - readfile($file[0]); - exit(); - } - - $view = $file[0]; - /** @noinspection PhpIncludeInspection */ - require $view; - exit(); - } -} - -require_once "server_files/404.php"; diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..d4bb2cb --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..128ec7f --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,60 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- Project information ----------------------------------------------------- + +project = 'Plateforme du TFJM²' +copyright = "2020-2021" +author = "Animath" + + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx_rtd_theme", +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'fr' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['_build'] + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..215e312 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,23 @@ +Documentation de la plateforme du TFJM² +======================================= + +.. image:: https://gitlab.com/animath/si/plateforme-tfjm/badges/master/pipeline.svg + :target: https://gitlab.com/animath/si/plateforme-tfjm/-/commits/master + :alt: Pipeline status + +.. image:: https://gitlab.com/animath/si/plateforme-tfjm/badges/master/coverage.svg + :target: https://gitlab.com/animath/si/plateforme-tfjm/-/commits/master + :alt: Coverage report + +.. image:: https://img.shields.io/badge/License-GPL%20v3-blue.svg + :target: https://www.gnu.org/licenses/gpl-3.0.txt + :alt: License: GPL v3 + + +.. toctree:: + :maxdepth: 3 + :caption: Développer + +.. toctree:: + :maxdepth: 3 + :caption: Jouer diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..540deda --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,2 @@ +sphinx>=3.3 +sphinx-rtd-theme>=0.5 diff --git a/entrypoint.sh b/entrypoint.sh index 6ed74bf..f22cc81 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,13 +1,14 @@ #!/bin/sh -python manage.py compilemessages -python manage.py makemigrations +crond -l 0 + python manage.py migrate +python manage.py loaddata initial nginx if [ "$TFJM_STAGE" = "prod" ]; then gunicorn -b 0.0.0.0:8000 --workers=2 --threads=4 --worker-class=gthread tfjm.wsgi --access-logfile '-' --error-logfile '-'; else - ./manage.py runserver 0.0.0.0:8000; + python manage.py runserver 0.0.0.0:8000; fi diff --git a/index.html b/index.html deleted file mode 100644 index da8c197..0000000 --- a/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - Erreur - - - -Le mode Rewrite n'est pas activé. - - \ No newline at end of file diff --git a/locale/fr/LC_MESSAGES/django.po b/locale/fr/LC_MESSAGES/django.po index 07a9aaa..794e7f3 100644 --- a/locale/fr/LC_MESSAGES/django.po +++ b/locale/fr/LC_MESSAGES/django.po @@ -1,796 +1,1702 @@ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. -# FIRST AUTHOR yohann.danello@animath.fr, 2020. +# Yohann D'ANELLO , 2020. # -#, fuzzy msgid "" msgstr "" -"Project-Id-Version: TFJM2\n" +"Project-Id-Version: TFJM\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2020-05-25 18:23+0200\n" -"PO-Revision-Date: 2020-04-29 02:30+0000\n" +"POT-Creation-Date: 2021-01-21 22:34+0100\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: Yohann D'ANELLO \n" -"Language-Team: fr \n" +"Language-Team: LANGUAGE \n" "Language: fr\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" -#: apps/api/apps.py:10 +#: apps/api/apps.py:13 msgid "API" msgstr "API" -#: apps/member/apps.py:10 -msgid "member" -msgstr "membre" +#: apps/eastereggs/templates/eastereggs/xp_modal.html:7 +msgid "Error" +msgstr "Erreur" -#: apps/member/forms.py:18 -msgid "Choose a role..." -msgstr "Choisir un rôle ..." +#: apps/eastereggs/templates/eastereggs/xp_modal.html:13 +msgid "This task failed successfully." +msgstr "Cette tâche a échoué avec succès." -#: apps/member/forms.py:19 apps/member/models.py:138 -msgid "Participant" -msgstr "Participant" +#: apps/eastereggs/templates/eastereggs/xp_modal.html:16 +#: tfjm/templates/base_modal.html:19 +msgid "Close" +msgstr "Fermer" -#: apps/member/forms.py:20 apps/member/models.py:137 -msgid "Coach" -msgstr "Encadrant" +#: apps/logs/apps.py:11 +msgid "Logs" +msgstr "Logs" -#: apps/member/models.py:21 templates/member/tfjmuser_detail.html:35 -msgid "email" -msgstr "Adresse électronique" - -#: apps/member/models.py:22 -msgid "This should be valid and will be controlled." -msgstr "Elle doit être valide et sera contrôlée." - -#: apps/member/models.py:30 apps/member/models.py:244 apps/member/models.py:263 -#: apps/member/models.py:306 apps/tournament/models.py:286 -#: apps/tournament/models.py:400 templates/member/tfjmuser_detail.html:16 -msgid "team" -msgstr "équipe" - -#: apps/member/models.py:31 -msgid "Concerns only coaches and participants." -msgstr "Concerne uniquement les encadrants et participants." - -#: apps/member/models.py:37 templates/member/tfjmuser_detail.html:21 -msgid "birth date" -msgstr "date de naissance" - -#: apps/member/models.py:45 -msgid "Male" -msgstr "Homme" - -#: apps/member/models.py:46 -msgid "Female" -msgstr "Femme" - -#: apps/member/models.py:47 -msgid "Non binary" -msgstr "Non binaire" - -#: apps/member/models.py:49 templates/member/tfjmuser_detail.html:26 -msgid "gender" -msgstr "genre" - -#: apps/member/models.py:56 templates/member/tfjmuser_detail.html:31 -msgid "address" -msgstr "adresse" - -#: apps/member/models.py:62 -msgid "postal code" -msgstr "code postal" - -#: apps/member/models.py:69 -msgid "city" -msgstr "ville" - -#: apps/member/models.py:76 -msgid "country" -msgstr "pays" - -#: apps/member/models.py:84 templates/member/tfjmuser_detail.html:39 -msgid "phone number" -msgstr "numéro de téléphone" - -#: apps/member/models.py:91 templates/member/tfjmuser_detail.html:44 -msgid "school" -msgstr "école" - -#: apps/member/models.py:97 -msgid "Seconde or less" -msgstr "Seconde ou inférieur" - -#: apps/member/models.py:98 -msgid "Première" -msgstr "Première" - -#: apps/member/models.py:99 -msgid "Terminale" -msgstr "Terminale" - -#: apps/member/models.py:110 templates/member/tfjmuser_detail.html:51 -msgid "responsible name" -msgstr "nom du responsable" - -#: apps/member/models.py:117 templates/member/tfjmuser_detail.html:56 -msgid "responsible phone" -msgstr "téléphone du responsable" - -#: apps/member/models.py:123 templates/member/tfjmuser_detail.html:61 -msgid "responsible email" -msgstr "email du responsable" - -#: apps/member/models.py:129 apps/tournament/models.py:45 -#: templates/member/tfjmuser_detail.html:67 -#: templates/tournament/tournament_detail.html:42 -msgid "description" -msgstr "description" - -#: apps/member/models.py:135 -msgid "Admin" -msgstr "Administrateur" - -#: apps/member/models.py:136 -msgid "Organizer" -msgstr "Organisateur" - -#: apps/member/models.py:144 apps/tournament/models.py:90 -#: apps/tournament/models.py:215 -msgid "year" -msgstr "année" - -#: apps/member/models.py:171 apps/member/models.py:214 -#: apps/tournament/models.py:393 +#: apps/logs/models.py:22 apps/registration/models.py:30 msgid "user" msgstr "utilisateur" -#: apps/member/models.py:172 -msgid "users" -msgstr "utilisateurs" +#: apps/logs/models.py:28 +msgid "IP Address" +msgstr "Adresse IP" -#: apps/member/models.py:189 -msgid "file" -msgstr "fichier" +#: apps/logs/models.py:36 +msgid "model" +msgstr "modèle" -#: apps/member/models.py:194 -msgid "uploaded at" -msgstr "téléversé le" +#: apps/logs/models.py:43 +msgid "identifier" +msgstr "identifiant" -#: apps/member/models.py:198 -msgid "document" -msgstr "document" +#: apps/logs/models.py:49 +msgid "previous data" +msgstr "données précédentes" -#: apps/member/models.py:199 -msgid "documents" -msgstr "documents" +#: apps/logs/models.py:55 +msgid "new data" +msgstr "nouvelles données" -#: apps/member/models.py:220 -msgid "Parental consent" -msgstr "Autorisation parentale" +#: apps/logs/models.py:63 +msgid "create" +msgstr "créer" -#: apps/member/models.py:221 -msgid "Photo consent" -msgstr "Autorisation de droit à l'image" +#: apps/logs/models.py:64 +msgid "edit" +msgstr "modifier" -#: apps/member/models.py:222 -msgid "Sanitary plug" -msgstr "Fiche sanitaire" +#: apps/logs/models.py:65 +msgid "delete" +msgstr "supprimer" -#: apps/member/models.py:223 apps/tournament/models.py:411 -msgid "Scholarship" -msgstr "Bourse" +#: apps/logs/models.py:68 +msgid "action" +msgstr "action" -#: apps/member/models.py:225 -msgid "type" -msgstr "type" +#: apps/logs/models.py:76 +msgid "timestamp" +msgstr "date" -#: apps/member/models.py:229 -msgid "authorization" -msgstr "autorisation" +#: apps/logs/models.py:80 +msgid "Logs cannot be destroyed." +msgstr "Les logs ne peuvent pas être détruits." -#: apps/member/models.py:230 -msgid "authorizations" -msgstr "autorisations" +#: apps/logs/models.py:83 +msgid "changelog" +msgstr "changelog" -#: apps/member/models.py:233 +#: apps/logs/models.py:84 +msgid "changelogs" +msgstr "changelogs" + +#: apps/logs/models.py:87 #, python-brace-format -msgid "{authorization} for user {user}" -msgstr "{authorization} pour l'utilisateur {user}" +msgid "Changelog of type \"{action}\" for model {model} at {timestamp}" +msgstr "Changelog de type \"{action}\" pour le modèle {model} le {timestamp}" -#: apps/member/models.py:248 -msgid "motivation letter" -msgstr "lettre de motivation" +#: apps/participation/admin.py:19 apps/participation/models.py:298 +#: apps/participation/tables.py:44 apps/registration/models.py:335 +msgid "valid" +msgstr "valide" -#: apps/member/models.py:249 -msgid "motivation letters" -msgstr "lettres de motivation" +#: apps/participation/forms.py:23 apps/participation/models.py:37 +msgid "The trigram must be composed of three uppercase letters." +msgstr "Le trigramme doit être composé de trois lettres majuscules." -#: apps/member/models.py:252 -#, python-brace-format -msgid "Motivation letter of team {team} ({trigram})" -msgstr "Lettre de motivation de l'équipe {team} ({trigram})" +#: apps/participation/forms.py:38 +msgid "No team was found with this access code." +msgstr "Aucune équipe n'a été trouvée avec ce code d'accès." -#: apps/member/models.py:267 -msgid "problem" -msgstr "problème" +#: apps/participation/forms.py:72 +msgid "I engage myself to participate to the whole TFJM²." +msgstr "Je m'engage à participer à l'intégralité du TFJM²." -#: apps/member/models.py:272 -msgid "final solution" -msgstr "solution pour la finale" +#: apps/participation/forms.py:87 +msgid "Message to address to the team:" +msgstr "Message à adresser à l'équipe :" -#: apps/member/models.py:285 -msgid "solution" -msgstr "solution" +#: apps/participation/forms.py:124 +msgid "The uploaded file size must be under 5 Mo." +msgstr "Le fichier envoyé doit peser moins de 5 Mo." -#: apps/member/models.py:286 apps/tournament/models.py:325 -msgid "solutions" -msgstr "solutions" +#: apps/participation/forms.py:126 apps/participation/forms.py:189 +msgid "The uploaded file must be a PDF file." +msgstr "Le fichier envoyé doit être au format PDF." -#: apps/member/models.py:291 -#, python-brace-format -msgid "Solution of team {trigram} for problem {problem} for final" -msgstr "" -"Solution de l'équipe {trigram} pour le problème {problem} pour la finale" +#: apps/participation/forms.py:130 +msgid "The PDF file must not have more than 30 pages." +msgstr "Le fichier PDF ne doit pas avoir plus de 30 pages." -#: apps/member/models.py:294 -#, python-brace-format -msgid "Solution of team {trigram} for problem {problem}" -msgstr "Solution de l'équipe {trigram} pour le problème {problem}" +#: apps/participation/forms.py:170 +msgid "The defender, the opponent and the reporter must be different." +msgstr "Le défenseur, l'opposant et le rapporteur doivent être différents." -#: apps/member/models.py:312 -msgid "Opponent" -msgstr "Opposant" +#: apps/participation/forms.py:174 +msgid "This defender did not work on this problem." +msgstr "Ce défenseur ne travaille pas sur ce problème." -#: apps/member/models.py:313 -msgid "Rapporteur" -msgstr "Rapporteur" +#: apps/participation/forms.py:187 apps/registration/forms.py:116 +#: apps/registration/forms.py:138 apps/registration/forms.py:160 +#: apps/registration/forms.py:214 +msgid "The uploaded file size must be under 2 Mo." +msgstr "Le fichier envoyé doit peser moins de 2 Mo." -#: apps/member/models.py:315 -msgid "source" -msgstr "source" - -#: apps/member/models.py:320 apps/tournament/models.py:330 -msgid "Round 1" -msgstr "Tour 1" - -#: apps/member/models.py:321 apps/tournament/models.py:331 -msgid "Round 2" -msgstr "Tour 2" - -#: apps/member/models.py:323 apps/tournament/models.py:333 -#: templates/tournament/pool_detail.html:18 -msgid "round" -msgstr "tour" - -#: apps/member/models.py:328 -msgid "final synthesis" -msgstr "synthèse pour la finale" - -#: apps/member/models.py:341 -msgid "synthesis" -msgstr "synthèse" - -#: apps/member/models.py:342 -msgid "syntheses" -msgstr "synthèses" - -#: apps/member/models.py:346 -#, python-brace-format -msgid "" -"Synthesis of team {trigram} that is {source} for the round {round} of " -"tournament {tournament}" -msgstr "" -"Synthèse de l'équipe {trigram} qui est {source} pour le tour {round} du " -"tournoi {tournament}" - -#: apps/member/models.py:358 -msgid "key" -msgstr "clé" - -#: apps/member/models.py:363 -msgid "value" -msgstr "valeur" - -#: apps/member/models.py:367 -msgid "configuration" -msgstr "configuration" - -#: apps/member/models.py:368 -msgid "configurations" -msgstr "configurations" - -#: apps/member/views.py:105 apps/member/views.py:145 -msgid "You can't organize and participate at the same time." -msgstr "Vous ne pouvez pas organiser et participer en même temps." - -#: apps/member/views.py:109 apps/member/views.py:149 -msgid "You are already in a team." -msgstr "Vous êtes déjà dans une équipe." - -#: apps/member/views.py:153 -msgid "This team is full of coachs." -msgstr "Cette équipe est pleine en encadrants." - -#: apps/member/views.py:157 -msgid "This team is full of participants." -msgstr "Cette équipe est pleine en participants." - -#: apps/member/views.py:161 -msgid "This team is already validated or waiting for validation." -msgstr "L'équipe est déjà en attente de validation." - -#: apps/member/views.py:194 -#, python-format -msgid "No %(verbose_name)s found matching the query" -msgstr "" - -#: apps/member/views.py:244 templates/base.html:81 -msgid "All profiles" -msgstr "Tous les profils" - -#: apps/member/views.py:256 templates/base.html:80 -msgid "Orphaned profiles" -msgstr "Profils orphelins" - -#: apps/member/views.py:268 apps/tournament/forms.py:23 templates/base.html:83 -msgid "Organizers" -msgstr "Organisateurs" - -#: apps/tournament/apps.py:10 apps/tournament/models.py:135 -#: apps/tournament/models.py:183 apps/tournament/tables.py:110 -#: templates/tournament/pool_detail.html:21 -#: templates/tournament/team_detail.html:21 -msgid "tournament" -msgstr "tournoi" - -#: apps/tournament/forms.py:31 -msgid "This tournament already exists." -msgstr "Ce tournoi existe déjà." - -#: apps/tournament/forms.py:33 -msgid "The final tournament was already defined." -msgstr "Le tournoi de la finale est déjà défini." - -#: apps/tournament/forms.py:65 -msgid "This organizer already exist." -msgstr "Cet organisateur existe déjà." - -#: apps/tournament/forms.py:94 -msgid "The trigram must be composed of three upcase letters." -msgstr "Le trigramme doit être composé de trois lettres en majuscules." - -#: apps/tournament/forms.py:98 -msgid "This trigram is already used." -msgstr "Ce trigramme est déjà utilisé." - -#: apps/tournament/forms.py:101 -msgid "This name is already used." -msgstr "Ce nom est déjà utilisé." - -#: apps/tournament/forms.py:104 -msgid "This tournament is already closed." -msgstr "Ce tournoi est déjà fermé." - -#: apps/tournament/forms.py:115 -msgid "Access code" -msgstr "Code d'accès" - -#: apps/tournament/forms.py:123 -msgid "The access code must be composed of 6 alphanumeric characters." -msgstr "Le code d'accès doit être composé de 6 caractères alphanumériques." - -#: apps/tournament/forms.py:127 -msgid "This access code is invalid." -msgstr "Ce code d'accès est invalide." - -#: apps/tournament/forms.py:130 -msgid "The team is already validated." -msgstr "L'équipe est déjà validée." - -#: apps/tournament/forms.py:142 -msgid "Problem" -msgstr "Problème" - -#: apps/tournament/forms.py:143 -#, python-format -msgid "Problem #%(problem)d" -msgstr "Problème n°%(problem)d" - -#: apps/tournament/forms.py:152 apps/tournament/forms.py:176 -#, python-format -msgid "" -"Please keep filesize under %(max_size)s. Current filesize %(current_size)s" -msgstr "" -"Merci de ne pas dépasser les %(max_size)s. Le fichier envoyé pèse " -"%(current_size)s." - -#: apps/tournament/forms.py:157 apps/tournament/forms.py:181 -msgid "The file should be a PDF file." -msgstr "Ce fichier doit être au format PDF." - -#: apps/tournament/forms.py:197 apps/tournament/forms.py:210 -#: apps/tournament/forms.py:223 -msgid "Choose a team..." -msgstr "Choisir une équipe ..." - -#: apps/tournament/forms.py:198 -msgid "Team 1" -msgstr "Équipe 1" - -#: apps/tournament/forms.py:205 -msgid "Problem defended by team 1" -msgstr "Problème défendu par l'équipe 1" - -#: apps/tournament/forms.py:211 -msgid "Team 2" -msgstr "Équipe 2" - -#: apps/tournament/forms.py:218 -msgid "Problem defended by team 2" -msgstr "Problème défendu par l'équipe 2" - -#: apps/tournament/forms.py:224 -msgid "Team 3" -msgstr "Équipe 3" - -#: apps/tournament/forms.py:231 -msgid "Problem defended by team 3" -msgstr "Problème défendu par l'équipe 3" - -#: apps/tournament/models.py:19 apps/tournament/models.py:170 -#: templates/tournament/team_detail.html:12 +#: apps/participation/models.py:30 apps/participation/models.py:121 +#: apps/participation/tables.py:17 apps/participation/tables.py:34 msgid "name" msgstr "nom" -#: apps/tournament/models.py:25 templates/tournament/tournament_detail.html:12 -msgid "organizers" -msgstr "organisateurs" - -#: apps/tournament/models.py:26 -msgid "" -"List of all organizers that can see and manipulate data of the tournament " -"and the teams." -msgstr "" -"Liste des organisateurs qui peuvent manipuler les données du tournoi et des " -"équipes." - -#: apps/tournament/models.py:30 templates/tournament/tournament_detail.html:15 -msgid "size" -msgstr "taille" - -#: apps/tournament/models.py:31 -msgid "Number of teams that are allowed to join the tournament." -msgstr "Nombre d'équipes qui sont autorisées à rejoindre le tournoi." - -#: apps/tournament/models.py:36 templates/tournament/tournament_detail.html:18 -msgid "place" -msgstr "lieu" - -#: apps/tournament/models.py:40 templates/tournament/tournament_detail.html:21 -msgid "price" -msgstr "prix" - -#: apps/tournament/models.py:41 -msgid "Price asked to participants. Free with a scholarship." -msgstr "Prix demandé par participant. Gratuit pour les boursiers." - -#: apps/tournament/models.py:50 -msgid "date start" -msgstr "date de début" - -#: apps/tournament/models.py:55 -msgid "date end" -msgstr "date de fin" - -#: apps/tournament/models.py:60 templates/tournament/tournament_detail.html:27 -msgid "date of registration closing" -msgstr "date de clôture des inscriptions" - -#: apps/tournament/models.py:65 templates/tournament/tournament_detail.html:30 -msgid "date of maximal solution submission" -msgstr "date d'envoi maximal des solutions" - -#: apps/tournament/models.py:70 templates/tournament/tournament_detail.html:33 -msgid "date of maximal syntheses submission for the first round" -msgstr "date d'envoi maximal des notes de synthèses du premier tour" - -#: apps/tournament/models.py:75 templates/tournament/tournament_detail.html:36 -msgid "date when solutions of round 2 are available" -msgstr "date à partir de laquelle les solutions du tour 2 sont disponibles" - -#: apps/tournament/models.py:80 templates/tournament/tournament_detail.html:39 -msgid "date of maximal syntheses submission for the second round" -msgstr "date d'envoi maximal des notes de synthèses pour le second tour" - -#: apps/tournament/models.py:84 -msgid "final tournament" -msgstr "finale" - -#: apps/tournament/models.py:85 -msgid "It should be only one final tournament." -msgstr "Il ne doit y avoir qu'une seule finale." - -#: apps/tournament/models.py:136 -msgid "tournaments" -msgstr "tournois" - -#: apps/tournament/models.py:175 templates/tournament/team_detail.html:15 +#: apps/participation/models.py:36 apps/participation/tables.py:39 msgid "trigram" msgstr "trigramme" -#: apps/tournament/models.py:176 -msgid "" -"The trigram should be composed of 3 capitalize letters, that is a funny " -"acronym for the team." -msgstr "" -"Le trigramme doit être composé de trois lettres en majuscule, qui doit être " -"un acronyme amusant représentant l'équipe." - -#: apps/tournament/models.py:184 -msgid "The tournament where the team is registered." -msgstr "Le tournoi où l'équipe est inscrite." - -#: apps/tournament/models.py:189 -msgid "inscription date" -msgstr "date d'inscription" - -#: apps/tournament/models.py:195 apps/tournament/models.py:420 -msgid "Registration not validated" -msgstr "Inscription non validée" - -#: apps/tournament/models.py:196 apps/tournament/models.py:421 -msgid "Waiting for validation" -msgstr "En attente de validation" - -#: apps/tournament/models.py:197 apps/tournament/models.py:422 -msgid "Registration validated" -msgstr "Inscription validée" - -#: apps/tournament/models.py:199 apps/tournament/models.py:424 -#: templates/tournament/team_detail.html:32 -msgid "validation status" -msgstr "statut de validation" - -#: apps/tournament/models.py:204 -msgid "selected for final" -msgstr "sélectionnée pour la finale" - -#: apps/tournament/models.py:210 templates/tournament/team_detail.html:18 +#: apps/participation/models.py:44 msgid "access code" msgstr "code d'accès" -#: apps/tournament/models.py:287 apps/tournament/models.py:319 -#: templates/tournament/pool_detail.html:15 +#: apps/participation/models.py:45 +msgid "The access code let other people to join the team." +msgstr "Le code d'accès permet aux autres participants de rejoindre l'équipe." + +#: apps/participation/models.py:108 +#, python-brace-format +msgid "Team {name} ({trigram})" +msgstr "Équipe {name} ({trigram})" + +#: apps/participation/models.py:111 apps/participation/models.py:283 +#: apps/registration/models.py:123 +msgid "team" +msgstr "équipe" + +#: apps/participation/models.py:112 apps/participation/tables.py:84 msgid "teams" msgstr "équipes" -#: apps/tournament/models.py:339 templates/tournament/pool_detail.html:12 +#: apps/participation/models.py:126 +msgid "start" +msgstr "début" + +#: apps/participation/models.py:131 +msgid "end" +msgstr "fin" + +#: apps/participation/models.py:136 apps/participation/models.py:390 +#: apps/participation/templates/participation/tournament_detail.html:18 +msgid "place" +msgstr "lieu" + +#: apps/participation/models.py:140 +msgid "max team count" +msgstr "nombre maximal d'équipes" + +#: apps/participation/models.py:145 +#: apps/participation/templates/participation/tournament_detail.html:21 +msgid "price" +msgstr "prix" + +#: apps/participation/models.py:150 +msgid "limit date for registrations" +msgstr "date limite d'inscription" + +#: apps/participation/models.py:155 +msgid "limit date to upload solutions" +msgstr "date limite pour envoyer les solutions" + +#: apps/participation/models.py:160 +msgid "random draw for solutions" +msgstr "tirage au sort des solutions" + +#: apps/participation/models.py:165 +msgid "limit date to upload the syntheses for the first phase" +msgstr "date limite pour envoyer les notes de synthèses pour la première phase" + +#: apps/participation/models.py:170 +msgid "date when the solutions for the second round become available" +msgstr "date à laquelle les solutions pour le second tour sont accessibles" + +#: apps/participation/models.py:175 +msgid "limit date to upload the syntheses for the second phase" +msgstr "date limite d'envoi des notes de synthèse pour la seconde phase" + +#: apps/participation/models.py:180 +#: apps/participation/templates/participation/tournament_detail.html:45 +msgid "description" +msgstr "description" + +#: apps/participation/models.py:186 +#: apps/participation/templates/participation/tournament_detail.html:12 +msgid "organizers" +msgstr "organisateurs" + +#: apps/participation/models.py:191 +msgid "final" +msgstr "finale" + +#: apps/participation/models.py:268 apps/participation/models.py:292 +#: apps/participation/models.py:324 +msgid "tournament" +msgstr "tournoi" + +#: apps/participation/models.py:269 +msgid "tournaments" +msgstr "tournois" + +#: apps/participation/models.py:299 +msgid "The participation got the validation of the organizers." +msgstr "La participation a été validée par les organisateurs." + +#: apps/participation/models.py:304 +msgid "selected for final" +msgstr "sélectionnée pour la finale" + +#: apps/participation/models.py:305 +msgid "The team is selected for the final tournament." +msgstr "L'équipe est sélectionnée pour la finale." + +#: apps/participation/models.py:312 +#, python-brace-format +msgid "Participation of the team {name} ({trigram})" +msgstr "Participation de l'équipe {name} ({trigram})" + +#: apps/participation/models.py:315 apps/participation/models.py:512 +#: apps/participation/models.py:550 +msgid "participation" +msgstr "participation" + +#: apps/participation/models.py:316 apps/participation/models.py:338 +msgid "participations" +msgstr "participations" + +#: apps/participation/models.py:328 +msgid "round" +msgstr "tour" + +#: apps/participation/models.py:330 apps/participation/models.py:331 +#, python-brace-format +msgid "Round {round}" +msgstr "Tour {round}" + +#: apps/participation/models.py:344 msgid "juries" msgstr "jurys" -#: apps/tournament/models.py:345 -msgid "extra access token" -msgstr "code d'accès spécial" +#: apps/participation/models.py:351 +msgid "BigBlueButton code" +msgstr "Code BigBlueButton" -#: apps/tournament/models.py:346 -msgid "Let other users access to the pool data without logging in." -msgstr "Permet à d'autres utilisateurs d'accéder au contenu de la poule sans connexion." +#: apps/participation/models.py:352 +msgid "The code of the form xxx-xxx-xxx at the end of the BBB link." +msgstr "Le code de la forme xxx-xxx-xxx à la fin du lien BBB." -#: apps/tournament/models.py:380 +#: apps/participation/models.py:371 +#, python-brace-format +msgid "Pool {round} for tournament {tournament} with teams {teams}" +msgstr "Poule {round} du tournoi {tournament} avec les équipes {teams}" + +#: apps/participation/models.py:377 apps/participation/models.py:385 msgid "pool" msgstr "poule" -#: apps/tournament/models.py:381 +#: apps/participation/models.py:378 msgid "pools" msgstr "poules" -#: apps/tournament/models.py:406 -msgid "Not paid" -msgstr "Non payé" +#: apps/participation/models.py:392 +msgid "Where the solution is presented?" +msgstr "Où est-ce que les solutions sont défendues ?" -#: apps/tournament/models.py:407 -msgid "Credit card" -msgstr "Carte bancaire" +#: apps/participation/models.py:397 +msgid "defended solution" +msgstr "solution défendue" -#: apps/tournament/models.py:408 -msgid "Bank check" -msgstr "Chèque bancaire" - -#: apps/tournament/models.py:409 -msgid "Bank transfer" -msgstr "Virement bancaire" - -#: apps/tournament/models.py:410 -msgid "Cash" -msgstr "Espèces" - -#: apps/tournament/models.py:414 -msgid "payment method" -msgstr "moyen de paiement" - -#: apps/tournament/models.py:428 -msgid "payment" -msgstr "paiement" - -#: apps/tournament/models.py:429 -msgid "payments" -msgstr "paiements" - -#: apps/tournament/models.py:432 +#: apps/participation/models.py:399 apps/participation/models.py:519 #, python-brace-format -msgid "Payment of {user}" -msgstr "Paiement de {user}" +msgid "Problem #{problem}" +msgstr "Problème n°{problem}" -#: apps/tournament/tables.py:22 templates/tournament/tournament_detail.html:24 -msgid "dates" -msgstr "dates" +#: apps/participation/models.py:406 apps/participation/tables.py:105 +msgid "defender" +msgstr "défenseur" -#: apps/tournament/tables.py:26 -msgid "From {start:%b %d %Y} to {end:%b %d %Y}" -msgstr "Du {start: %d %b %Y} au {end:%d %b %Y}" +#: apps/participation/models.py:413 apps/participation/models.py:562 +msgid "opponent" +msgstr "opposant" -#: apps/tournament/tables.py:71 apps/tournament/tables.py:147 -msgid "Tournament" -msgstr "Tournoi" +#: apps/participation/models.py:420 apps/participation/models.py:563 +msgid "reporter" +msgstr "rapporteur" -#: apps/tournament/tables.py:85 apps/tournament/tables.py:124 -#: templates/tournament/team_detail.html:135 -#: templates/tournament/team_detail.html:144 -msgid "Download" -msgstr "Télécharger" - -#: apps/tournament/tables.py:140 -msgid "Problems" -msgstr "Problèmes" - -#: apps/tournament/views.py:68 -msgid "Tournaments list" -msgstr "Liste des tournois" - -#: apps/tournament/views.py:91 -msgid "Add tournament" -msgstr "Ajouter un tournoi" - -#: apps/tournament/views.py:108 +#: apps/participation/models.py:480 apps/participation/models.py:483 +#: apps/participation/models.py:486 #, python-brace-format -msgid "Tournament of {name}" -msgstr "Tournoi de {name}" +msgid "Team {trigram} is not registered in the pool." +msgstr "L'équipe {trigram} n'est pas inscrite dans la poule." -#: apps/tournament/views.py:146 -msgid "Update tournament" -msgstr "Modifier le tournoi" - -#: apps/tournament/views.py:195 apps/tournament/views.py:323 +#: apps/participation/models.py:491 #, python-brace-format -msgid "Solutions for team {team}.zip" -msgstr "Solutions pour l'équipe {team}.zip" +msgid "Passage of {defender} for problem {problem}" +msgstr "Passage de {defender} pour le problème {problem}" -#: apps/tournament/views.py:251 -msgid "Information about team" -msgstr "Informations sur l'équipe" +#: apps/participation/models.py:495 apps/participation/models.py:557 +#: apps/participation/models.py:595 +msgid "passage" +msgstr "passage" -#: apps/tournament/views.py:266 +#: apps/participation/models.py:496 +msgid "passages" +msgstr "passages" + +#: apps/participation/models.py:517 +msgid "problem" +msgstr "numéro de problème" + +#: apps/participation/models.py:524 +msgid "solution for the final tournament" +msgstr "solution pour la finale" + +#: apps/participation/models.py:529 apps/participation/models.py:568 +msgid "file" +msgstr "fichier" + +#: apps/participation/models.py:537 +#, python-brace-format +msgid "Solution of team {team} for problem {problem}" +msgstr "Solution de l'équipe {team} pour le problème {problem}" + +#: apps/participation/models.py:541 +msgid "solution" +msgstr "solution" + +#: apps/participation/models.py:542 +msgid "solutions" +msgstr "solutions" + +#: apps/participation/models.py:576 +#, python-brace-format +msgid "Synthesis for the {type} of the {passage}" +msgstr "Synthèse pour {type} du {passage}" + +#: apps/participation/models.py:579 +msgid "synthesis" +msgstr "note de synthèse" + +#: apps/participation/models.py:580 +msgid "syntheses" +msgstr "notes de synthèse" + +#: apps/participation/models.py:588 +msgid "jury" +msgstr "jury" + +#: apps/participation/models.py:600 +msgid "defender writing note" +msgstr "note d'écrit du défenseur" + +#: apps/participation/models.py:606 +msgid "defender oral note" +msgstr "note d'oral du défenseur" + +#: apps/participation/models.py:612 +msgid "opponent writing note" +msgstr "note d'écrit de l'opposant" + +#: apps/participation/models.py:618 +msgid "opponent oral note" +msgstr "note d'oral de l'opposant" + +#: apps/participation/models.py:624 +msgid "reporter writing note" +msgstr "not d'écrit du rapporteur" + +#: apps/participation/models.py:630 +msgid "reporter oral note" +msgstr "note d'oral du rapporteur" + +#: apps/participation/models.py:639 +#, python-brace-format +msgid "Notes of {jury} for {passage}" +msgstr "Notes de {jury} pour le {passage}" + +#: apps/participation/models.py:646 +msgid "note" +msgstr "note" + +#: apps/participation/models.py:647 +msgid "notes" +msgstr "notes" + +#: apps/participation/tables.py:50 +msgid "Validated" +msgstr "Validée" + +#: apps/participation/tables.py:50 +msgid "Validation pending" +msgstr "Validation en attente" + +#: apps/participation/tables.py:50 +msgid "Not validated" +msgstr "Non validée" + +#: apps/participation/tables.py:64 +msgid "date" +msgstr "date" + +#: apps/participation/tables.py:67 +#, python-brace-format +msgid "From {start} to {end}" +msgstr "Du {start} au {end}" + +#: apps/participation/tables.py:90 +msgid "No defined team" +msgstr "Pas d'équipe définie" + +#: apps/participation/templates/participation/chat.html:7 +msgid "The chat is located on the dedicated Matrix server:" +msgstr "Le chat est situé sur le serveur Matrix dédié au TFJM² :" + +#: apps/participation/templates/participation/chat.html:14 +msgid "Access to the Matrix server" +msgstr "Accéder au serveur Matrix" + +#: apps/participation/templates/participation/chat.html:20 +msgid "" +"To connect to the server, you can select \"Log in\", then use your " +"credentials of this platform to connect with the central authentication " +"server, then you must trust the connection between the Matrix account and " +"the platform. Finally, you will be able to access to the chat platform." +msgstr "" +"Pour se connecter au serveur, vous pouvez sélectionner \"Se connecter\", " +"puis utiliser vos identifiants de cette plateforme via l'authentication " +"centralisée. Vous devrez ensuite approuver la connexion entre le compte " +"Matrix et la plateforme. Enfin, vous pourrez accéder à la plateforme de chat." + +#: apps/participation/templates/participation/chat.html:28 +msgid "" +"You will be invited in some basic rooms. You must confirm the invitations to " +"join channels." +msgstr "" +"Vous serez invités dans quelques salons basiques. Vous devez confirmer les " +"invitations pour rejoindre les canaux." + +#: apps/participation/templates/participation/chat.html:34 +msgid "If you have any trouble, don't hesitate to contact us :)" +msgstr "" +"Si vous rencontrez le moindre problème, n'hésitez surtout pas à nous " +"contacter :)" + +#: apps/participation/templates/participation/create_team.html:11 +#: apps/participation/templates/participation/tournament_form.html:14 +#: tfjm/templates/base.html:234 +msgid "Create" +msgstr "Créer" + +#: apps/participation/templates/participation/join_team.html:11 +#: tfjm/templates/base.html:229 +msgid "Join" +msgstr "Rejoindre" + +#: apps/participation/templates/participation/note_form.html:11 +#: apps/participation/templates/participation/passage_detail.html:44 +#: apps/participation/templates/participation/passage_detail.html:100 +#: apps/participation/templates/participation/passage_detail.html:105 +#: apps/participation/templates/participation/pool_detail.html:55 +#: apps/participation/templates/participation/pool_detail.html:73 +#: apps/participation/templates/participation/pool_detail.html:78 +#: apps/participation/templates/participation/team_detail.html:91 +#: apps/participation/templates/participation/team_detail.html:150 +#: apps/participation/templates/participation/tournament_form.html:12 +#: apps/participation/templates/participation/update_team.html:12 +#: apps/registration/templates/registration/payment_form.html:49 +#: apps/registration/templates/registration/update_user.html:16 +#: apps/registration/templates/registration/user_detail.html:147 +#: apps/registration/templates/registration/user_detail.html:156 +#: apps/registration/templates/registration/user_detail.html:184 +msgid "Update" +msgstr "Modifier" + +#: apps/participation/templates/participation/participation_detail.html:6 +#: apps/participation/templates/participation/participation_detail.html:21 +#: apps/participation/templates/participation/passage_detail.html:6 +#: apps/participation/templates/participation/team_detail.html:30 +#: apps/participation/templates/participation/team_detail.html:39 +#: apps/participation/templates/participation/team_detail.html:48 +#: apps/registration/templates/registration/user_detail.html:6 +#: apps/registration/templates/registration/user_detail.html:35 +msgid "any" +msgstr "aucun·e" + +#: apps/participation/templates/participation/participation_detail.html:9 +msgid "Participation of team" +msgstr "Participation de l'équipe" + +#: apps/participation/templates/participation/participation_detail.html:13 +#: apps/registration/templates/registration/user_detail.html:34 +msgid "Team:" +msgstr "Équipe :" + +#: apps/participation/templates/participation/participation_detail.html:16 +#: apps/participation/templates/participation/pool_detail.html:12 +#: apps/participation/templates/participation/team_detail.html:43 +msgid "Tournament:" +msgstr "Tournoi :" + +#: apps/participation/templates/participation/participation_detail.html:25 +msgid "Solutions:" +msgstr "Solutions :" + +#: apps/participation/templates/participation/participation_detail.html:30 +msgid "No solution was uploaded yet." +msgstr "Aucune solution n'a encore été envoyée." + +#: apps/participation/templates/participation/participation_detail.html:35 +msgid "Pools:" +msgstr "Poules :" + +#: apps/participation/templates/participation/participation_detail.html:45 +#: apps/participation/templates/participation/participation_detail.html:49 +msgid "Upload solution" +msgstr "Envoyer une solution" + +#: apps/participation/templates/participation/participation_detail.html:50 +#: apps/participation/templates/participation/passage_detail.html:110 +#: apps/participation/templates/participation/upload_solution.html:11 +#: apps/participation/templates/participation/upload_synthesis.html:11 +#: apps/registration/templates/registration/upload_health_sheet.html:17 +#: apps/registration/templates/registration/upload_parental_authorization.html:17 +#: apps/registration/templates/registration/upload_photo_authorization.html:18 +#: apps/registration/templates/registration/user_detail.html:162 +#: apps/registration/templates/registration/user_detail.html:167 +#: apps/registration/templates/registration/user_detail.html:172 +#: apps/registration/templates/registration/user_detail.html:177 +msgid "Upload" +msgstr "Téléverser" + +#: apps/participation/templates/participation/passage_detail.html:13 +msgid "Pool:" +msgstr "Poule :" + +#: apps/participation/templates/participation/passage_detail.html:16 +msgid "Defender:" +msgstr "Défenseur :" + +#: apps/participation/templates/participation/passage_detail.html:19 +msgid "Opponent:" +msgstr "Opposant :" + +#: apps/participation/templates/participation/passage_detail.html:22 +msgid "Reporter:" +msgstr "Rapporteur :" + +#: apps/participation/templates/participation/passage_detail.html:25 +msgid "Defended solution:" +msgstr "Solution défendue" + +#: apps/participation/templates/participation/passage_detail.html:28 +msgid "Place:" +msgstr "Lieu :" + +#: apps/participation/templates/participation/passage_detail.html:31 +msgid "Syntheses:" +msgstr "Notes de synthèse :" + +#: apps/participation/templates/participation/passage_detail.html:36 +msgid "No synthesis was uploaded yet." +msgstr "Aucune note de synthèse n'a encore été envoyée." + +#: apps/participation/templates/participation/passage_detail.html:43 +#: apps/participation/templates/participation/passage_detail.html:104 +msgid "Update notes" +msgstr "Modifier les notes" + +#: apps/participation/templates/participation/passage_detail.html:48 +#: apps/participation/templates/participation/passage_detail.html:109 +msgid "Upload synthesis" +msgstr "Envoyer une note de synthèse" + +#: apps/participation/templates/participation/passage_detail.html:56 +msgid "Notes detail" +msgstr "Détails des notes" + +#: apps/participation/templates/participation/passage_detail.html:63 +msgid "Average points for the defender writing:" +msgstr "Moyenne de l'écrit du défenseur :" + +#: apps/participation/templates/participation/passage_detail.html:66 +msgid "Average points for the defender oral:" +msgstr "Moyenne de l'oral du défenseur :" + +#: apps/participation/templates/participation/passage_detail.html:69 +msgid "Average points for the opponent writing:" +msgstr "Moyenne de l'écrit de l'opposant :" + +#: apps/participation/templates/participation/passage_detail.html:72 +msgid "Average points for the opponent oral:" +msgstr "Moyenne de l'oral de l'opposant :" + +#: apps/participation/templates/participation/passage_detail.html:75 +msgid "Average points for the reporter writing:" +msgstr "Moyenne de l'écrit du rapporteur :" + +#: apps/participation/templates/participation/passage_detail.html:78 +msgid "Average points for the reporter oral:" +msgstr "Moyenne de l'oral du rapporteur :" + +#: apps/participation/templates/participation/passage_detail.html:85 +msgid "Defender points:" +msgstr "Points du défenseur :" + +#: apps/participation/templates/participation/passage_detail.html:88 +msgid "Opponent points:" +msgstr "Points de l'opposant :" + +#: apps/participation/templates/participation/passage_detail.html:91 +msgid "Reporter points:" +msgstr "Points du rapporteur :" + +#: apps/participation/templates/participation/passage_detail.html:99 +#: apps/participation/templates/participation/passage_form.html:11 +msgid "Update passage" +msgstr "Modifier le passage" + +#: apps/participation/templates/participation/pool_detail.html:15 +msgid "Round:" +msgstr "Tour :" + +#: apps/participation/templates/participation/pool_detail.html:18 +msgid "Teams:" +msgstr "Équipes :" + +#: apps/participation/templates/participation/pool_detail.html:25 +msgid "Juries:" +msgstr "Jurys :" + +#: apps/participation/templates/participation/pool_detail.html:28 +msgid "Defended solutions:" +msgstr "Solutions défendues :" + +#: apps/participation/templates/participation/pool_detail.html:35 +msgid "BigBlueButton link:" +msgstr "Lien BigBlueButton :" + +#: apps/participation/templates/participation/pool_detail.html:41 +#: apps/participation/templates/participation/tournament_detail.html:91 +msgid "Ranking" +msgstr "Classement" + +#: apps/participation/templates/participation/pool_detail.html:54 +#: apps/participation/templates/participation/pool_detail.html:67 +msgid "Add passage" +msgstr "Ajouter un passage" + +#: apps/participation/templates/participation/pool_detail.html:56 +#: apps/participation/templates/participation/pool_detail.html:77 +msgid "Update teams" +msgstr "Modifier les équipes" + +#: apps/participation/templates/participation/pool_detail.html:63 +msgid "Passages" +msgstr "Passages" + +#: apps/participation/templates/participation/pool_detail.html:68 +#: apps/participation/templates/participation/tournament_detail.html:105 +msgid "Add" +msgstr "Ajouter" + +#: apps/participation/templates/participation/pool_detail.html:72 +#: apps/participation/templates/participation/pool_form.html:11 +msgid "Update pool" +msgstr "Modifier la poule" + +#: apps/participation/templates/participation/team_detail.html:13 +msgid "Name:" +msgstr "Nom :" + +#: apps/participation/templates/participation/team_detail.html:16 +msgid "Trigram:" +msgstr "Trigramme :" + +#: apps/participation/templates/participation/team_detail.html:19 +#: apps/registration/templates/registration/user_detail.html:20 +msgid "Email:" +msgstr "Adresse e-mail :" + +#: apps/participation/templates/participation/team_detail.html:22 +msgid "Access code:" +msgstr "Code d'accès :" + +#: apps/participation/templates/participation/team_detail.html:25 +msgid "Coaches:" +msgstr "Encadrants :" + +#: apps/participation/templates/participation/team_detail.html:34 +msgid "Participants:" +msgstr "Participants :" + +#: apps/participation/templates/participation/team_detail.html:52 +msgid "Photo authorizations:" +msgstr "Autorisations de droit à l'image :" + +#: apps/participation/templates/participation/team_detail.html:58 +#: apps/participation/templates/participation/team_detail.html:70 +#: apps/participation/templates/participation/team_detail.html:83 +msgid "Not uploaded yet" +msgstr "Pas encore envoyée" + +#: apps/participation/templates/participation/team_detail.html:63 +msgid "Health sheets:" +msgstr "Fiches sanitaires :" + +#: apps/participation/templates/participation/team_detail.html:76 +msgid "Parental authorizations:" +msgstr "Autorisations parentales :" + +#: apps/participation/templates/participation/team_detail.html:93 +#: apps/participation/templates/participation/team_detail.html:155 +#: apps/participation/templates/participation/team_leave.html:11 +msgid "Leave" +msgstr "Quitter" + +#: apps/participation/templates/participation/team_detail.html:103 +msgid "Access to team participation" +msgstr "Accéder à la participation de l'équipe" + +#: apps/participation/templates/participation/team_detail.html:110 +msgid "" +"Your team has at least 4 members and a coach and all authorizations were " +"given: the team can be validated." +msgstr "" +"Votre équipe contient au moins 4 personnes et un encadrant et toutes les " +"autorisations ont été données : l'équipe peut être validée." + +#: apps/participation/templates/participation/team_detail.html:115 +msgid "Submit my team to validation" +msgstr "Soumettre mon équipe à validation" + +#: apps/participation/templates/participation/team_detail.html:121 +msgid "" +"Your team must be composed of 4 members and a coach and each member must " +"upload their authorizations and confirm its email address." +msgstr "" +"Votre équipe doit être composée de 4 membres et un encadrant et chaque " +"membre doit envoyer ses autorisations et confirmé son adresse e-mail." + +#: apps/participation/templates/participation/team_detail.html:126 +msgid "This team didn't ask for validation yet." +msgstr "L'équipe n'a pas encore demandé à être validée." + +#: apps/participation/templates/participation/team_detail.html:132 +msgid "Your validation is pending." +msgstr "Votre validation est en attente." + +#: apps/participation/templates/participation/team_detail.html:136 +msgid "" +"The team requested to be validated. You may now control the authorizations " +"and confirm that they can participate." +msgstr "" +"L'équipe a demandé à être validée. Vous pouvez désormais contrôler les " +"différentes autorisations et confirmer qu'elle peut participer." + +#: apps/participation/templates/participation/team_detail.html:142 +msgid "Validate" +msgstr "Valider" + +#: apps/participation/templates/participation/team_detail.html:143 +msgid "Invalidate" +msgstr "Invalider" + +#: apps/participation/templates/participation/team_detail.html:149 msgid "Update team" msgstr "Modifier l'équipe" -#: apps/tournament/views.py:284 -msgid "Add organizer" -msgstr "Ajouter un organisateur" +#: apps/participation/templates/participation/team_detail.html:154 +#: apps/participation/views.py:360 +msgid "Leave team" +msgstr "Quitter l'équipe" -#: apps/tournament/views.py:307 templates/base.html:108 templates/base.html:118 -#: templates/base.html:132 templates/tournament/pool_detail.html:31 -msgid "Solutions" -msgstr "Solutions" +#: apps/participation/templates/participation/team_leave.html:9 +msgid "Are you sure that you want to leave this team?" +msgstr "Êtes-vous sûr·e de vouloir quitter cette équipe ?" -#: apps/tournament/views.py:347 -msgid "" -"You can't publish your solution anymore. Deadline: {date:%m-%d-%Y %H:%M}." +#: apps/participation/templates/participation/team_list.html:6 +#: tfjm/templates/base.html:222 +msgid "All teams" +msgstr "Toutes les équipes" + +#: apps/participation/templates/participation/tournament_detail.html:15 +msgid "size" +msgstr "taille" + +#: apps/participation/templates/participation/tournament_detail.html:22 +msgid "Free" +msgstr "Gratuit" + +#: apps/participation/templates/participation/tournament_detail.html:24 +msgid "dates" +msgstr "dates" + +#: apps/participation/templates/participation/tournament_detail.html:25 +msgid "From" +msgstr "Du" + +#: apps/participation/templates/participation/tournament_detail.html:25 +msgid "to" +msgstr "au" + +#: apps/participation/templates/participation/tournament_detail.html:27 +msgid "date of registration closing" +msgstr "date de clôture des inscriptions" + +#: apps/participation/templates/participation/tournament_detail.html:30 +msgid "date of maximal solution submission" +msgstr "date limite d'envoi des solutions" + +#: apps/participation/templates/participation/tournament_detail.html:33 +msgid "date of the random draw" +msgstr "date du tirage au sort" + +#: apps/participation/templates/participation/tournament_detail.html:36 +msgid "date of maximal syntheses submission for the first round" +msgstr "date limite de soumission des notes de synthèse pour le premier tour" + +#: apps/participation/templates/participation/tournament_detail.html:39 +msgid "date when solutions of round 2 are available" msgstr "" -"Vous ne pouvez plus publier vos solutions. Deadline : {date:%d/%m/%Y %H:%M}." +"date à partir de laquelle les solutions pour le second tour sont disponibles" -#: apps/tournament/views.py:376 -msgid "All solutions" -msgstr "Toutes les solutions" +#: apps/participation/templates/participation/tournament_detail.html:42 +msgid "date of maximal syntheses submission for the second round" +msgstr "date limite de soumission des notes de synthèse pour le second tour" -#: apps/tournament/views.py:395 -#, python-brace-format -msgid "Solutions for tournament {tournament}.zip" -msgstr "Solutions pour le tournoi {tournament}.zip" +#: apps/participation/templates/participation/tournament_detail.html:48 +msgid "To contact organizers" +msgstr "Pour contacter les organisateurs" -#: apps/tournament/views.py:432 templates/base.html:111 templates/base.html:121 -#: templates/base.html:135 templates/tournament/pool_detail.html:57 -msgid "Syntheses" -msgstr "Synthèses" +#: apps/participation/templates/participation/tournament_detail.html:51 +msgid "To contact juries" +msgstr "Pour contacter les jurys" -#: apps/tournament/views.py:448 -#, python-brace-format -msgid "Syntheses for team {team}.zip" -msgstr "Notes de synthèse de l'équipe {team}.zip" +#: apps/participation/templates/participation/tournament_detail.html:54 +msgid "To contact valid teams" +msgstr "Pour contacter les équipes valides" -#: apps/tournament/views.py:473 -msgid "" -"You can't publish your synthesis anymore for the first round. Deadline: " -"{date:%m-%d-%Y %H:%M}." -msgstr "" -"Vous ne pouvez plus envoyer vos notes de synthèse pour le premier tour. " -"Deadline : {date:%d/%m/%Y %h:%M}." +#: apps/participation/templates/participation/tournament_detail.html:61 +msgid "Edit tournament" +msgstr "Modifier le tournoi" -#: apps/tournament/views.py:479 -msgid "" -"You can't publish your synthesis anymore for the second round. Deadline: " -"{date:%m-%d-%Y %H:%M}." -msgstr "" -"Vous ne pouvez plus envoyer vos notes de synthèse pour le second tour. " -"Deadline : {date:%d/%m/%Y %h:%M}." +#: apps/participation/templates/participation/tournament_detail.html:68 +#: tfjm/templates/base.html:68 +msgid "Teams" +msgstr "Équipes" -#: apps/tournament/views.py:509 -msgid "All syntheses" -msgstr "Toutes les notes de synthèses" - -#: apps/tournament/views.py:528 -#, python-brace-format -msgid "Syntheses for tournament {tournament}.zip" -msgstr "Notes de synthèse pour le tournoi {tournament}.zip" - -#: apps/tournament/views.py:571 templates/base.html:125 templates/base.html:138 +#: apps/participation/templates/participation/tournament_detail.html:76 msgid "Pools" msgstr "Poules" -#: apps/tournament/views.py:594 -msgid "Create pool" -msgstr "Créer une poule" +#: apps/participation/templates/participation/tournament_detail.html:83 +msgid "Add new pool" +msgstr "Ajouter une nouvelle poule" -#: apps/tournament/views.py:611 -msgid "Pool detail" -msgstr "Détails d'une poule" +#: apps/participation/templates/participation/tournament_detail.html:104 +msgid "Add pool" +msgstr "Ajouter une poule" -#: apps/tournament/views.py:644 +#: apps/participation/templates/participation/tournament_list.html:6 +#: tfjm/templates/base.html:218 +msgid "All tournaments" +msgstr "Tous les tournois" + +#: apps/participation/templates/participation/tournament_list.html:13 +msgid "Add tournament" +msgstr "Ajouter un tournoi" + +#: apps/participation/views.py:40 tfjm/templates/base.html:74 +#: tfjm/templates/base.html:233 +msgid "Create team" +msgstr "Créer une équipe" + +#: apps/participation/views.py:49 apps/participation/views.py:94 +msgid "You don't participate, so you can't create a team." +msgstr "Vous ne participez pas, vous ne pouvez pas créer d'équipe." + +#: apps/participation/views.py:51 apps/participation/views.py:96 +msgid "You are already in a team." +msgstr "Vous êtes déjà dans une équipe." + +#: apps/participation/views.py:85 tfjm/templates/base.html:79 +#: tfjm/templates/base.html:228 +msgid "Join team" +msgstr "Rejoindre une équipe" + +#: apps/participation/views.py:147 apps/participation/views.py:366 +#: apps/participation/views.py:399 +msgid "You are not in a team." +msgstr "Vous n'êtes pas dans une équipe." + +#: apps/participation/views.py:148 apps/participation/views.py:400 +msgid "You don't participate, so you don't have any team." +msgstr "Vous ne participez pas, vous n'avez donc pas d'équipe." + +#: apps/participation/views.py:172 #, python-brace-format -msgid "" -"Solutions of a pool for the round {round} of the tournament {tournament}.zip" -msgstr "Solutions d'une poule du tour {round} du tournoi {tournament}.zip" +msgid "Detail of team {trigram}" +msgstr "Détails de l'équipe {trigram}" -#: apps/tournament/views.py:658 +#: apps/participation/views.py:205 +msgid "You don't participate, so you can't request the validation of the team." +msgstr "" +"Vous ne participez pas, vous ne pouvez pas demander la validation de " +"l'équipe." + +#: apps/participation/views.py:208 +msgid "The validation of the team is already done or pending." +msgstr "La validation de l'équipe est déjà faite ou en cours." + +#: apps/participation/views.py:211 +msgid "" +"The team can't be validated: missing email address confirmations, " +"authorizations, people or the chosen problem is not set." +msgstr "" +"L'équipe ne peut pas être validée : il manque soit les confirmations " +"d'adresse e-mail, soit une autorisation, soit des personnes soit le problème " +"n'a pas été choisi." + +#: apps/participation/views.py:230 +msgid "You are not an administrator." +msgstr "Vous n'êtes pas administrateur." + +#: apps/participation/views.py:233 +msgid "This team has no pending validation." +msgstr "L'équipe n'a pas de validation en attente." + +#: apps/participation/views.py:263 +msgid "You must specify if you validate the registration or not." +msgstr "Vous devez spécifier si vous validez l'inscription ou non." + +#: apps/participation/views.py:294 #, python-brace-format -msgid "" -"Syntheses of a pool for the round {round} of the tournament {tournament}.zip" -msgstr "Synthèse d'une poule du tour {round} du tournoi {tournament}.zip" +msgid "Update team {trigram}" +msgstr "Mise à jour de l'équipe {trigram}" -#: templates/400.html:6 +#: apps/participation/views.py:333 +#, python-brace-format +msgid "Photo authorization of {participant}.{ext}" +msgstr "Autorisation de droit à l'image de {participant}.{ext}" + +#: apps/participation/views.py:339 +#, python-brace-format +msgid "Parental authorization of {participant}.{ext}" +msgstr "Autorisation parentale de {participant}.{ext}" + +#: apps/participation/views.py:346 +#, python-brace-format +msgid "Health sheet of {participant}.{ext}" +msgstr "Fiche sanitaire de {participant}.{ext}" + +#: apps/participation/views.py:350 +#, python-brace-format +msgid "Photo authorizations of team {trigram}.zip" +msgstr "Autorisations de droit à l'image de l'équipe {trigram}.zip" + +#: apps/participation/views.py:368 +msgid "The team is already validated or the validation is pending." +msgstr "La validation de l'équipe est déjà faite ou en cours." + +#: apps/participation/views.py:414 +msgid "The team is not validated yet." +msgstr "L'équipe n'est pas encore validée." + +#: apps/participation/views.py:426 +#, python-brace-format +msgid "Participation of team {trigram}" +msgstr "Participation de l'équipe {trigram}" + +#: apps/participation/views.py:515 +msgid "You can't upload a solution after the deadline." +msgstr "Vous ne pouvez pas envoyer de solution après la date limite." + +#: apps/participation/views.py:695 +msgid "You can't upload a synthesis after the deadline." +msgstr "Vous ne pouvez pas envoyer de note de synthèse après la date limite." + +#: apps/registration/forms.py:21 apps/registration/forms.py:53 +msgid "role" +msgstr "rôle" + +#: apps/registration/forms.py:23 +msgid "participant" +msgstr "participant" + +#: apps/registration/forms.py:24 apps/registration/models.py:236 +msgid "coach" +msgstr "encadrant" + +#: apps/registration/forms.py:34 apps/registration/forms.py:67 +msgid "This email address is already used." +msgstr "Cette adresse e-mail est déjà utilisée." + +#: apps/registration/forms.py:55 apps/registration/models.py:262 +msgid "volunteer" +msgstr "bénévole" + +#: apps/registration/forms.py:56 apps/registration/models.py:281 +msgid "admin" +msgstr "admin" + +#: apps/registration/forms.py:118 apps/registration/forms.py:140 +#: apps/registration/forms.py:162 apps/registration/forms.py:216 +msgid "The uploaded file must be a PDF, PNG of JPEG file." +msgstr "Le fichier envoyé doit être au format PDF, PNG ou JPEG." + +#: apps/registration/forms.py:208 +msgid "Pending" +msgstr "En attente" + +#: apps/registration/forms.py:224 +msgid "You must upload your scholarship attestation." +msgstr "Vous devez envoyer votre attestation de bourse." + +#: apps/registration/models.py:35 +msgid "Grant Animath to contact me in the future about other actions" +msgstr "" +"Autoriser Animath à me recontacter à l'avenir à propos d'autres actions" + +#: apps/registration/models.py:40 +msgid "email confirmed" +msgstr "email confirmé" + +#: apps/registration/models.py:48 +msgid "Activate your TFJM² account" +msgstr "Activez votre compte du TFJM²" + +#: apps/registration/models.py:99 apps/registration/models.py:302 +msgid "registration" +msgstr "inscription" + +#: apps/registration/models.py:100 +msgid "registrations" +msgstr "inscriptions" + +#: apps/registration/models.py:127 +msgid "birth date" +msgstr "date de naissance" + +#: apps/registration/models.py:132 +msgid "address" +msgstr "adresse" + +#: apps/registration/models.py:138 +msgid "phone number" +msgstr "numéro de téléphone" + +#: apps/registration/models.py:143 +msgid "photo authorization" +msgstr "autorisation de droit à l'image" + +#: apps/registration/models.py:169 +msgid "12th grade" +msgstr "Terminale" + +#: apps/registration/models.py:170 +msgid "11th grade" +msgstr "Première" + +#: apps/registration/models.py:171 +msgid "10th grade or lower" +msgstr "Seconde ou inférieur" + +#: apps/registration/models.py:173 +msgid "student class" +msgstr "classe" + +#: apps/registration/models.py:178 +msgid "school" +msgstr "école" + +#: apps/registration/models.py:183 +msgid "responsible name" +msgstr "nom du responsable légal" + +#: apps/registration/models.py:188 +msgid "responsible phone number" +msgstr "numéro de téléphone du responsable légal" + +#: apps/registration/models.py:193 +msgid "responsible email address" +msgstr "adresse e-mail du responsable légal" + +#: apps/registration/models.py:198 +msgid "parental authorization" +msgstr "autorisation parentale" + +#: apps/registration/models.py:205 +msgid "health sheet" +msgstr "fiche sanitaire" + +#: apps/registration/models.py:213 +msgid "student" +msgstr "étudiant" + +#: apps/registration/models.py:221 +msgid "student registration" +msgstr "inscription d'élève" + +#: apps/registration/models.py:222 +msgid "student registrations" +msgstr "inscriptions d'élève" + +#: apps/registration/models.py:231 apps/registration/models.py:253 +msgid "professional activity" +msgstr "activité professionnelle" + +#: apps/registration/models.py:244 +msgid "coach registration" +msgstr "inscription d'encadrant" + +#: apps/registration/models.py:245 +msgid "coach registrations" +msgstr "inscriptions d'encadrants" + +#: apps/registration/models.py:276 +msgid "role of the administrator" +msgstr "rôle de l'administrateur" + +#: apps/registration/models.py:289 +msgid "admin registration" +msgstr "inscription d'administrateur" + +#: apps/registration/models.py:290 +msgid "admin registrations" +msgstr "inscriptions d'administrateur" + +#: apps/registration/models.py:306 +msgid "type" +msgstr "type" + +#: apps/registration/models.py:309 +msgid "No payment" +msgstr "Pas de paiement" + +#: apps/registration/models.py:311 +msgid "Scholarship" +msgstr "Notification de bourse" + +#: apps/registration/models.py:312 +msgid "Bank transfer" +msgstr "Virement bancaire" + +#: apps/registration/models.py:313 +msgid "The tournament is free" +msgstr "Le tournoi est gratuit" + +#: apps/registration/models.py:320 +msgid "scholarship file" +msgstr "Notification de bourse" + +#: apps/registration/models.py:321 +msgid "only if you have a scholarship." +msgstr "Nécessaire seulement si vous déclarez être boursier." + +#: apps/registration/models.py:328 +msgid "additional information" +msgstr "informations additionnelles" + +#: apps/registration/models.py:329 +msgid "To help us to find your payment." +msgstr "Pour nous aider à retrouver votre paiement, si nécessaire." + +#: apps/registration/models.py:344 +#, python-brace-format +msgid "Payment of {registration}" +msgstr "Paiement de {registration}" + +#: apps/registration/models.py:347 +msgid "payment" +msgstr "paiement" + +#: apps/registration/models.py:348 +msgid "payments" +msgstr "paiements" + +#: apps/registration/tables.py:17 +msgid "last name" +msgstr "nom de famille" + +#: apps/registration/templates/registration/add_organizer.html:5 +#: apps/registration/templates/registration/add_organizer.html:12 +#: apps/registration/templates/registration/add_organizer.html:19 +#: apps/registration/templates/registration/user_list.html:8 +#: apps/registration/views.py:88 +msgid "Add organizer" +msgstr "Ajouter un organisateur" + +#: apps/registration/templates/registration/email_validation_complete.html:15 +msgid "Your email have successfully been validated." +msgstr "Votre email a été validé avec succès." + +#: apps/registration/templates/registration/email_validation_complete.html:18 +#, python-format +msgid "You can now log in." +msgstr "Vous pouvez désormais vous connecter." + +#: apps/registration/templates/registration/email_validation_complete.html:23 +msgid "" +"The link was invalid. The token may have expired, or your account is already " +"activated. However, your account seems to be already valid." +msgstr "" +"Le lien est invalide. Le jeton a peut-être expiré, ou votre compte est déjà " +"activé. Toutefois, il semble que votre compte est déjà valide." + +#: apps/registration/templates/registration/email_validation_complete.html:25 +msgid "" +"The link was invalid. The token may have expired, or your account is already " +"activated. Please send us an email to activate your account." +msgstr "" +"Le lien est invalide. Le jeton a peut-être expiré, ou votre compte est déjà " +"activé. Merci de nous envoyer un mail pour activer votre compte." + +#: apps/registration/templates/registration/email_validation_email_sent.html:10 +msgid "Account activation" +msgstr "Activation du compte" + +#: apps/registration/templates/registration/email_validation_email_sent.html:14 +msgid "" +"An email has been sent. Please click on the link to activate your account." +msgstr "" +"Un email a été envoyé. Merci de cliquer sur le lien pour activer votre " +"compte." + +#: apps/registration/templates/registration/mails/add_organizer.html:37 +#: apps/registration/templates/registration/mails/add_organizer.txt:17 +#: apps/registration/templates/registration/mails/email_validation_email.html:35 +#: apps/registration/templates/registration/mails/email_validation_email.txt:13 +msgid "The TFJM² team." +msgstr "L'équipe du TFJM²" + +#: apps/registration/templates/registration/mails/email_validation_email.html:12 +#: apps/registration/templates/registration/mails/email_validation_email.txt:3 +msgid "Hi" +msgstr "Bonjour" + +#: apps/registration/templates/registration/mails/email_validation_email.html:16 +#: apps/registration/templates/registration/mails/email_validation_email.txt:5 +msgid "" +"You recently registered on the TFJM² platform. Please click on the link " +"below to confirm your registration." +msgstr "" +"Vous vous êtes inscrits sur la plateforme du TFJM². Merci de cliquer sur le " +"lien ci-dessous pour confirmer votre inscription." + +#: apps/registration/templates/registration/mails/email_validation_email.html:26 +#: apps/registration/templates/registration/mails/email_validation_email.txt:9 +msgid "" +"This link is only valid for a couple of days, after that you will need to " +"contact us to validate your email." +msgstr "" +"Ce lien n'est valide que pendant quelques jours, après cela vous devrez nous " +"contacter pour valider votre email." + +#: apps/registration/templates/registration/mails/email_validation_email.html:30 +#: apps/registration/templates/registration/mails/email_validation_email.txt:11 +msgid "Thanks" +msgstr "Merci" + +#: apps/registration/templates/registration/password_change_done.html:8 +msgid "Your password was changed." +msgstr "Votre mot de passe a été changé." + +#: apps/registration/templates/registration/password_change_form.html:9 +msgid "" +"Please enter your old password, for security's sake, and then enter your new " +"password twice so we can verify you typed it in correctly." +msgstr "" +"Merci d'entrer votre ancien mot de passe pour des raisons de sécurité, et " +"d'entrer votre nouveau mot de passe deux fois afin de s'assurer que vous " +"l'ayez tapé correctement." + +#: apps/registration/templates/registration/password_change_form.html:11 +#: apps/registration/templates/registration/password_reset_confirm.html:12 +msgid "Change my password" +msgstr "Changer mon mot de passe" + +#: apps/registration/templates/registration/password_reset_complete.html:8 +msgid "Your password has been set. You may go ahead and log in now." +msgstr "Votre mot de passe a été changé. Vous pouvez désormais vous connecter." + +#: apps/registration/templates/registration/password_reset_complete.html:10 +#: tfjm/templates/base.html:127 tfjm/templates/base.html:238 +#: tfjm/templates/base.html:239 tfjm/templates/registration/login.html:7 +#: tfjm/templates/registration/login.html:8 +#: tfjm/templates/registration/login.html:25 +msgid "Log in" +msgstr "Connexion" + +#: apps/registration/templates/registration/password_reset_confirm.html:9 +msgid "" +"Please enter your new password twice so we can verify you typed it in " +"correctly." +msgstr "" +"Merci d'entrer votre nouveau mot de passe deux fois afin de vérifier que " +"vous l'ayez tapé correctement." + +#: apps/registration/templates/registration/password_reset_confirm.html:15 +msgid "" +"The password reset link was invalid, possibly because it has already been " +"used. Please request a new password reset." +msgstr "" +"Le lien de réinitialisation du mot de passe est invalide, probablement parce " +"qu'il a déjà été utilisé. Merci de demander une nouvelle réinitialisation du " +"mot de passe." + +#: apps/registration/templates/registration/password_reset_done.html:8 +msgid "" +"We've emailed you instructions for setting your password, if an account " +"exists with the email you entered. You should receive them shortly." +msgstr "" +"Nous vous avons envoyé un email contenant des instructions pour définir " +"votre mot de passe, si un compte existe avec l'adresse mail que vous avez " +"entrée. Vous devriez le recevoir très rapidement." + +#: apps/registration/templates/registration/password_reset_done.html:9 +msgid "" +"If you don't receive an email, please make sure you've entered the address " +"you registered with, and check your spam folder." +msgstr "" +"Si vous ne recevez pas de mail, merci de vous assurer que vous avez entré " +"l'adresse mail avec laquelle vous êtes inscrits, et de vérifier vos " +"courriers indésirables." + +#: apps/registration/templates/registration/password_reset_form.html:8 +msgid "" +"Forgotten your password? Enter your email address below, and we'll email " +"instructions for setting a new one." +msgstr "" +"Mot de passe oublié ? Entrez votre adresse mail ci-dessous, et nous vous " +"enverrons un mail avec les instructions pour en définir un nouveau." + +#: apps/registration/templates/registration/password_reset_form.html:11 +msgid "Reset my password" +msgstr "Réinitialiser mon mot de passe" + +#: apps/registration/templates/registration/payment_form.html:10 +#, python-format +msgid "" +"The price of the tournament is %(price)s €. The participation fee is offered " +"for coaches and for students who have a scholarship. If so, please send us " +"your scholarship attestation." +msgstr "" +"Le prix du tournoi est de %(price)s €. Les frais de participation sont " +"offerts pour les encadrants et les étudiants boursiers. Si c'est le cas, " +"merci de nous transmettre votre notification de bourse." + +#: apps/registration/templates/registration/payment_form.html:17 +msgid "" +"You can pay with a credit card through our " +"Hello Asso page. To make the validation of the payment easier, please use the same e-mail address that you use on " +"this platform. The payment verification will be checked automatically " +"under 10 minutes, you don't necessary need to fill this form." +msgstr "" +"Vous pouvez payer par carte bancaire sur notre page Hello Asso. Pour rendre la validation du " +"paiement plus facile, merci d'utiliser la même " +"adresse e-mail que vous utilisez sur cette plateforme. La " +"vérification du paiement sera faite automatiquement sous 10 minutes, vous " +"n'avez pas nécessairement besoin de remplir ce formulaire." + +#: apps/registration/templates/registration/payment_form.html:27 +msgid "" +"You can also send a bank transfer to the bank account of Animath. You must " +"put in the reference of the transfer the mention \"TFJMpu\" followed by the " +"last name and the first name of the student." +msgstr "" +"Vous pouvez également faire un virement bancaire sur le compte d'Animath. " +"Vous devez alors mettre dans la référence du transfert la mention \"TFJMpu\" " +"suivie du nom et du prénom de l'élève." + +#: apps/registration/templates/registration/payment_form.html:39 +msgid "" +"If any payment mean is available to you, please contact us at contact@tfjm.org to find " +"a solution to your difficulties." +msgstr "" +"Si aucun moyen de paiement ne vous convient, merci de nous contecter à " +"l'adresse contact@tfjm.org pour que nous puissions trouver une solution à vos " +"difficultés." + +#: apps/registration/templates/registration/signup.html:5 +#: apps/registration/templates/registration/signup.html:12 +#: apps/registration/templates/registration/signup.html:19 +#: apps/registration/views.py:44 +msgid "Sign up" +msgstr "Inscription" + +#: apps/registration/templates/registration/upload_health_sheet.html:6 +#: apps/registration/templates/registration/upload_parental_authorization.html:6 +#: apps/registration/templates/registration/upload_photo_authorization.html:6 +msgid "Back to the user detail" +msgstr "Retour aux détails de l'utilisateur" + +#: apps/registration/templates/registration/upload_health_sheet.html:11 +msgid "Health sheet template:" +msgstr "Modèle de fiche sanitaire :" + +#: apps/registration/templates/registration/upload_health_sheet.html:12 +#: apps/registration/templates/registration/upload_parental_authorization.html:12 +#: apps/registration/templates/registration/user_detail.html:54 +#: apps/registration/templates/registration/user_detail.html:67 +#: apps/registration/templates/registration/user_detail.html:77 +msgid "Download" +msgstr "Télécharger" + +#: apps/registration/templates/registration/upload_parental_authorization.html:11 +msgid "Authorization template:" +msgstr "Modèles d'autorisation :" + +#: apps/registration/templates/registration/upload_photo_authorization.html:11 +msgid "Authorization templates:" +msgstr "Modèles d'autorisation :" + +#: apps/registration/templates/registration/upload_photo_authorization.html:12 +msgid "Adult" +msgstr "Majeur" + +#: apps/registration/templates/registration/upload_photo_authorization.html:13 +msgid "Child" +msgstr "Mineur" + +#: apps/registration/templates/registration/user_detail.html:14 +msgid "Last name:" +msgstr "Nom de famille :" + +#: apps/registration/templates/registration/user_detail.html:17 +msgid "First name:" +msgstr "Prénom :" + +#: apps/registration/templates/registration/user_detail.html:22 +msgid "Not confirmed" +msgstr "Non confirmée" + +#: apps/registration/templates/registration/user_detail.html:22 +msgid "resend the validation link" +msgstr "Renvoyer le lien de validation" + +#: apps/registration/templates/registration/user_detail.html:25 +msgid "Password:" +msgstr "Mot de passe :" + +#: apps/registration/templates/registration/user_detail.html:28 +msgid "Change password" +msgstr "Changer mon mot de passe" + +#: apps/registration/templates/registration/user_detail.html:42 +msgid "Birth date:" +msgstr "Date de naissance :" + +#: apps/registration/templates/registration/user_detail.html:45 +msgid "Address:" +msgstr "Adresse :" + +#: apps/registration/templates/registration/user_detail.html:48 +msgid "Phone number:" +msgstr "Numéro de téléphone :" + +#: apps/registration/templates/registration/user_detail.html:51 +msgid "Photo authorization:" +msgstr "Autorisation de droit à l'image" + +#: apps/registration/templates/registration/user_detail.html:57 +#: apps/registration/templates/registration/user_detail.html:70 +#: apps/registration/templates/registration/user_detail.html:80 +msgid "Replace" +msgstr "Remplacer" + +#: apps/registration/templates/registration/user_detail.html:64 +msgid "Health sheet:" +msgstr "Fiche sanitaire :" + +#: apps/registration/templates/registration/user_detail.html:74 +msgid "Parental authorization:" +msgstr "Autorisation parentale :" + +#: apps/registration/templates/registration/user_detail.html:85 +msgid "Student class:" +msgstr "Classe :" + +#: apps/registration/templates/registration/user_detail.html:88 +msgid "School:" +msgstr "École :" + +#: apps/registration/templates/registration/user_detail.html:91 +msgid "Responsible name:" +msgstr "Nom du responsable légal :" + +#: apps/registration/templates/registration/user_detail.html:94 +msgid "Responsible phone number:" +msgstr "Numéro de téléphone du responsable légal :" + +#: apps/registration/templates/registration/user_detail.html:97 +msgid "Responsible email address:" +msgstr "Adresse e-mail du responsable légal :" + +#: apps/registration/templates/registration/user_detail.html:102 +msgid "Role:" +msgstr "Rôle :" + +#: apps/registration/templates/registration/user_detail.html:105 +msgid "Profesional activity:" +msgstr "Activité professionnelle :" + +#: apps/registration/templates/registration/user_detail.html:109 +msgid "Grant Animath to contact me in the future about other actions:" +msgstr "Autorise Animath à recontacter à propos d'autres actions :" + +#: apps/registration/templates/registration/user_detail.html:117 +msgid "Payment information:" +msgstr "Informations de paiement :" + +#: apps/registration/templates/registration/user_detail.html:119 +msgid "yes,no,pending" +msgstr "oui,non,en attente" + +#: apps/registration/templates/registration/user_detail.html:123 +#: apps/registration/templates/registration/user_detail.html:126 +msgid "valid:" +msgstr "valide :" + +#: apps/registration/templates/registration/user_detail.html:130 +#: apps/registration/templates/registration/user_detail.html:183 +msgid "Update payment" +msgstr "Modifier le paiement" + +#: apps/registration/templates/registration/user_detail.html:136 +msgid "Download scholarship attestation" +msgstr "Télécharger l'attestation de bourse" + +#: apps/registration/templates/registration/user_detail.html:149 +msgid "Impersonate" +msgstr "Impersonifier" + +#: apps/registration/templates/registration/user_detail.html:155 +msgid "Update user" +msgstr "Modifier l'utilisateur" + +#: apps/registration/templates/registration/user_detail.html:161 +#: apps/registration/views.py:315 +msgid "Upload photo authorization" +msgstr "Téléverser l'autorisation de droit à l'image" + +#: apps/registration/templates/registration/user_detail.html:166 +#: apps/registration/views.py:341 +msgid "Upload health sheet" +msgstr "Téléverser la fiche sanitaire" + +#: apps/registration/templates/registration/user_detail.html:171 +#: apps/registration/templates/registration/user_detail.html:176 +#: apps/registration/views.py:367 +msgid "Upload parental authorization" +msgstr "Téléverser l'autorisation parentale" + +#: apps/registration/views.py:127 +msgid "New TFJM² organizer account" +msgstr "Nouveau compte organisateur pour le TFJM²" + +#: apps/registration/views.py:149 +msgid "Email validation" +msgstr "Validation de l'adresse mail" + +#: apps/registration/views.py:151 +msgid "Validate email" +msgstr "Valider l'adresse mail" + +#: apps/registration/views.py:190 +msgid "Email validation unsuccessful" +msgstr "Échec de la validation de l'adresse mail" + +#: apps/registration/views.py:201 +msgid "Email validation email sent" +msgstr "Mail de confirmation de l'adresse mail envoyé" + +#: apps/registration/views.py:209 +msgid "Resend email validation link" +msgstr "Renvoyé le lien de validation de l'adresse mail" + +#: apps/registration/views.py:249 +#, python-brace-format +msgid "Detail of user {user}" +msgstr "Détails de l'utilisateur {user}" + +#: apps/registration/views.py:279 +#, python-brace-format +msgid "Update user {user}" +msgstr "Mise à jour de l'utilisateur {user}" + +#: apps/registration/views.py:476 +#, python-brace-format +msgid "Photo authorization of {student}.{ext}" +msgstr "Autorisation de droit à l'image de {student}.{ext}" + +#: apps/registration/views.py:499 +#, python-brace-format +msgid "Health sheet of {student}.{ext}" +msgstr "Fiche sanitaire de {student}.{ext}" + +#: apps/registration/views.py:522 +#, python-brace-format +msgid "Parental authorization of {student}.{ext}" +msgstr "Autorisation parentale de {student}.{ext}" + +#: apps/registration/views.py:544 +#, python-brace-format +msgid "Scholarship attestation of {user}.{ext}" +msgstr "Notification de bourse de {user}.{ext}" + +#: tfjm/settings.py:162 +msgid "English" +msgstr "Anglais" + +#: tfjm/settings.py:163 +msgid "French" +msgstr "Français" + +#: tfjm/templates/400.html:6 msgid "Bad request" msgstr "Requête invalide" -#: templates/400.html:7 +#: tfjm/templates/400.html:7 msgid "" "Sorry, your request was bad. Don't know what could be wrong. An email has " -"been sent to webmasters with the details of the error. You can now drink a " -"coke." +"been sent to webmasters with the details of the error. You can now think " +"about other solutions." msgstr "" -"Désolé, votre requête comporte une erreur. Aucune idée de ce qui a pu se " -"passer. Un email a été envoyé au développeur avec les détails de l'erreur. " -"Vous pouvez désormais aller chercher un coca." +"Désolé, votre requête est invalide. Aucune idée de ce qui a pu se passer. Un " +"email a été envoyé aux administrateurs avec les détails de l'erreur. Vous " +"pouvez désormais retourner chercher d'autres solutions." -#: templates/403.html:6 +#: tfjm/templates/403.html:6 msgid "Permission denied" -msgstr "Accès refusé" +msgstr "Permission refusée" -#: templates/403.html:7 +#: tfjm/templates/403.html:7 msgid "You don't have the right to perform this request." -msgstr "Vous n'avez pas la permission d'effectuer cette requête." +msgstr "Vous n'avez pas le droit d'effectuer cette requête." -#: templates/403.html:10 templates/404.html:10 +#: tfjm/templates/403.html:10 tfjm/templates/404.html:10 msgid "Exception message:" msgstr "Message d'erreur :" -#: templates/404.html:6 +#: tfjm/templates/404.html:6 msgid "Page not found" msgstr "Page non trouvée" -#: templates/404.html:7 +#: tfjm/templates/404.html:7 #, python-format msgid "" "The requested path %(request_path)s was not found on the server." @@ -798,445 +1704,121 @@ msgstr "" "Le chemin demandé %(request_path)s n'a pas été trouvé sur le " "serveur." -#: templates/500.html:6 +#: tfjm/templates/500.html:6 msgid "Server error" msgstr "Erreur du serveur" -#: templates/500.html:7 +#: tfjm/templates/500.html:7 msgid "" "Sorry, an error occurred when processing your request. An email has been " "sent to webmasters with the detail of the error, and this will be fixed " -"soon. You can now drink a beer." +"soon. You can now think about other solutions." msgstr "" -"Désolé, votre requête comporte une erreur. Aucune idée de ce qui a pu se " -"passer. Un email a été envoyé au développeur avec les détails de l'erreur. " -"Vous pouvez désormais aller chercher une bière." +"Désolé, une erreur est survenue lors du traitement de votre requête. Aucune " +"idée de ce qui a pu se passer. Un email a été envoyé aux administrateurs " +"avec les détails de l'erreur. Vous pouvez désormais retourner chercher " +"d'autres solutions.." -#: templates/base.html:11 -msgid "The inscription site of the TFJM²." -msgstr "Le site d'inscription au TFJM²." - -#: templates/base.html:73 +#: tfjm/templates/base.html:56 msgid "Home" msgstr "Accueil" -#: templates/base.html:76 -msgid "Tournament list" -msgstr "Liste des tournois" +#: tfjm/templates/base.html:60 +msgid "Tournaments" +msgstr "Tournois" -#: templates/base.html:89 -msgid "My account" -msgstr "Mon compte" +#: tfjm/templates/base.html:65 +msgid "Users" +msgstr "Utilisateurs" -#: templates/base.html:94 -msgid "Add a team" -msgstr "Ajouter une équipe" - -#: templates/base.html:97 -msgid "Join a team" -msgstr "Rejoindre une équipe" - -#: templates/base.html:101 +#: tfjm/templates/base.html:85 msgid "My team" msgstr "Mon équipe" -#: templates/base.html:144 -msgid "Make a gift" -msgstr "Faire un don" +#: tfjm/templates/base.html:90 +msgid "My participation" +msgstr "Ma participation" -#: templates/base.html:148 +#: tfjm/templates/base.html:97 +msgid "Chat" +msgstr "Chat" + +#: tfjm/templates/base.html:101 msgid "Administration" msgstr "Administration" -#: templates/base.html:155 +#: tfjm/templates/base.html:109 +msgid "Search..." +msgstr "Chercher ..." + +#: tfjm/templates/base.html:118 msgid "Return to admin view" -msgstr "Retour à l'interface administrateur" +msgstr "Retourner à l'interface administrateur" -#: templates/base.html:160 templates/registration/login.html:7 -#: templates/registration/login.html:8 templates/registration/login.html:22 -#: templates/registration/password_reset_complete.html:10 -msgid "Log in" -msgstr "Connexion" - -#: templates/base.html:163 templates/registration/signup.html:5 -#: templates/registration/signup.html:8 templates/registration/signup.html:14 -msgid "Sign up" +#: tfjm/templates/base.html:123 +msgid "Register" msgstr "S'inscrire" -#: templates/base.html:167 +#: tfjm/templates/base.html:139 +msgid "My account" +msgstr "Mon compte" + +#: tfjm/templates/base.html:142 msgid "Log out" msgstr "Déconnexion" -#: templates/django_filters/rest_framework/crispy_form.html:4 -#: templates/django_filters/rest_framework/form.html:2 -msgid "Field filters" -msgstr "Filtres" - -#: templates/django_filters/rest_framework/form.html:5 -#: templates/member/my_account.html:9 templates/tournament/add_organizer.html:9 -#: templates/tournament/pool_form.html:9 -#: templates/tournament/solutions_list.html:24 -#: templates/tournament/syntheses_list.html:40 -#: templates/tournament/team_form.html:9 -#: templates/tournament/tournament_form.html:9 -msgid "Submit" -msgstr "Envoyer" - -#: templates/member/my_account.html:14 -msgid "Update my password" -msgstr "Changer mon mot de passe" - -#: templates/member/profile_list.html:9 -msgid "Add an organizer" -msgstr "Ajouter un organisateur" - -#: templates/member/tfjmuser_detail.html:12 -msgid "role" -msgstr "rôle" - -#: templates/member/tfjmuser_detail.html:47 -msgid "class" -msgstr "classe" - -#: templates/member/tfjmuser_detail.html:76 -#: templates/tournament/team_detail.html:129 -msgid "Documents" -msgstr "Documents" - -#: templates/member/tfjmuser_detail.html:84 +#: tfjm/templates/base.html:159 #, python-format -msgid "View site as %(tfjmuser)s" -msgstr "Voir le site en tant que %(tfjmuser)s" - -#: templates/registration/email_validation_complete.html:6 -msgid "Your email have successfully been validated." -msgstr "Votre adresse e-mail a bien été validée." - -#: templates/registration/email_validation_complete.html:8 -#, python-format -msgid "You can now log in." -msgstr "Vous pouvez désormais vous connecter" - -#: templates/registration/email_validation_complete.html:10 msgid "" -"You must pay now your membership in the Kfet to complete your registration." +"Your email address is not validated. Please click on the link you received " +"by email. You can resend a mail by clicking on this link." msgstr "" +"Votre adresse mail n'est pas validée. Merci de cliquer sur le lien que vous " +"avez reçu par mail. Vous pouvez renvoyer un mail en cliquant sur ce lien." -#: templates/registration/email_validation_complete.html:13 -msgid "" -"The link was invalid. The token may have expired. Please send us an email to " -"activate your account." -msgstr "" -"Le lien est invalide. Le jeton a du expirer. Merci de nous envoyer un mail " -"afin d'activer votre compte." +#: tfjm/templates/base.html:183 +msgid "Contact us" +msgstr "Nous contacter" -#: templates/registration/logged_out.html:8 +#: tfjm/templates/base.html:202 +msgid "About" +msgstr "À propos" + +#: tfjm/templates/base.html:225 +msgid "Search results" +msgstr "Résultats de la recherche" + +#: tfjm/templates/registration/logged_out.html:8 msgid "Thanks for spending some quality time with the Web site today." msgstr "Merci d'avoir utilisé la plateforme du TFJM²." -#: templates/registration/logged_out.html:9 +#: tfjm/templates/registration/logged_out.html:9 msgid "Log in again" -msgstr "Se connecter à nouveau" +msgstr "Se reconnecter" -#: templates/registration/login.html:13 +#: tfjm/templates/registration/login.html:13 #, python-format msgid "" "You are authenticated as %(user)s, but are not authorized to access this " "page. Would you like to login to a different account?" msgstr "" -"Vous êtes déjà connecté sous le nom %(user)s, mais vous n'êtes pas autorisés " -"à accéder à cette page. Souhaitez-vous vous connecter sous un compte " -"différent ?" +"Vous êtes connectés en tant que %(user)s, mais n'êtes pas autorisés à " +"accéder à cette page. Voulez-vous vous reconnecter avec un autre compte ?" -#: templates/registration/login.html:23 +#: tfjm/templates/registration/login.html:23 msgid "Forgotten your password or username?" msgstr "Mot de passe oublié ?" -#: templates/registration/mails/email_validation_email.html:3 -msgid "Hi" -msgstr "Bonjour" +#: tfjm/templates/search/search.html:6 tfjm/templates/search/search.html:10 +msgid "Search" +msgstr "Chercher" -#: templates/registration/mails/email_validation_email.html:5 -msgid "" -"You recently registered on the Note Kfet. Please click on the link below to " -"confirm your registration." -msgstr "" +#: tfjm/templates/search/search.html:15 +msgid "Results" +msgstr "Résultats" -#: templates/registration/mails/email_validation_email.html:9 -msgid "" -"This link is only valid for a couple of days, after that you will need to " -"contact us to validate your email." -msgstr "" - -#: templates/registration/mails/email_validation_email.html:11 -msgid "" -"After that, you'll have to wait that someone validates your account before " -"you can log in. You will need to pay your membership in the Kfet." -msgstr "" - -#: templates/registration/mails/email_validation_email.html:13 -msgid "Thanks" -msgstr "Merci" - -#: templates/registration/mails/email_validation_email.html:15 -msgid "The Note Kfet team." -msgstr "" - -#: templates/registration/password_change_done.html:8 -msgid "Your password was changed." -msgstr "Votre mot de passe a été changé" - -#: templates/registration/password_change_form.html:9 -msgid "" -"Please enter your old password, for security's sake, and then enter your new " -"password twice so we can verify you typed it in correctly." -msgstr "" -"Veuillez entrer votre ancien mot de passe, pour des raisons de sécurité, " -"puis entrer votre mot de passe deux fois afin de vérifier que vous l'avez " -"tapé correctement." - -#: templates/registration/password_change_form.html:11 -#: templates/registration/password_reset_confirm.html:12 -msgid "Change my password" -msgstr "Changer mon mot de passe" - -#: templates/registration/password_reset_complete.html:8 -msgid "Your password has been set. You may go ahead and log in now." -msgstr "Votre mot de passe a été changé. Vous pouvez désormais vous connecter." - -#: templates/registration/password_reset_confirm.html:9 -msgid "" -"Please enter your new password twice so we can verify you typed it in " -"correctly." -msgstr "" -"Veuillez taper votre nouveau mot de passe deux fois afin de s'assurer que " -"vous l'ayez tapé correctement." - -#: templates/registration/password_reset_confirm.html:15 -msgid "" -"The password reset link was invalid, possibly because it has already been " -"used. Please request a new password reset." -msgstr "" -"Le lien de réinitialisation du mot de passe est invalide, sans doute parce " -"qu'il a été déjà utilisé. Veuillez demander une nouvelle demande de " -"réinitialisation." - -#: templates/registration/password_reset_done.html:8 -msgid "" -"We've emailed you instructions for setting your password, if an account " -"exists with the email you entered. You should receive them shortly." -msgstr "" -"Nous vous avons envoyé des instructions pour réinitialiser votre mot de " -"passe, si un compte existe avec l'adresse email entrée. Vous devriez les " -"recevoir d'ici peu." - -#: templates/registration/password_reset_done.html:9 -msgid "" -"If you don't receive an email, please make sure you've entered the address " -"you registered with, and check your spam folder." -msgstr "" -"Si vous n'avez pas reçu d'email, merci de vérifier que vous avez entré " -"l'adresse avec laquelle vous êtes inscrits, et vérifier vos spams." - -#: templates/registration/password_reset_form.html:8 -msgid "" -"Forgotten your password? Enter your email address below, and we'll email " -"instructions for setting a new one." -msgstr "" -"Mot de passe oublié ? Entrez votre adresse email ci-dessous, et nous vous " -"enverrons des instructions pour en définir un nouveau." - -#: templates/registration/password_reset_form.html:11 -msgid "Reset my password" -msgstr "Réinitialiser mon mot de passe" - -#: templates/tournament/pool_detail.html:36 -msgid "Solutions will be available here for teams from:" -msgstr "Les solutions seront disponibles ici pour les équipes à partir du :" - -#: templates/tournament/pool_detail.html:49 -#: templates/tournament/pool_detail.html:73 -msgid "Download ZIP archive" -msgstr "Télécharger l'archive ZIP" - -#: templates/tournament/pool_detail.html:61 -#: templates/tournament/syntheses_list.html:7 -msgid "Templates for syntheses are available here:" -msgstr "Le modèle de note de synthèse est disponible ici :" - -#: templates/tournament/pool_detail.html:83 -msgid "Pool list" -msgstr "Liste des poules" - -#: templates/tournament/pool_detail.html:89 -msgid "" -"Give this link to juries to access this page (warning: should stay " -"confidential and only given to juries of this pool):" -msgstr "" -"Donnez ce lien aux jurys pour leur permettre d'accéder à cette page " -"(attention : ce lien doit rester confidentiel et ne doit être donné " -"exclusivement qu'à des jurys) :" - -#: templates/tournament/pool_list.html:10 -msgid "Add pool" -msgstr "Ajouter une poule" - -#: templates/tournament/solutions_list.html:9 -#, python-format -msgid "You can upload your solutions until %(deadline)s." -msgstr "Vous pouvez envoyer vos solutions jusqu'au %(deadline)s." - -#: templates/tournament/solutions_list.html:14 -msgid "" -"The deadline to send your solutions is reached. However, you have an extra " -"time of 30 minutes to send your papers, no panic :)" -msgstr "" -"La date limite pour envoyer vos solutions est dépassée. Toutefois, vous avez " -"droit à un délai supplémentaire de 30 minutes pour envoyer vos papiers, pas " -"de panique :)" - -#: templates/tournament/solutions_list.html:16 -msgid "You can't upload your solutions anymore." -msgstr "Vous ne pouvez plus publier vos solutions." - -#: templates/tournament/solutions_orga_list.html:14 -#: templates/tournament/syntheses_orga_list.html:14 -#, python-format -msgid "%(tournament)s — ZIP" -msgstr "%(tournament)s — ZIP" - -#: templates/tournament/syntheses_list.html:14 -#: templates/tournament/syntheses_list.html:26 -#, python-format -msgid "You can upload your syntheses for round %(round)s until %(deadline)s." -msgstr "" -"Vous pouvez envoyer vos notes de synthèses pour le tour %(round)s jusqu'au " -"%(deadline)s." - -#: templates/tournament/syntheses_list.html:18 -#: templates/tournament/syntheses_list.html:30 -#, python-format -msgid "" -"The deadline to send your syntheses for the round %(round)s is reached. " -"However, you have an extra time of 30 minutes to send your papers, no " -"panic :)" -msgstr "" -"La date limite pour envoyer vos notes de synthèses pour le tour %(round)s " -"est dépassée. Toutefois, vous avez droit à un délai supplémentaire de 30 " -"minutes pour envoyer vos papiers, pas de panique :)" - -#: templates/tournament/syntheses_list.html:22 -#: templates/tournament/syntheses_list.html:34 -#, python-format -msgid "You can't upload your syntheses for the round %(round)s anymore." -msgstr "" -"Vous ne pouvez plus publier vos notes de synthèses pour le tour %(round)s." - -#: templates/tournament/team_detail.html:8 -msgid "Team" -msgstr "Équipe" - -#: templates/tournament/team_detail.html:25 -msgid "coachs" -msgstr "encadrants" - -#: templates/tournament/team_detail.html:28 -msgid "participants" -msgstr "participants" - -#: templates/tournament/team_detail.html:39 -msgid "Send a mail to people in this team" -msgstr "Envoyer un mail à toutes les personnes de cette équipe" - -#: templates/tournament/team_detail.html:49 -msgid "Edit team" -msgstr "Modifier l'équipe" - -#: templates/tournament/team_detail.html:53 -msgid "Select for final" -msgstr "Sélectionner pour la finale" - -#: templates/tournament/team_detail.html:59 -msgid "Delete team" -msgstr "Supprimer l'équipe" - -#: templates/tournament/team_detail.html:61 -msgid "Leave this team" -msgstr "Quitter l'équipe" - -#: templates/tournament/team_detail.html:105 -msgid "The team is waiting about validation." -msgstr "L'équipe est en attente de validation" - -#: templates/tournament/team_detail.html:112 -msgid "Message addressed to the team:" -msgstr "Message adressé à l'équipe :" - -#: templates/tournament/team_detail.html:114 -msgid "Message..." -msgstr "Message ..." - -#: templates/tournament/team_detail.html:119 -msgid "Invalidate team" -msgstr "Invalider l'équipe" - -#: templates/tournament/team_detail.html:120 -msgid "Validate team" -msgstr "Valider l'équipe" - -#: templates/tournament/team_detail.html:133 -msgid "Motivation letter:" -msgstr "Lettre de motivation :" - -#: templates/tournament/team_detail.html:152 -msgid "Download solutions as ZIP" -msgstr "Télécharger les solutions en archive ZIP" - -#: templates/tournament/tournament_detail.html:22 -msgid "Free" -msgstr "Gratuit" - -#: templates/tournament/tournament_detail.html:25 -msgid "From" -msgstr "Du" - -#: templates/tournament/tournament_detail.html:25 -msgid "to" -msgstr "à" - -#: templates/tournament/tournament_detail.html:48 -msgid "Send a mail to all people in this tournament" -msgstr "Envoyer un mail à toutes les personnes du tournoi" - -#: templates/tournament/tournament_detail.html:49 -msgid "Send a mail to all people in this tournament that are in a valid team" -msgstr "" -"Envoyer un mail à toutes les personnes du tournoi dans une équipe valide" - -#: templates/tournament/tournament_detail.html:56 -msgid "Edit tournament" -msgstr "Modifier le tournoi" - -#: templates/tournament/tournament_detail.html:63 -msgid "Teams" -msgstr "Équipes" - -#: templates/tournament/tournament_list.html:8 -msgid "Send a mail to all people that are in a team" -msgstr "Envoyer un mail à toutes les personnes dans une équipe" - -#: templates/tournament/tournament_list.html:9 -msgid "Send a mail to all people that are in a valid team" -msgstr "Envoyer un mail à toutes les personnes dans une équipe validée" - -#: templates/tournament/tournament_list.html:15 -msgid "Add a tournament" -msgstr "Ajouter un tournoi" - -#: tfjm/settings.py:147 -msgid "English" -msgstr "Anglais" - -#: tfjm/settings.py:148 -msgid "French" -msgstr "Français" +#: tfjm/templates/search/search.html:25 +msgid "No results found." +msgstr "Aucun résultat." diff --git a/nginx_tfjm.conf b/nginx_tfjm.conf index be143ce..3fa0e6b 100644 --- a/nginx_tfjm.conf +++ b/nginx_tfjm.conf @@ -5,6 +5,8 @@ upstream tfjm { server { listen 80; server_name tfjm; + charset utf-8; + client_max_body_size 50M; location / { proxy_pass http://tfjm; @@ -16,4 +18,8 @@ server { location /static { alias /code/static/; } + + location /doc { + alias /code/docs/_build/html/; + } } diff --git a/requirements.txt b/requirements.txt index 4338302..48ed2f3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,14 +1,25 @@ -bcrypt +asgiref~=3.3.1 Django~=3.0 -django-allauth -django-crispy-forms -django-extensions -django-filter -django-polymorphic -django-tables2 -djangorestframework -django-rest-polymorphic -mysqlclient -psycopg2-binary -ptpython -gunicorn \ No newline at end of file +django-address~=0.2 +django-bootstrap-datepicker-plus~=3.0 +django-cas-server~=1.2 +django-crispy-forms~=1.9 +django-extensions~=3.0 +django-filter~=2.3 +django-haystack~=3.0 +django-mailer~=2.0 +django-phonenumber-field~=5.0.0 +django-polymorphic~=3.0 +django-tables2~=2.3 +djangorestframework~=3.12 +django-rest-polymorphic~=0.1 +gunicorn~=20.0 +matrix-nio~=0.15 +phonenumbers~=8.9.10 +psycopg2-binary~=2.8 +PyPDF3~=1.0.2 +ipython~=7.19.0 +python-magic==0.4.18 +requests~=2.25.0 +sympasoap~=1.0 +whoosh~=2.7 \ No newline at end of file diff --git a/server_files/403.php b/server_files/403.php deleted file mode 100644 index 72127d0..0000000 --- a/server_files/403.php +++ /dev/null @@ -1,16 +0,0 @@ - - -
-

- Vous n'êtes pas autorisé à accéder à cette page. -

-
- - - -
-

- Cette page n'existe pas. -

-
- -prepare("SELECT * FROM `documents` WHERE `file_id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - return self::fromData($data); - } - - public static function fromData($data) - { - $doc = new Document(); - $doc->fill($data); - return $doc; - } - - private function fill($data) - { - $this->file_id = $data["file_id"]; - $this->user_id = $data["user"]; - $this->team_id = $data["team"]; - $this->tournament_id = $data["tournament"]; - $this->type = DocumentType::fromName($data["type"]); - $this->uploaded_at = $data["uploaded_at"]; - $this->version = isset($data["version"]) ? $data["version"] : 1; - } - - public function getFileId() - { - return $this->file_id; - } - - public function getUserId() - { - return $this->user_id; - } - - public function getTeamId() - { - return $this->team_id; - } - - public function getTournamentId() - { - return $this->tournament_id; - } - - public function getType() - { - return $this->type; - } - - public function getUploadedAt() - { - return $this->uploaded_at; - } - - public function getVersion() - { - return $this->version; - } -} - -class Solution -{ - private $file_id; - private $team_id; - private $tournament_id; - private $problem; - private $uploaded_at; - private $version; - - private function __construct() {} - - public static function fromId($id) - { - global $DB; - $req = $DB->prepare("SELECT * FROM `solutions` WHERE `file_id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - return self::fromData($data); - } - - public static function fromData($data) - { - $sol = new Solution(); - $sol->fill($data); - return $sol; - } - - private function fill($data) - { - $this->file_id = $data["file_id"]; - $this->team_id = $data["team"]; - $this->tournament_id = $data["tournament"]; - $this->problem = $data["problem"]; - $this->uploaded_at = $data["uploaded_at"]; - $this->version = isset($data["version"]) ? $data["version"] : 1; - } - - public function getFileId() - { - return $this->file_id; - } - - public function getTeamId() - { - return $this->team_id; - } - - public function getTournamentId() - { - return $this->tournament_id; - } - - public function getProblem() - { - return $this->problem; - } - - public function getUploadedAt() - { - return $this->uploaded_at; - } - - public function getVersion() - { - return $this->version; - } -} - -class Synthesis -{ - private $file_id; - private $team_id; - private $tournament_id; - private $dest; - private $round; - private $uploaded_at; - private $version; - - private function __construct() {} - - public static function fromId($id) - { - global $DB; - $req = $DB->prepare("SELECT * FROM `syntheses` WHERE `file_id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - return self::fromData($data); - } - - public static function fromData($data) - { - $synthese = new Synthesis(); - $synthese->fill($data); - return $synthese; - } - - private function fill($data) - { - $this->file_id = $data["file_id"]; - $this->team_id = $data["team"]; - $this->tournament_id = $data["tournament"]; - $this->dest = $data["dest"]; - $this->round = $data["round"]; - $this->uploaded_at = $data["uploaded_at"]; - $this->version = isset($data["version"]) ? $data["version"] : 1; - } - - public function getFileId() - { - return $this->file_id; - } - - public function getTeamId() - { - return $this->team_id; - } - - public function getTournamentId() - { - return $this->tournament_id; - } - - public function getDest() - { - return $this->dest; - } - - public function getRound() - { - return $this->round; - } - - public function getUploadedAt() - { - return $this->uploaded_at; - } - - public function getVersion() - { - return $this->version; - } -} - -class DestType -{ - const DEFENSEUR = 0; - const OPPOSANT = 1; - const RAPPORTEUR = 2; - - public static function getTranslatedName($status) { - switch ($status) { - case self::OPPOSANT: - return "Opposant"; - case self::RAPPORTEUR: - return "Rapporteur"; - default: - return "Défenseur"; - } - } - - public static function getName($status) { - switch ($status) { - case self::OPPOSANT: - return "OPPOSANT"; - case self::RAPPORTEUR: - return "RAPPORTEUR"; - default: - return "DEFENSEUR"; - } - } - - public static function fromName($name) { - switch ($name) { - case "OPPOSANT": - return self::OPPOSANT; - case "RAPPORTEUR": - return self::RAPPORTEUR; - default: - return self::DEFENSEUR; - } - } -} - -class DocumentType -{ - const PARENTAL_CONSENT = 0; - const PHOTO_CONSENT = 1; - const SANITARY_PLUG = 2; - const SOLUTION = 3; - const SYNTHESIS = 4; - const SCHOLARSHIP = 5; - const MOTIVATION_LETTER = 6; - - public static function getTranslatedName($type) { - switch ($type) { - case self::PARENTAL_CONSENT: - return "Autorisation parentale"; - case self::PHOTO_CONSENT: - return "Autorisation de droit à l'image"; - case self::SANITARY_PLUG: - return "Fiche sanitaire"; - case self::SCHOLARSHIP: - return "Notification de bourse"; - case self::MOTIVATION_LETTER: - return "Lettre de motivation"; - case self::SOLUTION: - return "Solution"; - default: - return "Note de synthèse"; - } - } - - public static function getName($type) { - switch ($type) { - case self::PARENTAL_CONSENT: - return "PARENTAL_CONSENT"; - case self::PHOTO_CONSENT: - return "PHOTO_CONSENT"; - case self::SANITARY_PLUG: - return "SANITARY_PLUG"; - case self::SCHOLARSHIP: - return "SCHOLARSHIP"; - case self::MOTIVATION_LETTER: - return "MOTIVATION_LETTER"; - case self::SOLUTION: - return "SOLUTION"; - default: - return "SYNTHESIS"; - } - } - - public static function fromName($name) { - switch ($name) { - case "PARENTAL_CONSENT": - return self::PARENTAL_CONSENT; - case "PHOTO_CONSENT": - return self::PHOTO_CONSENT; - case "SANITARY_PLUG": - return self::SANITARY_PLUG; - case "SCHOLARSHIP": - return self::SCHOLARSHIP; - case "MOTIVATION_LETTER": - return self::MOTIVATION_LETTER; - case "SOLUTION": - return self::SOLUTION; - default: - return self::SYNTHESIS; - } - } -} \ No newline at end of file diff --git a/server_files/classes/Payment.php b/server_files/classes/Payment.php deleted file mode 100644 index 2847403..0000000 --- a/server_files/classes/Payment.php +++ /dev/null @@ -1,152 +0,0 @@ -prepare("SELECT * FROM `payments` WHERE `id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $payment = new Payment(); - $payment->fill($data); - return $payment; - } - - private function fill($data) - { - $this->id = $data["id"]; - $this->user_id = $data["user"]; - $this->tournament_id = $data["tournament"]; - $this->amount = $data["amount"]; - $this->method = PaymentMethod::fromName($data["method"]); - $this->transaction_infos = $data["transaction_infos"]; - $this->validation_status = ValidationStatus::fromName($data["validation_status"]); - } - - /** - * @return int - */ - public function getId() - { - return $this->id; - } - - /** - * @return int - */ - public function getAmount() - { - return $this->amount; - } - - /** - * @param mixed $amount - */ - public function setAmount($amount) - { - global $DB; - $this->amount = $amount; - $DB->prepare("UPDATE `payments` SET `amount` = ? WHERE `id` = ?;")->execute([$amount, $this->id]); - } - - /** - * @return int - */ - public function getMethod() - { - return $this->method; - } - - /** - * @param int $method - */ - public function setMethod($method) - { - global $DB; - $this->method = $method; - $DB->prepare("UPDATE `payments` SET `method` = ? WHERE `id` = ?;")->execute([PaymentMethod::getName($method), $this->id]); - } - - /** - * @return int - */ - public function getTournamentId() - { - return $this->tournament_id; - } - - /** - * @return Tournament|null - */ - public function getTournament() - { - return Tournament::fromId($this->getTournamentId()); - } - - /** - * @return int - */ - public function getUserId() - { - return $this->user_id; - } - - /** - * @return User|null - */ - public function getUser() - { - return User::fromId($this->getUserId()); - } - - /** - * @return string - */ - public function getTransactionInfos() - { - return $this->transaction_infos; - } - - /** - * @param string $transaction_infos - */ - public function setTransactionInfos($transaction_infos) - { - global $DB; - $this->transaction_infos = $transaction_infos; - $DB->prepare("UPDATE `payments` SET `transaction_infos` = ? WHERE `id` = ?;")->execute([$transaction_infos, $this->id]); - } - - /** - * @return int - */ - public function getValidationStatus() - { - return $this->validation_status; - } - - /** - * @param int $validation_status - */ - public function setValidationStatus($validation_status) - { - global $DB; - $this->validation_status = $validation_status; - $DB->prepare("UPDATE `payments` SET `validation_status` = ? WHERE `id` = ?;")->execute([ValidationStatus::getName($validation_status), $this->id]); - } -} \ No newline at end of file diff --git a/server_files/classes/PaymentMethod.php b/server_files/classes/PaymentMethod.php deleted file mode 100644 index f0d5420..0000000 --- a/server_files/classes/PaymentMethod.php +++ /dev/null @@ -1,62 +0,0 @@ -prepare("SELECT * FROM `teams` WHERE `id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $team = new Team(); - $team->fill($data); - return $team; - } - - public static function fromTrigram($trigram) - { - global $DB, $YEAR; - $req = $DB->prepare("SELECT * FROM `teams` WHERE `trigram` = ? AND `year` = $YEAR;"); - $req->execute([htmlspecialchars($trigram)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $team = new Team(); - $team->fill($data); - return $team; - } - - public static function fromAccessCode($access_code) - { - global $DB, $YEAR; - $req = $DB->prepare("SELECT * FROM `teams` WHERE `access_code` = ? AND `year` = $YEAR;"); - $req->execute([htmlspecialchars($access_code)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $team = new Team(); - $team->fill($data); - return $team; - } - - private function fill($data) - { - $this->id = $data["id"]; - $this->name = $data["name"]; - $this->trigram = $data["trigram"]; - $this->tournament = $data["tournament"]; - $this->encadrants = [$data["encadrant_1"], $data["encadrant_2"], $data["encadrant_3"]]; - $this->participants = [$data["participant_1"], $data["participant_2"], $data["participant_3"], $data["participant_4"], $data["participant_5"], $data["participant_6"]]; - $this->inscription_date = $data["inscription_date"]; - $this->validation_status = ValidationStatus::fromName($data["validation_status"]); - $this->final_selection = $data["final_selection"] == true; - $this->access_code = $data["access_code"]; - $this->year = $data["year"]; - } - - public function getId() - { - return $this->id; - } - - public function getName() - { - return $this->name; - } - - public function setName($name) - { - global $DB; - $this->name = $name; - $DB->prepare("UPDATE `teams` SET `name` = ? WHERE `id` = ?;")->execute([$name, $this->id]); - } - - public function getTrigram() - { - return $this->trigram; - } - - public function setTrigram($trigram) - { - global $DB; - $this->trigram = $trigram; - $DB->prepare("UPDATE `teams` SET `trigram` = ? WHERE `id` = ?;")->execute([$trigram, $this->id]); - } - - public function getTournamentId() - { - return $this->tournament; - } - - /** - * @return Tournament - */ - public function getEffectiveTournament() - { - return $this->isSelectedForFinal() ? Tournament::getFinalTournament() : Tournament::fromId($this->getTournamentId()); - } - - public function setTournamentId($tournament) - { - global $DB; - $this->tournament = $tournament; - $DB->prepare("UPDATE `teams` SET `tournament` = ? WHERE `id` = ?;")->execute([$tournament, $this->id]); - } - - public function getEncadrants() - { - return $this->encadrants; - } - - public function setEncadrant($i, $encadrant) - { - global $DB; - $this->encadrants[$i - 1] = $encadrant; - /** @noinspection SqlResolve */ - $DB->prepare("UPDATE `teams` SET `encadrant_$i` = ? WHERE `id` = ?;")->execute([$encadrant, $this->id]); - } - - public function getParticipants() - { - return $this->participants; - } - - public function setParticipant($i, $participant) - { - global $DB; - $this->participants[$i - 1] = $participant; - /** @noinspection SqlResolve */ - $DB->prepare("UPDATE `teams` SET `participant_$i` = ? WHERE `id` = ?;")->execute([$participant, $this->id]); - } - - public function getInscriptionDate() - { - return $this->inscription_date; - } - - public function getValidationStatus() - { - return $this->validation_status; - } - - public function setValidationStatus($status) - { - global $DB; - $this->validation_status = $status; - /** @noinspection PhpUndefinedMethodInspection */ - $DB->prepare("UPDATE `teams` SET `validation_status` = ? WHERE `id` = ?;")->execute([ValidationStatus::getName($status), $this->id]); - } - - public function isSelectedForFinal() - { - return $this->final_selection; - } - - public function selectForFinal($selected) - { - global $DB; - $this->final_selection = $selected; - $DB->prepare("UPDATE `teams` SET `final_selection` = ? WHERE `id` = ?;")->execute([$selected, $this->id]); - } - - public function getAccessCode() - { - return $this->access_code; - } - - public function getYear() - { - return $this->year; - } - - public static function getAllTeams($only_not_validated = false) - { - global $DB, $YEAR; - $req = $DB->query("SELECT * FROM `teams` WHERE " . ($only_not_validated ? "`validation_status` = 0 AND " : "") . "`year` = $YEAR;"); - - $teams = []; - - while (($data = $req->fetch()) != false) { - $team = new Team(); - $team->fill($data); - $teams[] = $team; - } - - return $teams; - } -} diff --git a/server_files/classes/Tournament.php b/server_files/classes/Tournament.php deleted file mode 100644 index 6860bad..0000000 --- a/server_files/classes/Tournament.php +++ /dev/null @@ -1,385 +0,0 @@ -prepare("SELECT * FROM `tournaments` WHERE `id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $tournament = new Tournament(); - $tournament->fill($data); - return $tournament; - } - - public static function fromName($name) - { - global $DB, $YEAR; - $req = $DB->prepare("SELECT * FROM `tournaments` WHERE `name` = ? AND `year` = $YEAR;"); - $req->execute([htmlspecialchars($name)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $tournament = new Tournament(); - $tournament->fill($data); - return $tournament; - } - - public static function getFinalTournament() - { - global $DB, $YEAR; - $req = $DB->query("SELECT * FROM `tournaments` WHERE `final` AND `year` = $YEAR;"); - $data = $req->fetch(); - - if ($data === false) - return null; - - $tournament = new Tournament(); - $tournament->fill($data); - return $tournament; - } - - public static function getAllTournaments($include_final = true, $only_future = false) - { - global $DB, $YEAR; - $sql = "SELECT * FROM `tournaments` WHERE "; - if (!$include_final) - $sql .= "`final` = 0 AND "; - if ($only_future) - $sql .= "`date_start` > CURRENT_DATE AND "; - $sql .= "`year` = $YEAR ORDER BY `date_start`, `name`;"; - $req = $DB->query($sql); - - $tournaments = []; - - while (($data = $req->fetch()) !== false) { - $tournament = new Tournament(); - $tournament->fill($data); - $tournaments[] = $tournament; - } - - return $tournaments; - } - - private function fill($data) - { - $this->id = $data["id"]; - $this->name = $data["name"]; - $this->size = $data["size"]; - $this->place = $data["place"]; - $this->price = $data["price"]; - $this->description = $data["description"]; - $this->date_start = $data["date_start"]; - $this->date_end = $data["date_end"]; - $this->date_inscription = $data["date_inscription"]; - $this->date_solutions = $data["date_solutions"]; - $this->date_solutions_2 = $data["date_solutions_2"]; - $this->date_syntheses = $data["date_syntheses"]; - $this->date_syntheses_2 = $data["date_syntheses_2"]; - $this->final = $data["final"] == true; - $this->year = $data["year"]; - - global $DB; - $req = $DB->prepare("SELECT `organizer` FROM `organizers` WHERE `tournament` = ?;"); - $req->execute([$this->id]); - - while (($data = $req->fetch()) !== false) - $this->organizers[] = User::fromId($data["organizer"]); - } - - public function getId() - { - return $this->id; - } - - public function getName() - { - return $this->name; - } - - public function setName($name) - { - global $DB; - $this->name = $name; - $DB->prepare("UPDATE `tournaments` SET `name` = ? WHERE `id` = ?;")->execute([$name, $this->id]); - } - - public function getSize() - { - return $this->size; - } - - public function setSize($size) - { - global $DB; - $this->size = $size; - $DB->prepare("UPDATE `tournaments` SET `size` = ? WHERE `id` = ?;")->execute([$size, $this->id]); - } - - public function getPlace() - { - return $this->place; - } - - public function setPlace($place) - { - global $DB; - $this->place = $place; - $DB->prepare("UPDATE `tournaments` SET `place` = ? WHERE `id` = ?;")->execute([$place, $this->id]); - } - - public function getPrice() - { - return $this->price; - } - - public function setPrice($price) - { - global $DB; - $this->price = $price; - $DB->prepare("UPDATE `tournaments` SET `price` = ? WHERE `id` = ?;")->execute([$price, $this->id]); - } - - public function getDescription() - { - return $this->description; - } - - public function setDescription($desc) - { - global $DB; - $this->description = $desc; - $DB->prepare("UPDATE `tournaments` SET `description` = ? WHERE `id` = ?;")->execute([$desc, $this->id]); - } - - public function getStartDate() - { - return $this->date_start; - } - - public function setStartDate($date) - { - global $DB; - $this->date_start = $date; - $DB->prepare("UPDATE `tournaments` SET `date_start` = ? WHERE `id` = ?;")->execute([$date, $this->id]); - } - - public function getEndDate() - { - return $this->date_end; - } - - public function setEndDate($date) - { - global $DB; - $this->date_end = $date; - $DB->prepare("UPDATE `tournaments` SET `date_end` = ? WHERE `id` = ?;")->execute([$date, $this->id]); - } - - public function getInscriptionDate() - { - return $this->date_inscription; - } - - public function setInscriptionDate($date) - { - global $DB; - $this->date_inscription = $date; - $DB->prepare("UPDATE `tournaments` SET `date_inscription` = ? WHERE `id` = ?;")->execute([$date, $this->id]); - } - - public function getSolutionsDate() - { - return $this->date_solutions; - } - - public function setSolutionsDate($date) - { - global $DB; - $this->date_solutions = $date; - $DB->prepare("UPDATE `tournaments` SET `date_solutions` = ? WHERE `id` = ?;")->execute([$date, $this->id]); - } - - public function getSynthesesDate() - { - return $this->date_syntheses; - } - - public function setSynthesesDate($date) - { - global $DB; - $this->date_syntheses = $date; - $DB->prepare("UPDATE `tournaments` SET `date_syntheses` = ? WHERE `id` = ?;")->execute([$date, $this->id]); - } - - public function getSolutionsDate2() - { - return $this->date_solutions_2; - } - - public function setSolutionsDate2($date) - { - global $DB; - $this->date_solutions_2 = $date; - $DB->prepare("UPDATE `tournaments` SET `date_solutions_2` = ? WHERE `id` = ?;")->execute([$date, $this->id]); - } - - public function getSynthesesDate2() - { - return $this->date_syntheses_2; - } - - public function setSynthesesDate2($date) - { - global $DB; - $this->date_syntheses_2 = $date; - $DB->prepare("UPDATE `tournaments` SET `date_syntheses_2` = ? WHERE `id` = ?;")->execute([$date, $this->id]); - } - - public function isFinal() - { - return $this->final; - } - - public function setFinal($final) - { - global $DB; - $this->final = $final; - $DB->prepare("UPDATE `tournaments` SET `final` = ? WHERE `id` = ?;")->execute([$final, $this->id]); - } - - public function getAllTeams() - { - global $DB, $YEAR; - if ($this->final) - $req = $DB->query("SELECT `id` FROM `teams` WHERE `final_selection` AND `year` = $YEAR;"); - else - $req = $DB->query("SELECT `id` FROM `teams` WHERE `tournament` = $this->id AND `year` = $YEAR;"); - - $teams = []; - - while (($data = $req->fetch()) !== false) - $teams[] = Team::fromId($data["id"]); - - return $teams; - } - - public function getOrganizers() - { - return $this->organizers; - } - - public function organize($user_id) - { - foreach ($this->organizers as $organizer) { - if ($organizer->getId() == $user_id) - return true; - } - - return false; - } - - public function addOrganizer(User $user) - { - global $DB; - - $this->organizers[] = $user; - - $req = $DB->prepare("INSERT INTO `organizers`(`organizer`, `tournament`) VALUES(?, ?);"); - $req->execute([$user->getId(), $this->id]); - } - - public function clearOrganizers() - { - global $DB; - - $this->organizers = []; - - $req = $DB->prepare("DELETE FROM `organizers` WHERE `tournament` = ?;"); - $req->execute([$this->id]); - } - - public function getYear() - { - return $this->year; - } - - public function getAllDocuments($team_id = -1) - { - global $DB; - - $req = $DB->query("SELECT * FROM `documents` AS `t1` " - . "INNER JOIN (SELECT `user`, `type`, `tournament`, MAX(`uploaded_at`) AS `last_upload`, COUNT(`team`) AS `version` FROM `documents` GROUP BY `tournament`, `team`, `type`, `user`) `t2` " - . "ON `t1`.`user` = `t2`.`user` AND `t1`.`type` = `t2`.`type` AND `t1`.`tournament` = `t2`.`tournament` " - . "WHERE `t1`.`uploaded_at` = `t2`.`last_upload` AND `t1`.`tournament` = $this->id " . ($team_id == -1 ? "" : "AND `t1`.`team` = $team_id") . " ORDER BY `t1`.`team`, `t1`.`type`;"); - - $docs = []; - - while (($data = $req->fetch()) !== false) - $docs[] = Document::fromData($data); - - return $docs; - } - - public function getAllSolutions($team_id = -1) - { - global $DB; - - $req = $DB->query("SELECT * FROM `solutions` AS `t1` " - . "INNER JOIN (SELECT `team`, `problem`, `tournament`, MAX(`uploaded_at`) AS `last_upload`, COUNT(`team`) AS `version` FROM `solutions` GROUP BY `tournament`, `team`, `problem`) `t2` " - . "ON `t1`.`team` = `t2`.`team` AND `t1`.`problem` = `t2`.`problem` AND `t1`.`tournament` = `t2`.`tournament` " - . "WHERE `t1`.`uploaded_at` = `t2`.`last_upload` AND `t1`.`tournament` = $this->id " . ($team_id == -1 ? "" : "AND `t1`.`team` = $team_id") . " ORDER BY `t1`.`team`, `t1`.`problem`;"); - - $sols = []; - - while (($data = $req->fetch()) !== false) - $sols[] = Solution::fromData($data); - - return $sols; - } - - public function getAllSyntheses($team_id = -1) - { - global $DB; - - $req = $DB->query("SELECT * FROM `syntheses` AS `t1` " - . "INNER JOIN (SELECT `team`, `dest`, `round`, `tournament`, MAX(`uploaded_at`) AS `last_upload`, COUNT(`team`) AS `version` FROM `syntheses` GROUP BY `tournament`, `team`, `dest`, `round`) `t2` " - . "ON `t1`.`team` = `t2`.`team` AND `t1`.`dest` = `t2`.`dest` AND `t1`.`tournament` = `t2`.`tournament` AND `t1`.`round` = `t2`.`round` " - . "WHERE `t1`.`uploaded_at` = `t2`.`last_upload` AND `t1`.`tournament` = $this->id " . ($team_id == -1 ? "" : "AND `t1`.`team` = $team_id") . " ORDER BY `t1`.`team`, `t1`.`round`, `t1`.`dest`;"); - - $syntheses = []; - - while (($data = $req->fetch()) !== false) - $syntheses[] = Synthesis::fromData($data); - - return $syntheses; - } -} \ No newline at end of file diff --git a/server_files/classes/User.php b/server_files/classes/User.php deleted file mode 100644 index cc8111e..0000000 --- a/server_files/classes/User.php +++ /dev/null @@ -1,481 +0,0 @@ -prepare("SELECT * FROM `users` WHERE `id` = ?;"); - $req->execute([htmlspecialchars($id)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $user = new User(); - $user->fill($data); - return $user; - } - - public static function fromEmail($email) - { - global $DB, $YEAR; - $req = $DB->prepare("SELECT * FROM `users` WHERE `email` = ? AND `year` = $YEAR;"); - $req->execute([htmlspecialchars($email)]); - $data = $req->fetch(); - - if ($data === false) - return null; - - $user = new User(); - $user->fill($data); - return $user; - } - - private function fill($data) - { - $this->id = $data["id"]; - $this->email = $data["email"]; - $this->pwd_hash = $data["pwd_hash"]; - $this->surname = $data["surname"]; - $this->first_name = $data["first_name"]; - $this->birth_date = $data["birth_date"]; - $this->gender = $data["gender"]; - $this->address = $data["address"]; - $this->postal_code = $data["postal_code"]; - $this->city = $data["city"]; - $this->country = $data["country"]; - $this->phone_number = $data["phone_number"]; - $this->school = $data["school"]; - $this->class = SchoolClass::fromName($data["class"]); - $this->responsible_name = $data["responsible_name"]; - $this->responsible_phone = $data["responsible_phone"]; - $this->responsible_email = $data["responsible_email"]; - $this->description = $data["description"]; - $this->role = Role::fromName($data["role"]); - $this->team_id = $data["team_id"]; - $this->year = $data["year"]; - $this->confirm_email = $data["confirm_email"]; - $this->forgotten_password = $data["forgotten_password"]; - $this->inscription_date = $data["inscription_date"]; - } - public static function getOrganizers() - { - global $DB, $YEAR; - $admins = []; - $req = $DB->query("SELECT * FROM `users` WHERE `role` = 'ORGANIZER' OR `role` = 'ADMIN' AND `year` = $YEAR ORDER BY `role` DESC, `surname`, `first_name`;"); - - while (($data = $req->fetch()) !== false) { - $admin = new User(); - $admin->fill($data); - $admins[] = $admin; - } - - return $admins; - } - - public static function getAdmins() - { - global $DB, $YEAR; - $users = []; - $req = $DB->query("SELECT * FROM `users` WHERE (`role` = 'ADMIN') " - . "AND `year` = $YEAR ORDER BY `role`, `inscription_date`;"); - - while (($data = $req->fetch()) !== false) { - $orphan = new User(); - $orphan->fill($data); - $users[] = $orphan; - } - - return $users; - } - - public static function getAllUsers() - { - global $DB, $YEAR; - $users = []; - $req = $DB->query("SELECT * FROM `users` WHERE `year` = $YEAR ORDER BY `role` DESC, `inscription_date`;"); - - while (($data = $req->fetch()) !== false) { - $orphan = new User(); - $orphan->fill($data); - $users[] = $orphan; - } - - return $users; - } - - public static function getOrphanUsers() - { - global $DB, $YEAR; - $orphans = []; - $req = $DB->query("SELECT * FROM `users` WHERE `role` != 'ADMIN' AND `team_id` IS NULL " - . "AND `year` = $YEAR ORDER BY `role`, `inscription_date`;"); - - while (($data = $req->fetch()) !== false) { - $orphan = new User(); - $orphan->fill($data); - $orphans[] = $orphan; - } - - return $orphans; - } - - public function getEmail() - { - return $this->email; - } - - public function setEmail($email) - { - global $DB; - $this->email = $email; - $DB->prepare("UPDATE `users` SET `email` = ? WHERE `id` = ?;")->execute([$email, $this->getId()]); - } - - public function getId() - { - return $this->id; - } - - public function checkPassword($password) - { - return password_verify($password, $this->pwd_hash); - } - - public function setPassword($password) - { - $this->setPasswordHash(password_hash($password, PASSWORD_BCRYPT)); - } - - private function setPasswordHash($password_hash) - { - global $DB; - $this->pwd_hash = $password_hash; - $DB->prepare("UPDATE `users` SET `pwd_hash` = ? WHERE `id` = ?;")->execute([$password_hash, $this->getId()]); - } - - public function getSurname() - { - return $this->surname; - } - - public function setSurname($surname) - { - global $DB; - $this->surname = $surname; - $DB->prepare("UPDATE `users` SET `surname` = ? WHERE `id` = ?;")->execute([$surname, $this->getId()]); - } - - public function getFirstName() - { - return $this->first_name; - } - - public function setFirstName($first_name) - { - global $DB; - $this->first_name = $first_name; - $DB->prepare("UPDATE `users` SET `first_name` = ? WHERE `id` = ?;")->execute([$first_name, $this->getId()]); - } - - public function getBirthDate() - { - return $this->birth_date; - } - - public function setBirthDate($birth_date) - { - global $DB; - $this->birth_date = $birth_date; - $DB->prepare("UPDATE `users` SET `birth_date` = ? WHERE `id` = ?;")->execute([$birth_date, $this->getId()]); - } - - public function getGender() - { - return $this->gender; - } - - public function setGender($gender) - { - global $DB; - $this->gender = $gender; - $DB->prepare("UPDATE `users` SET `gender` = ? WHERE `id` = ?;")->execute([$gender, $this->getId()]); - } - - public function getAddress() - { - return $this->address; - } - - public function setAddress($address) - { - global $DB; - $this->address = $address; - $DB->prepare("UPDATE `users` SET `address` = ? WHERE `id` = ?;")->execute([$address, $this->getId()]); - } - - public function getPostalCode() - { - return $this->postal_code; - } - - public function setPostalCode($postal_code) - { - global $DB; - $this->postal_code = $postal_code; - $DB->prepare("UPDATE `users` SET `postal_code` = ? WHERE `id` = ?;")->execute([$postal_code, $this->getId()]); - } - - public function getCity() - { - return $this->city; - } - - public function setCity($city) - { - global $DB; - $this->city = $city; - $DB->prepare("UPDATE `users` SET `city` = ? WHERE `id` = ?;")->execute([$city, $this->getId()]); - } - - public function getCountry() - { - return $this->country; - } - - public function setCountry($country) - { - global $DB; - $this->country = $country; - $DB->prepare("UPDATE `users` SET `country` = ? WHERE `id` = ?;")->execute([$country, $this->getId()]); - } - - public function getPhoneNumber() - { - return $this->phone_number; - } - - public function setPhoneNumber($phone_number) - { - global $DB; - $this->phone_number = $phone_number; - $DB->prepare("UPDATE `users` SET `phone_number` = ? WHERE `id` = ?;")->execute([$phone_number, $this->getId()]); - } - - public function getSchool() - { - return $this->school; - } - - public function setSchool($school) - { - global $DB; - $this->school = $school; - $DB->prepare("UPDATE `users` SET `school` = ? WHERE `id` = ?;")->execute([$school, $this->getId()]); - } - - public function getClass() - { - return $this->class; - } - - public function setClass($class) - { - global $DB; - $this->class = $class; - $DB->prepare("UPDATE `users` SET `class` = ? WHERE `id` = ?;")->execute([SchoolClass::getName($class), $this->getId()]); - } - - public function getResponsibleName() - { - return $this->responsible_name; - } - - public function setResponsibleName($responsible_name) - { - global $DB; - $this->responsible_name = $responsible_name; - $DB->prepare("UPDATE `users` SET `responsible_name` = ? WHERE `id` = ?;")->execute([$responsible_name, $this->getId()]); - } - - public function getResponsiblePhone() - { - return $this->responsible_phone; - } - - public function setResponsiblePhone($responsible_phone) - { - global $DB; - $this->responsible_phone = $responsible_phone; - $DB->prepare("UPDATE `users` SET `responsible_phone` = ? WHERE `id` = ?;")->execute([$responsible_phone, $this->getId()]); - } - - public function getResponsibleEmail() - { - return $this->responsible_email; - } - - public function setResponsibleEmail($responsible_email) - { - global $DB; - $this->responsible_email = $responsible_email; - $DB->prepare("UPDATE `users` SET `responsible_email` = ? WHERE `id` = ?;")->execute([$responsible_email, $this->getId()]); - } - - public function getDescription() - { - return $this->description; - } - - public function setDescription($desc) - { - global $DB; - $this->description = $desc; - $DB->prepare("UPDATE `users` SET `description` = ? WHERE `id` = ?;")->execute([$desc, $this->getId()]); - } - - public function getRole() - { - return $this->role; - } - - public function setRole($role) - { - global $DB; - $this->role = $role; - /** @noinspection PhpUndefinedMethodInspection */ - $DB->prepare("UPDATE `users` SET `role` = ? WHERE `id` = ?;")->execute([Role::getName($role), $this->getId()]); - } - - public function getTeamId() - { - return $this->team_id; - } - - public function setTeamId($team_id) - { - global $DB; - $this->team_id = $team_id; - $DB->prepare("UPDATE `users` SET `team_id` = ? WHERE `id` = ?;")->execute([$team_id, $this->getId()]); - } - - public function getYear() - { - return $this->year; - } - - public function getConfirmEmailToken() - { - return $this->confirm_email; - } - - public function setConfirmEmailToken($token) - { - global $DB; - $this->confirm_email = $token; - $DB->prepare("UPDATE `users` SET `confirm_email` = ? WHERE `id` = ?;")->execute([$token, $this->getId()]); - } - - public function getForgottenPasswordToken() - { - return $this->forgotten_password; - } - - public function setForgottenPasswordToken($token) - { - global $DB; - $this->forgotten_password = $token; - $DB->prepare("UPDATE `users` SET `forgotten_password` = ? WHERE `id` = ?;")->execute([$token, $this->getId()]); - } - - public function getInscriptionDate() - { - return $this->inscription_date; - } - - public function getAllDocuments($tournament_id) - { - global $DB; - $req = $DB->query("SELECT * FROM `documents` AS `t1` " - . "INNER JOIN (SELECT `user`, `type`, `tournament`, MAX(`uploaded_at`) AS `last_upload`, COUNT(`team`) AS `version` FROM `documents` GROUP BY `tournament`, `type`, `user`) `t2` " - . "ON `t1`.`user` = `t2`.`user` AND `t1`.`type` = `t2`.`type` AND `t1`.`tournament` = `t2`.`tournament` " - . "WHERE `t1`.`uploaded_at` = `t2`.`last_upload` AND `t1`.`tournament` = $tournament_id AND `t1`.`user` = $this->id ORDER BY `t1`.`type`;"); - - $docs = []; - - while (($data = $req->fetch()) !== false) - $docs[] = Document::fromData($data); - - if ($this->team_id > 0) { - $req = $DB->query("SELECT * FROM `documents` AS `t1` " - . "INNER JOIN (SELECT `user`, `type`, `tournament`, MAX(`uploaded_at`) AS `last_upload`, COUNT(`team`) AS `version` FROM `documents` GROUP BY `tournament`, `type`, `user`) `t2` " - . "ON `t1`.`user` = `t2`.`user` AND `t1`.`type` = `t2`.`type` AND `t1`.`tournament` = `t2`.`tournament` " - . "WHERE `t1`.`uploaded_at` = `t2`.`last_upload` AND `t1`.`tournament` = $tournament_id AND `t1`.`team` = $this->team_id " - . "AND `t1`.`type` = 'MOTIVATION_LETTER';"); - - while (($data = $req->fetch()) !== false) - $docs[] = Document::fromData($data); - } - - return $docs; - } - - public function getPayment() { - global $DB; - - $team = Team::fromId($this->team_id); - $tournament = $team->getEffectiveTournament(); - - $req = $DB->prepare("SELECT `id` FROM `payments` WHERE `user` = ?;"); - $req->execute([$this->id]); - - if (($data = $req->fetch()) !== false) - return Payment::fromId($data["id"]); - - $req = $DB->prepare("INSERT INTO `payments`(`user`, `tournament`, `amount`, `method`, `transaction_infos`, `validation_status`) VALUES (?, ?, ?, ?, ?, ?);"); - $req->execute([$this->id, $tournament->getId(), 0, PaymentMethod::getName(PaymentMethod::NOT_PAID), "L'inscription n'est pas encore payée.", ValidationStatus::getName(ValidationStatus::NOT_READY)]); - - return $this->getPayment(); - } - - public function getOrganizedTournaments() - { - global $DB; - $req = $DB->query("SELECT `tournament` FROM `organizers` JOIN `tournaments` ON `tournaments`.`id` = `tournament` WHERE `organizer` = $this->id ORDER BY `date_start`, `name`;"); - - $tournaments = []; - - while (($data = $req->fetch()) !== false) - $tournaments[] = Tournament::fromId($data["tournament"]); - - return $tournaments; - } -} \ No newline at end of file diff --git a/server_files/classes/ValidationStatus.php b/server_files/classes/ValidationStatus.php deleted file mode 100644 index 459d7ad..0000000 --- a/server_files/classes/ValidationStatus.php +++ /dev/null @@ -1,41 +0,0 @@ - PDO::ERRMODE_EXCEPTION)); -} -catch (Exception $ex) { - die("Erreur lors de la connexion à la base de données : " . $ex->getMessage()); -} - -date_default_timezone_set("Europe/Paris"); - -session_start(); -setlocale(LC_ALL, "fr_FR.utf8"); diff --git a/server_files/controllers/ajouter_equipe.php b/server_files/controllers/ajouter_equipe.php deleted file mode 100644 index 95112bb..0000000 --- a/server_files/controllers/ajouter_equipe.php +++ /dev/null @@ -1,63 +0,0 @@ -query("SELECT `id`, `name` FROM `tournaments` WHERE `date_inscription` > CURRENT_TIMESTAMP AND `year` = $YEAR;"); - -$has_error = false; -$error_message = null; - -if (isset($_POST["add_team"])) { - $new_team = new NewTeam($_POST); - try { - $new_team->makeVerifications(); - $new_team->register(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class NewTeam { - public $name; - public $trigram; - public $tournament_id; - public $tournament; - public $access_code; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() { - ensure($_SESSION["team"] == null, "Vous êtes déjà dans une équipe."); - ensure($this->name != null && $this->name != "", "Vous devez spécifier un nom d'équipe."); - ensure(preg_match("#^[A-Z]{3}$#", $this->trigram), "Le trigramme entré n'est pas valide."); - ensure(!teamExists($this->name), "Une équipe existe déjà avec ce nom."); - ensure(!trigramExists($this->trigram), "Une équipe a déjà choisi ce trigramme."); - $this->tournament = Tournament::fromId($this->tournament_id); - ensure($this->tournament != null, "Le tournoi spécifié n'existe pas."); - } - - public function register() { - global $DB, $YEAR; - - $this->access_code = genRandomPhrase(6); - - $req = $DB->prepare("INSERT INTO `teams` (`name`, `trigram`, `tournament`, `encadrant_1`, `participant_1`, `validation_status`, `access_code`, `year`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?);"); - $req->execute([$this->name, $this->trigram, $this->tournament_id, $_SESSION["role"] == Role::ENCADRANT ? $_SESSION["user_id"] : NULL, - $_SESSION["role"] == Role::PARTICIPANT ? $_SESSION["user_id"] : NULL, ValidationStatus::getName(ValidationStatus::NOT_READY), $this->access_code, $YEAR]); - - $_SESSION["team"] = Team::fromTrigram($this->trigram); - $_SESSION["user"]->setTeamId($_SESSION["team"]->getId()); - - Mailer::sendAddTeamMail($_SESSION["user"], $_SESSION["team"], $this->tournament); - } -} - -require_once "server_files/views/ajouter_equipe.php"; diff --git a/server_files/controllers/ajouter_organisateur.php b/server_files/controllers/ajouter_organisateur.php deleted file mode 100644 index d196a88..0000000 --- a/server_files/controllers/ajouter_organisateur.php +++ /dev/null @@ -1,59 +0,0 @@ -makeVerifications(); - $orga->register(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class NewOrganizer { - public $surname; - public $first_name; - public $email; - public $admin; - public $password; - public $token; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() - { - ensure($this->surname != null && $this->surname != "", "Le nom est invalide."); - ensure($this->first_name != null && $this->first_name != "", "Le prénom est invalide."); - ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail est invalide."); - $this->email = strtolower($this->email); - ensure(!userExists($this->email), "Cette adresse e-mail est déjà utilisée."); - $this->admin = isset($this->admin) ? 1 : 0; - } - - public function register() { - global $DB, $YEAR; - - $this->password = genRandomPhrase(16, true); - $this->token = genRandomPhrase(64); - - $req = $DB->prepare("INSERT INTO `users`(`email`, `pwd_hash`, `surname`, `first_name`, `role`, `forgotten_password`, `year`) - VALUES (?, ?, ?, ?, ?, ?, ?);"); - $req->execute([$this->email, password_hash($this->password, PASSWORD_BCRYPT), $this->surname, $this->first_name, $this->admin ? "ADMIN" : "ORGANIZER", $this->token, $YEAR]); - - Mailer::sendAddOrganizerMail($this); - } -} - -require_once "server_files/views/ajouter_organisateur.php"; \ No newline at end of file diff --git a/server_files/controllers/ajouter_tournoi.php b/server_files/controllers/ajouter_tournoi.php deleted file mode 100644 index 6618de7..0000000 --- a/server_files/controllers/ajouter_tournoi.php +++ /dev/null @@ -1,111 +0,0 @@ -makeVerifications(); - $tournament->register(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class NewTournament { - public $name; - public $organizers; - public $size; - public $place; - public $price; - public $date_start; - public $date_end; - public $date_inscription; - public $time_inscription; - public $date_solutions; - public $time_solutions; - public $date_syntheses; - public $time_syntheses; - public $date_solutions_2; - public $time_solutions_2; - public $date_syntheses_2; - public $time_syntheses_2; - public $description; - public $final; - public $tournament; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = ($key == "organizers" ? $value : htmlspecialchars($value)); - } - - public function makeVerifications() - { - global $FINAL; - - ensure($this->name != null && $this->name != "", "Le nom est invalide."); - ensure(!tournamentExists($this->name), "Un tournoi existe déjà avec ce nom."); - ensure(sizeof($this->organizers) > 0, "Aucun organisateur n'a été choisi."); - - $orgas = []; - foreach ($this->organizers as $orga_id) { - $orga = User::fromId($orga_id); - ensure($orga != null, "Un organisateur spécifié n'existe pas."); - ensure($orga->getRole() == Role::ORGANIZER || $orga->getRole() == Role::ADMIN, "Une personne indiquée ne peut pas organiser de tournoi."); - $orgas[] = $orga; - } - $this->organizers = $orgas; - - ensure(preg_match("#[0-9]*#", $this->size), "Le nombre d'équipes indiqué n'est pas un nombre valide."); - $this->size = intval($this->size); - ensure($this->size >= 3 && $this->size <= 15, "Un tournoi doit avoir au moins 3 et au plus 15 équipes."); - - ensure(preg_match("#[0-9]*#", $this->price), "Le tarif pour les participants n'est pas un entier valide."); - $this->price = intval($this->price); - ensure($this->price >= 0, "Le TFJM² ne va pas payer les élèves pour venir."); - ensure($this->price <= 50, "Soyons raisonnable sur le prix."); - - ensure(dateWellFormed($this->date_start), "La date de début n'est pas valide."); - ensure(dateWellFormed($this->date_end), "La date de fin n'est pas valide."); - ensure(dateWellFormed($this->date_inscription . " " . $this->time_inscription), "La date de clôture des inscriptions n'est pas valide."); - ensure(dateWellFormed($this->date_solutions . " " . $this->time_solutions), "La date limite de remise des solutions n'est pas valide."); - ensure(dateWellFormed($this->date_syntheses . " " . $this->time_syntheses), "La date limite de remise des notes de synthèse pour le tour 1 n'est pas valide."); - ensure(dateWellFormed($this->date_solutions_2 . " " . $this->time_solutions_2), "La date limite de visibilité des solutions du tour 2 n'est pas valide."); - ensure(dateWellFormed($this->date_syntheses . " " . $this->time_syntheses), "La date limite de remise des notes de synthèse pour le tour 2 n'est pas valide."); - - $this->final = $this->final ? 1 : 0; - - ensure(!$this->final || $FINAL == NULL, "Une finale nationale est déjà enregistrée."); - } - - public function register() - { - global $DB, $YEAR; - - $req = $DB->prepare("INSERT INTO `tournaments` (`name`, `size`, `place`, `price`, `description`, - `date_start`, `date_end`, `date_inscription`, `date_solutions`, `date_syntheses`, - `date_solutions_2`, `date_syntheses_2`, `final`, `year`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); - $req->execute([$this->name, $this->size, $this->place, $this->price, $this->description, $this->date_start, $this->date_end, - "$this->date_inscription $this->time_inscription", "$this->date_solutions $this->time_solutions", - "$this->date_syntheses $this->time_syntheses", "$this->date_solutions_2 $this->time_solutions_2", - "$this->date_syntheses_2 $this->time_syntheses_2", $this->final ? 1 : 0, $YEAR]); - - $this->tournament = Tournament::fromName($this->name); - - /** @var User $organizer */ - foreach ($this->organizers as $organizer) { - $this->tournament->addOrganizer($organizer); - Mailer::sendAddOrganizerForTournamentMail($organizer, $this->tournament); - } - } -} - -require_once "server_files/views/ajouter_tournoi.php"; diff --git a/server_files/controllers/autorisation_droit_image.php b/server_files/controllers/autorisation_droit_image.php deleted file mode 100644 index 41b20c5..0000000 --- a/server_files/controllers/autorisation_droit_image.php +++ /dev/null @@ -1,52 +0,0 @@ -getEffectiveTournament(); - - $majeur = $user->getBirthDate() > strval($YEAR - 18) . substr($tournament->getStartDate(), 4); - - $tex = file_get_contents("assets/Autorisation_droit_image_" . ($majeur ? "majeur" : "mineur") . ".tex"); - - $tex = preg_replace("#{PARTICIPANT_NAME}#", "\\texttt{" . $user->getFirstName() . " " . $user->getSurname() . "}", $tex); - $tex = preg_replace("#{BIRTHDAY}#", "\\texttt{" . strftime("%d %B %G", strtotime($user->getBirthDate())) . "}", $tex); - $tex = preg_replace("#{ADDRESS}#", "\\texttt{" . $user->getAddress() . ", " . $user->getPostalCode() . ", " . $user->getCity() - . ($user->getCountry() == "France" ? "" : $user->getCountry()) . "}.", $tex); -} - -$tex = preg_replace("#{TOURNAMENT_NAME}#", $tournament->getName(), $tex); -$tex = preg_replace("#{PLACE}#", $tournament->getPlace(), $tex); -$tex = preg_replace("#{START_DATE}#", strftime("%d %B", strtotime($tournament->getStartDate())), $tex); -$tex = preg_replace("#{END_DATE}#", strftime("%d %B", strtotime($tournament->getEndDate())), $tex); -$tex = preg_replace("#{YEAR}#", $YEAR, $tex); - -shell_exec("mkdir tmp"); - -file_put_contents("tmp/file.tex", $tex); - -shell_exec("pdflatex -synctex=1 -interaction=nonstopmode -shell-escape -output-directory=tmp tmp/file.tex"); -header("Content-type: application/pdf"); -readfile("tmp/file.pdf"); - -exit(0); \ No newline at end of file diff --git a/server_files/controllers/autorisation_parentale.php b/server_files/controllers/autorisation_parentale.php deleted file mode 100644 index 40cdc29..0000000 --- a/server_files/controllers/autorisation_parentale.php +++ /dev/null @@ -1,44 +0,0 @@ -getEffectiveTournament(); - $tex = preg_replace("#{PARTICIPANT_NAME}#", "\\texttt{" . $user->getFirstName() . " " . $user->getSurname() . "}", $tex); - $tex = preg_replace("#{BIRTHDAY}#", "\\texttt{" . strftime("%d %B %G", strtotime($user->getBirthDate())) . "}", $tex); - $tex = preg_replace("#{PRONOUN}#", $user->getGender() == "M" ? "Il" : "Elle", $tex); -} - -$tex = preg_replace("#{TOURNAMENT_NAME}#", $tournament->getName(), $tex); -$tex = preg_replace("#{PLACE}#", $tournament->getPlace(), $tex); -$tex = preg_replace("#{START_DATE}#", strftime("%d %B", strtotime($tournament->getStartDate())), $tex); -$tex = preg_replace("#{END_DATE}#", strftime("%d %B", strtotime($tournament->getEndDate())), $tex); -$tex = preg_replace("#{YEAR}#", $YEAR, $tex); - -shell_exec("mkdir tmp"); - -file_put_contents("tmp/file.tex", $tex); - -shell_exec("pdflatex -synctex=1 -interaction=nonstopmode -shell-escape -output-directory=tmp tmp/file.tex"); -header("Content-type: application/pdf"); -readfile("tmp/file.pdf"); - -exit(0); \ No newline at end of file diff --git a/server_files/controllers/confirmer_mail.php b/server_files/controllers/confirmer_mail.php deleted file mode 100644 index 3b2326f..0000000 --- a/server_files/controllers/confirmer_mail.php +++ /dev/null @@ -1,22 +0,0 @@ -query("SELECT `email` FROM `users` WHERE `confirm_email` = '$token' AND `year` = '$YEAR';"); - if (($data = $result->fetch()) === FALSE) - $error_message = "Le jeton est invalide. Votre compte est peut-être déjà validé ?"; - else { - $DB->exec("UPDATE `users` SET `confirm_email` = NULL WHERE `confirm_email` = '$token';"); - $error_message = "Votre adresse mail a été validée ! Vous pouvez désormais vous connecter."; - $alert = "success"; - } -} -else { - $error_message = "Il n'y a pas de compte à valider !"; - $alert = "warning"; -} -require_once "server_files/views/header.php"; -echo "

$error_message

"; -require_once "server_files/views/footer.php"; diff --git a/server_files/controllers/connexion.php b/server_files/controllers/connexion.php deleted file mode 100644 index 47c8b69..0000000 --- a/server_files/controllers/connexion.php +++ /dev/null @@ -1,170 +0,0 @@ -makeVerifications(); - $logging_in_user->login(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_POST["forgotten_password"]) && !isset($_SESSION["user_id"])) { - $recuperate_account = new RecuperateAccount($_POST); - try { - $recuperate_account->makeVerifications(); - $recuperate_account->recuperateAccount(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_GET["reset_password"]) && isset($_GET["token"]) && !isset($_SESSION["user_id"])) { - $reset_password = new ResetPassword($_GET, $_POST); - try { - $reset_password->makeVerifications(); - if (isset($_POST["password"])) - $reset_password->resetPassword(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_GET["confirmation-mail"]) && !isset($_SESSION["user_id"])) - sendConfirmEmail(); - -class LoggingInUser -{ - public $email; - /** @var User $user */ - public $user; - private $password; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() - { - global $URL_BASE; - - ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse email est invalide."); - $this->user = User::fromEmail($this->email); - ensure($this->user != null, "Le compte n'existe pas."); - ensure($this->user->checkPassword($this->password), "Le mot de passe est incorrect."); - if ($this->user->getConfirmEmailToken() != null) { - $_SESSION["confirm_email"] = $this->email; - throw new AssertionError("L'adresse mail n'a pas été validée. Veuillez vérifier votre boîte mail (surtout vos spams). " - . "Cliquez ici pour renvoyer le mail de confirmation."); - } - } - - public function login() - { - $_SESSION["user_id"] = $this->user->getId(); - loadUserValues(); - } -} - -class RecuperateAccount -{ - public $email; - /** @var User $user */ - public $user; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() - { - ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse email est invalide."); - $this->user = User::fromEmail($this->email); - ensure($this->user != null, "Le compte n'existe pas."); - } - - public function recuperateAccount() - { - $token = genRandomPhrase(64); - $this->user->setForgottenPasswordToken($token); - Mailer::sendForgottenPasswordProcedureMail($this->user); - } -} - -class ResetPassword -{ - public $token; - /** @var User $user */ - public $user; - private $password; - private $confirm_password; - - public function __construct($data, $data2) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - foreach ($data2 as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() - { - global $DB; - $data = $DB->query("SELECT `id` FROM `users` WHERE `forgotten_password` = '" . $this->token . "';")->fetch(); - ensure($data !== false, "Il n'y a pas de compte à récupérer avec ce jeton."); - $this->user = User::fromId($data["id"]); - - if ($this->password == null) - return; - - ensure($this->password == $this->confirm_password, "Les deux mots de passe sont différents."); - ensure(strlen($this->password) >= 8, "Le mot de passe doit comporter au moins 8 caractères."); - } - - public function resetPassword() - { - $this->user->setForgottenPasswordToken(null); - $this->user->setPassword($this->password); - - Mailer::sendChangePasswordMail($this->user); - - return false; - } -} - -function sendConfirmEmail() -{ - global $URL_BASE; - - $email = htmlspecialchars($_SESSION["confirm_email"]); - - if (!isset($email)) { - header("Location: $URL_BASE/connexion"); - exit(); - } - - $user = User::fromEmail($email); - - if ($user === null) { - unset($_SESSION["confirm_email"]); - header("Location: $URL_BASE/connexion"); - exit(); - } - - Mailer::sendConfirmEmail($user); - - return false; -} - -require_once "server_files/views/connexion.php"; diff --git a/server_files/controllers/deconnexion.php b/server_files/controllers/deconnexion.php deleted file mode 100644 index eb04b0a..0000000 --- a/server_files/controllers/deconnexion.php +++ /dev/null @@ -1,14 +0,0 @@ - - -
- Déconnexion réussie ! -
- -getTournamentId()); - -if ($_SESSION["role"] == Role::ORGANIZER && !$tournament->organize($_SESSION["user_id"])) - require_once "server_files/403.php"; - -if ($team === null) - require_once "server_files/404.php"; - -if (isset($_POST["team_edit"])) { - $edit_team = new EditTeam($_POST); - try { - $edit_team->makeVerifications(); - $edit_team->updateTeam(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_POST["validate"])) { - $team->setValidationStatus(ValidationStatus::VALIDATED); - Mailer::sendValidateTeam($team, $_POST["message"]); -} -elseif (isset($_POST["unvalidate"])) { - $team->setValidationStatus(ValidationStatus::NOT_READY); - Mailer::sendUnvalidateTeam($team, $_POST["message"]); -} - -if (isset($_POST["select"])) { - $team->selectForFinal(true); - # $team->setValidationStatus(ValidationStatus::NOT_READY); - $sols = $tournament->getAllSolutions($team->getId()); - /** @var Solution $sol */ - foreach ($sols as $sol) { - $old_id = $sol->getFileId(); - do - $id = genRandomPhrase(64); - while (file_exists("$LOCAL_PATH/files/$id")); - - copy("$LOCAL_PATH/files/$old_id", "$LOCAL_PATH/files/$id"); - - $req = $DB->prepare("INSERT INTO `solutions`(`file_id`, `team`, `tournament`, `problem`) VALUES (?, ?, ?, ?);"); - $req->execute([$id, $team->getId(), $FINAL->getId(), $sol->getProblem()]); - } -} - -if (isset($_POST["download_zip"])) { - $final = isset($_POST["final"]); - $tournament_dest = $final ? $FINAL : $tournament; - - $file_name = getZipFile(DocumentType::PARENTAL_CONSENT, $tournament_dest->getId(), $team->getId()); - - header("Content-Type: application/zip"); - header("Content-Disposition: attachment; filename=\"Documents de l'équipe " . $team->getTrigram() . ".zip\""); - header("Content-Length: " . strval(filesize($file_name))); - - readfile($file_name); - - exit(); -} - -if (isset($_POST["select_tournament"])) { - $new_tournament = Tournament::fromId($_POST["select_tournament"]); - ensure($new_tournament != null, "Le tournoi indiqué n'existe pas."); - $team->setTournamentId($new_tournament->getId()); - $DB->prepare("UPDATE `documents` SET `tournament` = ? WHERE `team` = ?;")->execute([$tournament->getId(), $team->getId()]); - $DB->prepare("UPDATE `solutions` SET `tournament` = ? WHERE `team` = ?;")->execute([$tournament->getId(), $team->getId()]); - $DB->prepare("UPDATE `syntheses` SET `tournament` = ? WHERE `team` = ?;")->execute([$tournament->getId(), $team->getId()]); - foreach ($team->getParticipants() as $user) { - if ($user != null) - $DB->prepare("UPDATE `payments` SET `tournament` = ? WHERE `user` = ?;")->execute([$tournament->getId(), $user]); - } - foreach ($team->getEncadrants() as $user) { - if ($user != null) - $DB->prepare("UPDATE `payments` SET `tournament` = ? WHERE `user` = ?;")->execute([$tournament->getId(), $user]); - } - $tournament = $new_tournament; -} - -if (isset($_POST["delete_team"])) { - foreach ($team->getEncadrants() as $encadrant_id) { - quitTeam($encadrant_id); - } - foreach ($team->getParticipants() as $participant_id) { - quitTeam($participant_id); - } - - header("Location: /"); - return; - -} - -class EditTeam -{ - public $name; - public $trigram; - public $tournament_id; - private $team; - private $tournament; - - public function __construct($data) - { - global $team; - - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->trigram = strtoupper($this->trigram); - $this->team = $team; - $this->tournament = Tournament::fromId($this->tournament_id); - } - - public function makeVerifications() - { - ensure($this->name != "" && $this->name != null, "Veuillez spécifier un nom d'équipe."); - ensure($this->name == $this->team->getName() || !teamExists($this->name), "Une équipe existe déjà avec ce nom."); - ensure(preg_match("#^[A-Z]{3}$#", $this->trigram), "Le trigramme n'est pas valide."); - ensure($this->trigram == $this->team->getTrigram() || !trigramExists($this->trigram), "Une équipe a déjà choisi ce trigramme."); - ensure($this->tournament != null, "Le tournoi indiqué n'existe pas."); - ensure($this->tournament_id == $this->team->getTournamentId() || $_SESSION["role"] == Role::ADMIN, "Vous n'avez pas la permission pour changer cette équipe de tournoi."); - } - - public function updateTeam() - { - global $URL_BASE; - - $this->team->setName($this->name); - $this->team->setTrigram($this->trigram); - $this->team->setTournamentId($this->tournament_id); - - $_SESSION["tournament"] = $this->tournament; - - header("Location: $URL_BASE/equipe/$this->trigram"); - } -} - -$documents = $tournament->getAllDocuments($team->getId()); -$documents_final = null; - -if ($team->isSelectedForFinal()) - $documents_final = $FINAL->getAllDocuments($team->getId()); - -$emails = []; - -if ($_SESSION["role"] == Role::ORGANIZER || $_SESSION["role"] == Role::ADMIN) { - foreach ($team->getEncadrants() as $encadrant_id) { - $encadrant = User::fromId($encadrant_id); - if ($encadrant != null) { - $emails[] = $encadrant->getEmail(); - } - } - - foreach ($team->getParticipants() as $participant_id) { - $participant = User::fromId($participant_id); - if ($participant != null) { - $emails[] = $participant->getEmail(); - if ($participant->getResponsibleEmail() != null) { - $emails[] = $participant->getResponsibleEmail(); - } - } - } -} - -require_once "server_files/views/equipe.php"; diff --git a/server_files/controllers/index.php b/server_files/controllers/index.php deleted file mode 100644 index 5a23b80..0000000 --- a/server_files/controllers/index.php +++ /dev/null @@ -1,20 +0,0 @@ -getTeamId()); - -if ($_SESSION["role"] != Role::ADMIN) { - if ($_SESSION["role"] == Role::ORGANIZER) { - if (($user->getRole() == Role::PARTICIPANT || $user->getRole() == Role::PARTICIPANT) && ($team == null || $team->getTournamentId() == null || !Tournament::fromId($team->getTournamentId())->organize($_SESSION["user_id"]))) - require_once "server_files/403.php"; - } - elseif ($user->getId() != $_SESSION["user_id"]) - require_once "server_files/403.php"; -} - -if ($user === null) - require_once "server_files/404.php"; - -if ($team != null) { - $documents = $user->getAllDocuments($team->getTournamentId()); - $documents_final = $user->getAllDocuments($FINAL->getId()); - $payment = $user->getPayment(); - $tournament = Tournament::fromId($team->getTournamentId()); -} - -$has_error = false; -$error_message = null; - -if (isset($_POST["kick"])) { - if ($team == null) { - $has_error = true; - $error_message = "La personne à expulser n'est dans aucune équipe."; - } - else { - quitTeam($id); - $team = null; - } -} - -if (isset($_POST["attribute_team"])) { - $attribute_team = new AttributeTeam($_POST); - try { - $attribute_team->makeVerifications(); - $attribute_team->attribute(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_POST["validate_payment"])) { - $validate_payment = new ValidatePayment($_POST); - try { - $validate_payment->makeVerifications(); - $validate_payment->validate(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_POST["view_as"]) && $_SESSION["role"] == Role::ADMIN) { - if (!isset($_SESSION["admin"])) - $_SESSION["admin"] = $_SESSION["user_id"]; - $_SESSION["user_id"] = $user->getId(); - header("Location: /"); - exit(); -} - -if (isset($_POST["delete_account"]) && $team == null && $_SESSION["role"] == Role::ADMIN) { - $DB->prepare("DELETE FROM `documents` WHERE `user` = ?;")->execute([$user->getId()]); - $DB->prepare("DELETE FROM `organizers` WHERE `organizer` = ?;")->execute([$user->getId()]); - $DB->prepare("DELETE FROM `users` WHERE `id` = ?;")->execute([$user->getId()]); - header("Location: /"); - exit(); -} - -class AttributeTeam -{ - private $team_id; - private $team; - private $min_null_index; - - public function __construct($data) - { - $this->team_id = htmlspecialchars($data["team"]); - $this->team = Team::fromId($this->team_id); - } - - public function makeVerifications() - { - global $user; - - ensure($user->getConfirmEmailToken() == null, "Ce participant n'a pas encore validé son adresse e-mail."); - ensure($this->team_id != "no_team", "Vous n'avez pas choisi d'équipe."); - ensure($this->team != null, "Cette équipe n'existe pas."); - ensure($user->getTeamId() <= 0, "Cette personne est déjà dans une équipe !"); - ensure($this->team->getValidationStatus() == ValidationStatus::NOT_READY, "Cette équipe est déjà validée ou en cours de validation."); - - $role = $user->getRole(); - for ($i = 1; $i <= $role == Role::ENCADRANT ? 3 : 6; ++$i) { - if (($role == Role::PARTICIPANT ? $this->team->getParticipants()[$i - 1] : $this->team->getEncadrants()[$i]) == NULL) - break; - } - - $this->min_null_index = $i; - - ensure($role == Role::PARTICIPANT && $this->min_null_index <= 6 || $role == Role::ENCADRANT && $this->min_null_index <= 2, - "Il n'y a plus de place pour vous dans l'équipe."); - } - - public function attribute() - { - global $user, $team; - - $user->setTeamId($this->team->getId()); - - if ($user->getRole() == Role::ENCADRANT) - $this->team->setEncadrant($this->min_null_index, $user->getId()); - else - $this->team->setParticipant($this->min_null_index, $user->getId()); - - Mailer::sendJoinTeamMail($user, $this->team, Tournament::fromId($this->team->getTournamentId())); - - $team = $this->team; - - global $documents, $payment, $tournament; - - $documents = $user->getAllDocuments($team->getTournamentId()); - $payment = $user->getPayment(); - $tournament = Tournament::fromId($team->getTournamentId()); - } -} - -class ValidatePayment -{ - private $accept, $reject; - private $message; - private $payment; - - public function __construct($data) - { - global $user; - - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->payment = $user->getPayment(); - } - - public function makeVerifications() - { - ensure($this->payment->getValidationStatus() == ValidationStatus::WAITING, "Le paiement n'était pas en attente."); - ensure(isset($this->accept) ^ isset($this->reject), "La sélection de validation est invalide."); - } - - public function validate() - { - global $user, $team, $tournament; - - if ($this->accept) - $this->payment->setValidationStatus(ValidationStatus::VALIDATED); - else - $this->payment->setValidationStatus(ValidationStatus::NOT_READY); - - Mailer::sendValidatePayment($user, $team, $tournament, $this->payment, $this->message); - } -} - -require_once "server_files/views/informations.php"; diff --git a/server_files/controllers/inscription.php b/server_files/controllers/inscription.php deleted file mode 100644 index d0ab6f3..0000000 --- a/server_files/controllers/inscription.php +++ /dev/null @@ -1,99 +0,0 @@ -makeVerifications(); - $user->register(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class NewUser -{ - public $email; - public $first_name; - public $surname; - public $birth_date; - public $gender; - public $address = ""; - public $postal_code; - public $city = ""; - public $country; - public $phone_number; - public $role; - public $school; - public $class; - public $responsible_name; - public $responsible_phone; - public $responsible_email; - public $description; - public $confirm_email_token; - private $password; - private $confirm_password; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - } - - public function makeVerifications() - { - global $YEAR; - - ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail entrée est invalide."); - $this->email = strtolower($this->email); - ensure(!userExists($this->email), "Un compte existe déjà avec cette adresse e-mail."); - ensure(strlen($this->password) >= 8, "Le mot de passe doit comporter au moins 8 caractères."); - ensure($this->password == $this->confirm_password, "Les deux mots de passe sont différents."); - ensure($this->surname != "", "Le nom de famille est obligatoire."); - ensure($this->first_name != "", "Le prénom est obligatoire."); - ensure(dateWellFormed($this->birth_date), "La date de naissance est invalide."); - ensure($this->birth_date < $YEAR . "-01-01", "Vous devez être né."); - ensure($this->gender == "M" || $this->gender == "F", "Merci de spécifier un genre."); - ensure(preg_match("#^[0-9]{4}[0-9]?$#", $this->postal_code) && intval($this->postal_code) >= 01000 && intval($this->postal_code) <= 95999, "Le code postal est invalide."); - if ($this->country == "") - $this->country = "France"; - ensure(strlen($this->phone_number) >= 10 && strlen($this->phone_number) <= 20, "Le numéro de téléphone est invalide."); - $this->role = Role::fromName(strtoupper($this->role)); - - if ($this->role == Role::PARTICIPANT) { - $this->class = SchoolClass::fromName(strtoupper($this->class)); - if ($this->birth_date > strval($YEAR - 18) . "04-01") { - ensure($this->responsible_name != "", "Veuillez spécifier un responsable légal."); - ensure(strlen($this->responsible_phone) >= 10, "Veuillez rentrer le numéro de téléphone de votre responsable légal."); - ensure(filter_var($this->responsible_email, FILTER_VALIDATE_EMAIL), "Veuillez spécifier un responsable légal."); - } - } - else { - $this->class = SchoolClass::ADULT; - } - - if (count(User::getAllUsers()) == 0) - $this->role = Role::ADMIN; - - $this->confirm_email_token = genRandomPhrase(64); - } - - public function register() - { - global $DB, $YEAR; - - $req = $DB->prepare("INSERT INTO `users`(`email`, `pwd_hash`, `confirm_email`, `surname`, `first_name`, `birth_date`, `gender`, - `address`, `postal_code`, `city`, `country`, `phone_number`, `school`, `class`, `role`, `description`, `responsible_name`, `responsible_phone`, `responsible_email`, `year`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); - $req->execute([$this->email, password_hash($this->password, PASSWORD_BCRYPT), $this->confirm_email_token, $this->surname, $this->first_name, $this->birth_date, $this->gender, $this->address, - $this->postal_code, $this->city, $this->country, $this->phone_number, $this->school, SchoolClass::getName($this->class), Role::getName($this->role), $this->description, $this->responsible_name, $this->responsible_phone, $this->responsible_email, $YEAR]); - - Mailer::sendRegisterMail($this); - } -} - -require_once "server_files/views/inscription.php"; diff --git a/server_files/controllers/instructions.php b/server_files/controllers/instructions.php deleted file mode 100644 index 20b58b4..0000000 --- a/server_files/controllers/instructions.php +++ /dev/null @@ -1,36 +0,0 @@ -getEffectiveTournament(); -} - -$tex = preg_replace("#{TOURNAMENT_NAME}#", $tournament->getName(), $tex); -$tex = preg_replace("#{PLACE}#", $tournament->getPlace(), $tex); -$tex = preg_replace("#{PRICE}#", $tournament->getPrice(), $tex); -$tex = preg_replace("#{END_PAYMENT_DATE}#", strftime("%d %B", strtotime($tournament->getInscriptionDate())), $tex); -$tex = preg_replace("#{YEAR}#", $YEAR, $tex); - -shell_exec("mkdir tmp"); -file_put_contents("tmp/file.tex", $tex); -shell_exec("pdflatex -synctex=1 -interaction=nonstopmode -shell-escape -output-directory=tmp tmp/file.tex"); -header("Content-type: application/pdf"); -readfile("tmp/file.pdf"); -shell_exec("rm -rf tmp"); - -exit(0); \ No newline at end of file diff --git a/server_files/controllers/mon_compte.php b/server_files/controllers/mon_compte.php deleted file mode 100644 index 71d26cf..0000000 --- a/server_files/controllers/mon_compte.php +++ /dev/null @@ -1,220 +0,0 @@ -getTournamentId()); - -$has_error = false; -$error_message = null; - -if (isset($_POST["update_account"])) { - $my_account = new MyAccount($_POST); - try { - $my_account->makeVerifications(); - $my_account->updateAccount(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_POST["update_password"])) { - $new_password = new NewPassword($_POST); - try { - $new_password->makeVerifications(); - $new_password->updatePassword(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_POST["send_document"])) { - $send_document = new SendDocument(); - try { - $send_document->makeVerifications(); - $send_document->sendDocument(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class MyAccount -{ - public $email; - public $surname; - public $first_name; - public $birth_date; - public $gender; - public $address; - public $postal_code; - public $city; - public $country; - public $phone_number; - public $school; - public $class; - public $responsible_name; - public $responsible_phone; - public $responsible_email; - public $description; - private $user; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->user = $_SESSION["user"]; - - $keys = ["email", "surname", "first_name", "birth_date", "gender", "address", "postal_code", "city", "country", "phone_number", - "school", "class", "responsible_name", "responsible_phone", "responsible_email", "description"]; - - if ($this->user->getRole() == Role::PARTICIPANT) - $this->class = SchoolClass::fromName(strtoupper($this->class)); - else - $this->class = SchoolClass::ADULT; - - foreach ($keys as $key) - $this->$key = $this->$key != null && $this->$key != "" ? $this->$key : $this->user->$key; - } - - public function makeVerifications() - { - global $YEAR; - - ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail entrée est invalide."); - $this->email = strtolower($this->email); - ensure($this->email == $this->user->getEmail() || !userExists($this->email), "Un compte existe déjà avec cette adresse e-mail."); - ensure(dateWellFormed($this->birth_date), "La date de naissance est invalide."); - ensure($this->birth_date < $YEAR . "-01-01", "Vous devez être né."); - ensure($this->gender == "M" || $this->gender == "F", "Merci de spécifier un genre."); - ensure(preg_match("#^[0-9]{4}[0-9]?$#", $this->postal_code) && intval($this->postal_code) >= 01000 && intval($this->postal_code) <= 95999, "Le code postal est invalide."); - ensure(strlen($this->phone_number) >= 10, "Le numéro de téléphone est invalide."); - - if ($this->user->getRole() == Role::PARTICIPANT) { - if ($this->birth_date > strval($YEAR - 18) . "04-01") { - ensure($this->responsible_name != "", "Veuillez spécifier un responsable légal."); - ensure(strlen($this->responsible_phone) >= 10, "Veuillez rentrer le numéro de téléphone de votre responsable légal."); - ensure(filter_var($this->responsible_email, FILTER_VALIDATE_EMAIL), "Veuillez spécifier un responsable légal."); - } - } - } - - public function updateAccount() - { - $this->user->setSurname($this->surname); - $this->user->setFirstName($this->first_name); - $this->user->setBirthDate($this->birth_date); - $this->user->setGender($this->gender); - $this->user->setAddress($this->address); - $this->user->setPostalCode($this->postal_code); - $this->user->setCity($this->city); - $this->user->setCountry($this->country); - $this->user->setPhoneNumber($this->phone_number); - $this->user->setSchool($this->school); - $this->user->setClass($this->class); - $this->user->setResponsibleName($this->responsible_name); - $this->user->setResponsiblePhone($this->responsible_phone); - $this->user->setResponsibleEmail($this->responsible_email); - $this->user->setDescription($this->description); - - if ($this->email != $this->user->getEmail()) { - $this->user->setEmail($this->email); - $this->user->setConfirmEmailToken(genRandomPhrase(64)); - - Mailer::sendChangeEmailAddressMail($this->user); - } - } -} - -class NewPassword -{ - private $user; - private $old_password; - private $new_password; - private $confirm_password; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->user = $_SESSION["user"]; - } - - public function makeVerifications() - { - ensure($this->user->checkPassword($this->old_password), "L'ancien mot de passe est incorrect."); - ensure(strlen($this->new_password) >= 8, "Le mot de passe doit comporter au moins 8 caractères."); - ensure($this->new_password == $this->confirm_password, "Les deux mots de passe sont différents."); - } - - public function updatePassword() - { - $this->user->setPassword($this->new_password); - - Mailer::sendChangePasswordMail($this->user); - } -} - -class SendDocument -{ - private $file; - private $type; - - public function __construct() - { - $this->file = $_FILES["document"]; - $this->type = strtoupper(htmlspecialchars($_POST["type"])); - } - - public function makeVerifications() - { - global $LOCAL_PATH; - - ensure($this->file["size"] <= 2e6, "Le fichier doit peser moins que 2 Mo."); - ensure(!$this->file["error"], "Une erreur est survenue."); - $mime = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file["tmp_name"]); - ensure($mime == "application/pdf" || $mime = "image/png" || $mime == "image/jpeg", "Le fichier doit être au format PDF."); - ensure(is_dir("$LOCAL_PATH/files") || mkdir("$LOCAL_PATH/files"), "Un problème est survenue dans l'envoi du fichier. Veuillez contacter l'administrateur du serveur."); - } - - public function sendDocument() - { - global $LOCAL_PATH, $DB, $FINAL; - - do - $id = genRandomPhrase(64); - while (file_exists("$LOCAL_PATH/files/$id")); - - if (!rename($this->file["tmp_name"], "$LOCAL_PATH/files/$id")) - throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier."); - - $req = $DB->prepare("INSERT INTO `documents`(`file_id`, `user`, `team`, `tournament`, `type`) - VALUES (?, ?, ?, ?, ?);"); - $req->execute([$id, $this->type == DocumentType::getName(DocumentType::MOTIVATION_LETTER) ? -1 : $_SESSION["user_id"], $_SESSION["team"]->getId(), - $_SESSION["team"]->isSelectedForFinal() ? $FINAL->getId() : $_SESSION["team"]->getTournamentId(), $this->type]); - } -} - -if ($team != null) { - $documents = $user->getAllDocuments($team->getTournamentId()); - if ($team->isSelectedForFinal()) - $documents_final = $user->getAllDocuments($FINAL->getId()); -} - -require_once "server_files/views/mon_compte.php"; diff --git a/server_files/controllers/mon_equipe.php b/server_files/controllers/mon_equipe.php deleted file mode 100644 index e165dcb..0000000 --- a/server_files/controllers/mon_equipe.php +++ /dev/null @@ -1,193 +0,0 @@ -makeVerifications(); - $my_team->updateTeam(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -if (isset($_SESSION["user_id"]) && isset($_SESSION["team"]) && $_SESSION["team"] !== null) { - /** - * @var User $user - * @var Team $team - */ - $user = $_SESSION["user"]; - $team = $_SESSION["team"]; - - $tournament = Tournament::fromId($team->getTournamentId()); - $documents = $tournament->getAllDocuments($team->getId()); - if ($team->isSelectedForFinal()) - $documents_final = $FINAL->getAllDocuments($team->getId()); -} -else - require_once "server_files/403.php"; - -if (isset($_POST["request_validation"])) { - if (!canValidate($team, $tournament)) - $error_message = "Votre équipe ne peut pas demander la validation : il manque soit des participants, soit des documents."; - else { - $team->setValidationStatus(ValidationStatus::WAITING); - Mailer::sendRequestValidationMail($team, $team->isSelectedForFinal() ? $FINAL : $tournament); - } -} - -$DUMPS = [ - ["TKT", 6, "PGA", 3, "IRD", 1], - ["OUI", 8, "LEP", 1, "REX", 7], - ["ASP", 1, "ABC", 3, "TDP", 6], - ["GIF", 8, "ETM", 1, "LPC", 3], - ["MST", 6, "LQF", 1, "WAL", 2], -]; - -$DUMPS_2 = [ - ["TKT", 4, "PGA", 1, "IRD", 6], - ["LEP", 6, "OUI", 5, "REX", 8], - ["ASP", 5, "ABC", 8, "TDP", 4], - ["ETM", 8, "LPC", 4, "GIF", 6], - ["MST", 5, "LQF", 4, "WAL", 8], -]; - -foreach ($DUMPS as $dump) { - $team1 = Team::fromTrigram($dump[0]); - $team2 = Team::fromTrigram($dump[2]); - $team3 = Team::fromTrigram($dump[4]); - $problem1 = $dump[1]; - $problem2 = $dump[3]; - $problem3 = $dump[5]; - - $req1 = $DB->prepare("SELECT * FROM `solutions` WHERE `team` = ? AND `problem` = ? ORDER BY uploaded_at DESC LIMIT 1"); - $req1->execute([$team1->getId(), $problem1]); - $data1 = $req1->fetch(); - $sol1 = Solution::fromData($data1); - $req2 = $DB->prepare("SELECT * FROM `solutions` WHERE `team` = ? AND `problem` = ? ORDER BY uploaded_at DESC LIMIT 1"); - $req2->execute([$team2->getId(), $problem2]); - $data2 = $req2->fetch(); - $sol2 = Solution::fromData($data2); - $req3 = $DB->prepare("SELECT * FROM `solutions` WHERE `team` = ? AND `problem` = ? ORDER BY uploaded_at DESC LIMIT 1"); - $req3->execute([$team3->getId(), $problem3]); - $data3 = $req3->fetch(); - $sol3 = Solution::fromData($data3); - - $req1 = $DB->prepare("UPDATE `teams` SET `opposed_problem` = ?, `rapported_problem` = ? WHERE `id` = ?;"); - $req1->execute([$sol2->getFileId(), $sol3->getFileId(), $team1->getId()]); - - $req2 = $DB->prepare("UPDATE `teams` SET `opposed_problem` = ?, `rapported_problem` = ? WHERE `id` = ?;"); - $req2->execute([$sol3->getFileId(), $sol1->getFileId(), $team2->getId()]); - - $req3 = $DB->prepare("UPDATE `teams` SET `opposed_problem` = ?, `rapported_problem` = ? WHERE `id` = ?;"); - $req3->execute([$sol1->getFileId(), $sol2->getFileId(), $team3->getId()]); -} - -foreach ($DUMPS_2 as $dump) { - $team1 = Team::fromTrigram($dump[0]); - $team2 = Team::fromTrigram($dump[2]); - $team3 = Team::fromTrigram($dump[4]); - $problem1 = $dump[1]; - $problem2 = $dump[3]; - $problem3 = $dump[5]; - - $req1 = $DB->prepare("SELECT * FROM `solutions` WHERE `team` = ? AND `problem` = ? ORDER BY uploaded_at DESC LIMIT 1"); - $req1->execute([$team1->getId(), $problem1]); - $data1 = $req1->fetch(); - $sol1 = Solution::fromData($data1); - $req2 = $DB->prepare("SELECT * FROM `solutions` WHERE `team` = ? AND `problem` = ? ORDER BY uploaded_at DESC LIMIT 1"); - $req2->execute([$team2->getId(), $problem2]); - $data2 = $req2->fetch(); - $sol2 = Solution::fromData($data2); - $req3 = $DB->prepare("SELECT * FROM `solutions` WHERE `team` = ? AND `problem` = ? ORDER BY uploaded_at DESC LIMIT 1"); - $req3->execute([$team3->getId(), $problem3]); - $data3 = $req3->fetch(); - $sol3 = Solution::fromData($data3); - - $req1 = $DB->prepare("UPDATE `teams` SET `opposed_problem_2` = ?, `rapported_problem_2` = ? WHERE `id` = ?;"); - $req1->execute([$sol2->getFileId(), $sol3->getFileId(), $team1->getId()]); - - $req2 = $DB->prepare("UPDATE `teams` SET `opposed_problem_2` = ?, `rapported_problem_2` = ? WHERE `id` = ?;"); - $req2->execute([$sol3->getFileId(), $sol1->getFileId(), $team2->getId()]); - - $req3 = $DB->prepare("UPDATE `teams` SET `opposed_problem_2` = ?, `rapported_problem_2` = ? WHERE `id` = ?;"); - $req3->execute([$sol1->getFileId(), $sol2->getFileId(), $team3->getId()]); -} - - -$req = $DB->prepare("SELECT opposed_problem, rapported_problem, opposed_problem_2, rapported_problem_2 FROM teams WHERE id = ?;"); -$req->execute([$team->getId()]); -$data = $req->fetch(); - -$opposed_solution = Solution::fromId($data["opposed_problem"]); -$rapported_solution = Solution::fromId($data["rapported_problem"]); -$opposed_solution_2 = Solution::fromId($data["opposed_problem_2"]); -$rapported_solution_2 = Solution::fromId($data["rapported_problem_2"]); - -class MyTeam -{ - public $name; - public $trigram; - public $tournament_id; - private $team; - private $tournament; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->trigram = strtoupper($this->trigram); - $this->team = $_SESSION["team"]; - $this->tournament = Tournament::fromId($this->tournament_id); - } - - public function makeVerifications() - { - ensure($this->name != "" && $this->name != null, "Veuillez spécifier un nom d'équipe."); - ensure($this->name == $this->team->getName() || !teamExists($this->name), "Une équipe existe déjà avec ce nom."); - ensure(preg_match("#^[A-Z]{3}$#", $this->trigram), "Le trigramme n'est pas valide."); - ensure($this->trigram == $this->team->getTrigram() || !trigramExists($this->trigram), "Une équipe a déjà choisi ce trigramme."); - ensure($this->tournament != null, "Le tournoi indiqué n'existe pas."); - ensure(date("Y-m-d H:i:s") <= $this->tournament->getInscriptionDate(), "Les inscriptions sont terminées."); - ensure($this->team->getValidationStatus() == ValidationStatus::NOT_READY, "Votre équipe est déjà validée ou en cours de validation."); - } - - public function updateTeam() - { - global $URL_BASE, $DB; - - $this->team->setName($this->name); - $this->team->setTrigram($this->trigram); - $this->team->setTournamentId($this->tournament_id); - - $DB->prepare("UPDATE `documents` SET `tournament` = ? WHERE `team` = ?;")->execute([$this->tournament_id, $this->team->getId()]); - $DB->prepare("UPDATE `solutions` SET `tournament` = ? WHERE `team` = ?;")->execute([$this->tournament_id, $this->team->getId()]); - $DB->prepare("UPDATE `syntheses` SET `tournament` = ? WHERE `team` = ?;")->execute([$this->tournament_id, $this->team->getId()]); - foreach ($this->team->getParticipants() as $user) { - if ($user != null) - $DB->prepare("UPDATE `payments` SET `tournament` = ? WHERE `user` = ?;")->execute([$this->tournament_id, $user]); - } - foreach ($this->team->getEncadrants() as $user) { - if ($user != null) - $DB->prepare("UPDATE `payments` SET `tournament` = ? WHERE `user` = ?;")->execute([$this->tournament_id, $user]); - } - - $_SESSION["tournament"] = $this->tournament; - - header("Location: $URL_BASE/mon-equipe"); - } -} - -require_once "server_files/views/mon_equipe.php"; diff --git a/server_files/controllers/organisateurs.php b/server_files/controllers/organisateurs.php deleted file mode 100644 index bfe340e..0000000 --- a/server_files/controllers/organisateurs.php +++ /dev/null @@ -1,8 +0,0 @@ -getEffectiveTournament(); -$payment = $user->getPayment(); - -if ($team->getValidationStatus() != ValidationStatus::VALIDATED) - require_once "server_files/403.php"; - -if (isset($_POST["pay"])) { - $pay = new Pay($_POST); - try { - $pay->makeVerifications(); - $pay->submit(); - } - catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class Pay { - private $method; - private $infos; - private $scholarship; - - public function __construct($data) - { - foreach ($data as $key => $value) - $this->$key = htmlspecialchars($value); - - $this->method = PaymentMethod::fromName(strtoupper($this->method)); - - $this->scholarship = $_FILES["scholarship"]; - } - - public function makeVerifications() - { - global $payment; - - ensure($payment->getValidationStatus() == ValidationStatus::NOT_READY, "Un paiement est déjà initié."); - ensure($this->method != PaymentMethod::NOT_PAID, "Vous n'avez pas payé."); - ensure($this->method == PaymentMethod::SCHOLARSHIP || ($this->infos != null && strlen($this->infos) > 0), "Merci d'indiquer des informations pour retrouver votre paiement."); - ensure($this->method != PaymentMethod::SCHOLARSHIP || ($this->scholarship != null && !$this->scholarship["error"]), "Si vous êtes boursier, vous devez indiquer votre notifcation de bourse (une erreur est survenue)."); - } - - public function submit() - { - global $DB, $LOCAL_PATH, $payment, $user, $team, $tournament; - - $payment->setMethod($this->method); - $payment->setAmount($this->method == PaymentMethod::SCHOLARSHIP ? 0 : $tournament->getPrice()); - $payment->setValidationStatus(ValidationStatus::WAITING); - if ($this->method == PaymentMethod::SCHOLARSHIP) { - do - $id = genRandomPhrase(64); - while (file_exists("$LOCAL_PATH/files/$id")); - - if (!rename($this->scholarship["tmp_name"], "$LOCAL_PATH/files/$id")) - throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier."); - - $req = $DB->prepare("INSERT INTO `documents`(`file_id`, `user`, `team`, `tournament`, `type`) - VALUES (?, ?, ?, ?, ?);"); - $req->execute([$id, $_SESSION["user_id"], $_SESSION["team"]->getId(), $tournament->getId(), DocumentType::getName(DocumentType::SCHOLARSHIP)]); - $payment->setTransactionInfos($id); - } - else - $payment->setTransactionInfos($this->infos); - - Mailer::requestPaymentValidation($user, $team, $tournament, $payment); - } -} - -require_once "server_files/views/paiement.php"; \ No newline at end of file diff --git a/server_files/controllers/profils.php b/server_files/controllers/profils.php deleted file mode 100644 index 51dc8b9..0000000 --- a/server_files/controllers/profils.php +++ /dev/null @@ -1,16 +0,0 @@ -getEmail(); -} - -require_once "server_files/views/profils.php"; \ No newline at end of file diff --git a/server_files/controllers/rejoindre_equipe.php b/server_files/controllers/rejoindre_equipe.php deleted file mode 100644 index c7db182..0000000 --- a/server_files/controllers/rejoindre_equipe.php +++ /dev/null @@ -1,68 +0,0 @@ -makeVerifications(); - $join_team->joinTeam(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -class JoinTeam -{ - private $access_code; - private $team; - private $min_null_index; - - public function __construct($data) - { - $this->access_code = strtolower(htmlspecialchars($data["access_code"])); - $this->team = Team::fromAccessCode($this->access_code); - } - - public function makeVerifications() - { - ensure(preg_match("#[a-z0-9]{6}#", $this->access_code), "Le code d'accès doit comporter 6 caractères alphanumériques."); - ensure($this->team != null, "Ce code d'accès est invalide."); - ensure($this->team->getValidationStatus() == ValidationStatus::NOT_READY, "Cette équipe est déjà validée ou en cours de validation, vous ne pouvez pas la rejoindre."); - - for ($i = 1; $i <= $_SESSION["role"] == Role::PARTICIPANT ? 6 : 3; ++$i) { - if (($_SESSION["role"] == Role::PARTICIPANT ? $this->team->getParticipants()[$i - 1] : $this->team->getEncadrants()[$i - 1]) == NULL) - break; - } - - $this->min_null_index = $i; - - ensure($_SESSION["role"] == Role::PARTICIPANT && $this->min_null_index <= 6 || $_SESSION["role"] == Role::ENCADRANT && $this->min_null_index <= 3, "Il n'y a plus de place pour vous dans l'équipe."); - } - - public function joinTeam() - { - global $team; - - $user = $_SESSION["user"]; - - $user->setTeamId($this->team->getId()); - - if ($_SESSION["role"] == Role::ENCADRANT) - $this->team->setEncadrant($this->min_null_index, $user->getId()); - else - $this->team->setParticipant($this->min_null_index, $user->getId()); - - $team = $_SESSION["team"] = $this->team; - $tournament = $_SESSION["tournament"] = Tournament::fromId($this->team->getTournamentId()); - - Mailer::sendJoinTeamMail($user, $this->team, $tournament); - } -} - -require_once "server_files/views/rejoindre_equipe.php"; diff --git a/server_files/controllers/solutions.php b/server_files/controllers/solutions.php deleted file mode 100644 index 66262b7..0000000 --- a/server_files/controllers/solutions.php +++ /dev/null @@ -1,72 +0,0 @@ -getTournamentId()); - -$has_error = false; -$error_message = null; - -if (isset($_POST["send_solution"])) { - $save_solution = new SaveSolution(); - try { - $save_solution->makeVerifications(); - $save_solution->saveSolution(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -$solutions = $tournament->getAllSolutions($team->getId()); -$solutions_final = null; -if ($team->isSelectedForFinal()) - $solutions_final = $FINAL->getAllSolutions($team->getId()); - -class SaveSolution -{ - private $problem; - private $file; - - public function __construct() - { - $this->file = $_FILES["solution"]; - $this->problem = htmlspecialchars($_POST["problem"]); - } - - public function makeVerifications() - { - global $LOCAL_PATH; - - ensure(preg_match("#[1-9]#", $this->problem), "Le numéro du problème est invalide."); - ensure($this->file["size"] <= 2e6, "Le fichier doit peser moins que 2 Mo."); - ensure(!$this->file["error"], "Une erreur est survenue."); - ensure(finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file["tmp_name"]) == "application/pdf", "Le fichier doit être au format PDF."); - ensure(is_dir("$LOCAL_PATH/files") || mkdir("$LOCAL_PATH/files"), "Un problème est survenue dans l'envoi du fichier. Veuillez contacter l'administrateur du serveur."); - } - - public function saveSolution() - { - global $LOCAL_PATH, $DB, $team, $tournament, $FINAL; - - do - $id = genRandomPhrase(64); - while (file_exists("$LOCAL_PATH/files/$id")); - - if (!rename($this->file["tmp_name"], "$LOCAL_PATH/files/$id")) - throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier."); - - $req = $DB->prepare("INSERT INTO `solutions`(`file_id`, `team`, `tournament`, `problem`) VALUES (?, ?, ?, ?);"); - $req->execute([$id, $team->getId(), $team->isSelectedForFinal() ? $FINAL->getId() : $tournament->getId(), $this->problem]); - - return false; - } -} - -require_once "server_files/views/solutions.php"; diff --git a/server_files/controllers/solutions_orga.php b/server_files/controllers/solutions_orga.php deleted file mode 100644 index 945c9f8..0000000 --- a/server_files/controllers/solutions_orga.php +++ /dev/null @@ -1,24 +0,0 @@ -getName() . ".zip\""); - header("Content-Length: " . strval(filesize($file_name))); - - readfile($file_name); - - exit(); -} - -$user = $_SESSION["user"]; -$tournaments = $_SESSION["role"] == Role::ADMIN ? Tournament::getAllTournaments() : $user->getOrganizedTournaments(); - -require_once "server_files/views/solutions_orga.php"; diff --git a/server_files/controllers/syntheses.php b/server_files/controllers/syntheses.php deleted file mode 100644 index 804618d..0000000 --- a/server_files/controllers/syntheses.php +++ /dev/null @@ -1,73 +0,0 @@ -getTournamentId()); - -if (isset($_POST["send_synthesis"])) { - $save_synthesis = new SaveSynthesis(); - try { - $save_synthesis->makeVerifications(); - $save_synthesis->saveSynthesis(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -$syntheses = $tournament->getAllSyntheses($team->getId()); -$syntheses_final = null; -if ($team->isSelectedForFinal()) - $syntheses_final = $FINAL->getAllSyntheses($team->getId()); - -class SaveSynthesis -{ - private $dest; - private $round; - private $file; - - public function __construct() - { - $this->file = $_FILES["synthese"]; - $this->round = htmlspecialchars($_POST["round"]); - $this->dest = DestType::fromName(strtoupper(htmlspecialchars($_POST["dest"]))); - } - - public function makeVerifications() - { - global $LOCAL_PATH, $tournament; - - ensure($this->dest != DestType::DEFENSEUR, "La source est invalide."); - ensure($this->round == 1 || $this->round == 2, "Le tour est invalide."); - $now = date("Y-m-d H:i"); - ensure($this->round == 1 && $now < $tournament->getSynthesesDate() || $this->round == 2 && $now < $tournament->getSynthesesDate2(), "Vous ne pouvez plus rendre de note de synthèse pour le tour $this->round."); - ensure($this->file["size"] <= 2e6, "Le fichier doit peser moins que 2 Mo."); - ensure(!$this->file["error"], "Une erreur est survenue."); - ensure(finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file["tmp_name"]) == "application/pdf", "Le fichier doit être au format PDF."); - ensure(is_dir("$LOCAL_PATH/files") || mkdir("$LOCAL_PATH/files"), "Un problème est survenue dans l'envoi du fichier. Veuillez contacter l'administrateur du serveur."); - } - - public function saveSynthesis() - { - global $LOCAL_PATH, $DB, $team, $tournament, $FINAL; - do - $id = genRandomPhrase(64); - while (file_exists("$LOCAL_PATH/files/$id")); - - if (!rename($this->file["tmp_name"], "$LOCAL_PATH/files/$id")) - throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier."); - - $req = $DB->prepare("INSERT INTO `syntheses`(`file_id`, `team`, `tournament`, `round`, `dest`) VALUES (?, ?, ?, ?, ?);"); - $req->execute([$id, $team->getId(), $team->isSelectedForFinal() ? $FINAL->getId() : $tournament->getId(), $this->round, $this->dest]); - - return false; - } -} - -require_once "server_files/views/syntheses.php"; diff --git a/server_files/controllers/syntheses_orga.php b/server_files/controllers/syntheses_orga.php deleted file mode 100644 index c4415e2..0000000 --- a/server_files/controllers/syntheses_orga.php +++ /dev/null @@ -1,22 +0,0 @@ -getName() . ".zip\""); - header("Content-Length: " . filesize($file_name)); - - readfile($file_name); - - exit(); -} - -$user = $_SESSION["user"]; -$tournaments = $_SESSION["role"] == Role::ADMIN ? Tournament::getAllTournaments() : $user->getOrganizedTournaments(); - -require_once "server_files/views/syntheses_orga.php"; \ No newline at end of file diff --git a/server_files/controllers/tournoi.php b/server_files/controllers/tournoi.php deleted file mode 100644 index e34bb9a..0000000 --- a/server_files/controllers/tournoi.php +++ /dev/null @@ -1,167 +0,0 @@ -organize($_SESSION["user_id"])) - require_once "server_files/403.php"; - -$has_error = false; -$error_message = null; - -if (isset($_POST["edit_tournament"])) { - $update_tournament = new UpdateTournament($_POST); - try { - $update_tournament->makeVerifications(); - $update_tournament->updateTournament(); - } catch (AssertionError $e) { - $has_error = true; - $error_message = $e->getMessage(); - } -} - -$orgas = $tournament->getOrganizers(); -$teams = $tournament->getAllTeams(); - -class UpdateTournament -{ - public $name; - public $organizers; - public $size; - public $place; - public $price; - public $date_start; - public $date_end; - public $date_inscription; - public $time_inscription; - public $date_solutions; - public $time_solutions; - public $date_syntheses; - public $time_syntheses; - public $date_solutions_2; - public $time_solutions_2; - public $date_syntheses_2; - public $time_syntheses_2; - public $description; - public $final; - - public function __construct($data) - { - global $tournament; - - foreach ($data as $key => $value) - $this->$key = ($key == "organizers" ? $value : htmlspecialchars($value)); - - if ($_SESSION["role"] != Role::ADMIN) { - $this->organizers = []; - /** @var User $organizer */ - foreach ($tournament->getOrganizers() as $organizer) - $this->organizers[] = $organizer->getId(); - } - } - - public function makeVerifications() - { - global $tournament; - - ensure($this->name != null && $this->name != "", "Le nom est invalide."); - ensure($this->name == $tournament->getName() || !tournamentExists($this->name), "Un tournoi existe déjà avec ce nom."); - ensure(sizeof($this->organizers) > 0, "Aucun organisateur n'a été choisi."); - - $orgas = []; - foreach ($this->organizers as $orga_id) { - $orga = User::fromId($orga_id); - ensure($orga != null, "Un organisateur spécifié n'existe pas."); - ensure($orga->getRole() == Role::ORGANIZER || $orga->getRole() == Role::ADMIN, "Une personne indiquée ne peut pas organiser de tournoi."); - $orgas[] = $orga; - } - $this->organizers = $orgas; - - ensure(preg_match("#[0-9]*#", $this->size), "Le nombre d'équipes indiqué n'est pas un nombre valide."); - $this->size = intval($this->size); - ensure($this->size >= 3 && $this->size <= 15, "Un tournoi doit avoir au moins 3 et au plus 15 équipes."); - - ensure(preg_match("#[0-9]*#", $this->price), "Le tarif pour les participants n'est pas un entier valide."); - $this->price = intval($this->price); - ensure($this->price >= 0, "Le TFJM² ne va pas payer les élèves pour venir."); - ensure($this->price <= 50, "Soyons raisonnable sur le prix."); - - ensure(dateWellFormed($this->date_start), "La date de début n'est pas valide."); - ensure(dateWellFormed($this->date_end), "La date de fin n'est pas valide."); - ensure(dateWellFormed($this->date_inscription . " " . $this->time_inscription), "La date de clôture des inscriptions n'est pas valide."); - ensure(dateWellFormed($this->date_solutions . " " . $this->time_solutions), "La date limite de remise des solutions n'est pas valide."); - ensure(dateWellFormed($this->date_syntheses . " " . $this->time_syntheses), "La date limite de remise des notes de synthèse pour le tour 1 n'est pas valide."); - ensure(dateWellFormed($this->date_solutions_2 . " " . $this->time_solutions_2), "La date limite de visibilité des solutions du tour 2 n'est pas valide."); - ensure(dateWellFormed($this->date_syntheses_2 . " " . $this->time_syntheses_2), "La date limite de remise des notes de synthèse pour le tour 2 n'est pas valide."); - } - - public function updateTournament() - { - global $URL_BASE, $tournament; - - $tournament->setName($this->name); - $tournament->setSize($this->size); - $tournament->setPlace($this->place); - $tournament->setPrice($this->price); - $tournament->setStartDate($this->date_start); - $tournament->setEndDate($this->date_end); - $tournament->setInscriptionDate("$this->date_inscription $this->time_inscription"); - $tournament->setSolutionsDate("$this->date_solutions $this->time_solutions"); - $tournament->setSynthesesDate("$this->date_syntheses $this->time_syntheses"); - $tournament->setSolutionsDate2("$this->date_solutions_2 $this->time_solutions_2"); - $tournament->setSynthesesDate2("$this->date_syntheses_2 $this->time_syntheses_2"); - $tournament->setDescription($this->description); - - foreach ($this->organizers as $organizer) { - if (!$tournament->organize($organizer->getId())) - Mailer::sendAddOrganizerForTournamentMail($organizer, $tournament); - } - - $tournament->clearOrganizers(); - /** @var User $organizer */ - foreach ($this->organizers as $organizer) - $tournament->addOrganizer($organizer); - - header("Location: $URL_BASE/tournoi/" . $this->name); - exit(); - } -} - -if ($_SESSION["role"] == Role::ORGANIZER || $_SESSION["role"] == Role::ADMIN) { - $emails = []; - $emails_validated = []; - foreach ($tournament->getOrganizers() as $organizer) { - $emails[] = $organizer->getEmail(); - $emails_validated[] = $organizer->getEmail(); - } - - foreach ($teams as $team) { - foreach ($team->getEncadrants() as $encadrant_id) { - $encadrant = User::fromId($encadrant_id); - if ($encadrant != null) { - $emails[] = $encadrant->getEmail(); - if ($team->getValidationStatus() == ValidationStatus::VALIDATED) - $emails_validated[] = $encadrant->getEmail(); - } - } - - foreach ($team->getParticipants() as $participant_id) { - $participant = User::fromId($participant_id); - if ($participant != null) { - $emails[] = $participant->getEmail(); - if ($team->getValidationStatus() == ValidationStatus::VALIDATED) - $emails_validated[] = $participant->getEmail(); - if ($participant->getResponsibleEmail() != null) { - $emails[] = $participant->getResponsibleEmail(); - if ($team->getValidationStatus() == ValidationStatus::VALIDATED) - $emails_validated[] = $participant->getResponsibleEmail(); - } - } - } - } -} - -require_once "server_files/views/tournoi.php"; diff --git a/server_files/controllers/tournois.php b/server_files/controllers/tournois.php deleted file mode 100644 index 7a304fc..0000000 --- a/server_files/controllers/tournois.php +++ /dev/null @@ -1,42 +0,0 @@ -getOrganizers() as $organizer) { - $emails[] = $organizer->getEmail(); - $emails_validated[] = $organizer->getEmail(); - } - - foreach ($tournament->getAllTeams() as $team) { - foreach ($team->getEncadrants() as $encadrant_id) { - $encadrant = User::fromId($encadrant_id); - if ($encadrant != null) { - $emails[] = $encadrant->getEmail(); - if ($team->getValidationStatus() == ValidationStatus::VALIDATED) - $emails_validated[] = $encadrant->getEmail(); - } - } - - foreach ($team->getParticipants() as $participant_id) { - $participant = User::fromId($participant_id); - if ($participant != null) { - $emails[] = $participant->getEmail(); - if ($team->getValidationStatus() == ValidationStatus::VALIDATED) - $emails_validated[] = $participant->getEmail(); - if ($participant->getResponsibleEmail() != null) { - $emails[] = $participant->getResponsibleEmail(); - if ($team->getValidationStatus() == ValidationStatus::VALIDATED) - $emails_validated[] = $participant->getResponsibleEmail(); - } - } - } - } - } -} - -require_once "server_files/views/tournois.php"; diff --git a/server_files/controllers/view_file.php b/server_files/controllers/view_file.php deleted file mode 100644 index cdc4904..0000000 --- a/server_files/controllers/view_file.php +++ /dev/null @@ -1,102 +0,0 @@ -getTeamId()); - $tournament = Tournament::fromId($file->getTournamentId()); - $trigram = $team->getTrigram(); - - if ($_SESSION["role"] == Role::ORGANIZER && !$tournament->organize($_SESSION["user_id"])) - require_once "server_files/403.php"; - - if ($type == DocumentType::SOLUTION) { - $problem = $file->getProblem(); - $name = "Problème $problem $trigram"; - - if (($_SESSION["role"] == Role::PARTICIPANT || $_SESSION["role"] == Role::ENCADRANT) && (!isset($_SESSION["team"]) || $_SESSION["team"]->getId() != $team->getId())) { - $req = $DB->prepare("SELECT opposed_problem, rapported_problem, opposed_problem_2, rapported_problem_2 FROM teams WHERE id = ?;"); - $req->execute([$_SESSION["team"]->getId()]); - $data = $req->fetch(); - if ($id != $data["opposed_problem"] && $id != $data["rapported_problem"]) { - if (date("Y-m-d H:i") < $tournament->getSolutionsDate2() || ($id != $data["opposed_problem_2"] && $id != $data["rapported_problem_2"])) - require_once "server_files/403.php"; - } - } - } - else if ($type == DocumentType::SYNTHESIS) { - $dest = $file->getDest(); - $name = "Note de synthèse $trigram " . ($dest == DestType::OPPOSANT ? "de l'opposant" : "du rapporteur"); - - if (($_SESSION["role"] == Role::PARTICIPANT || $_SESSION["role"] == Role::ENCADRANT) && (!isset($_SESSION["team"]) || $_SESSION["team"]->getId() != $team->getId())) - require_once "server_files/403.php"; - } - else { - $user = User::fromId($file->getUserId()); - $type = $file->getType(); - - if (($_SESSION["role"] == Role::PARTICIPANT || $_SESSION["role"] == Role::ENCADRANT)) { - if ($type != DocumentType::MOTIVATION_LETTER && $user->getId() != $_SESSION["user_id"] || $file->getTeamId() != $team->getId()) - require_once "server_files/403.php"; - } - - switch ($type) { - case DocumentType::PARENTAL_CONSENT: - $name = "Autorisation parentale"; - break; - case DocumentType::PHOTO_CONSENT: - $name = "Autorisation de droit à l'image"; - break; - case DocumentType::SANITARY_PLUG: - $name = "Fiche sanitaire"; - break; - case DocumentType::SCHOLARSHIP: - $name = "Notification de bourse"; - break; - } - if ($type == DocumentType::MOTIVATION_LETTER) - $name = "Lettre de motivation de l'équipe $trigram"; - else { - $surname = $user->getSurname(); - $first_name = $user->getFirstName(); - $name .= " de $first_name $surname"; - } - } -} -else - require_once "server_files/404.php"; - -$mime = finfo_file(finfo_open(FILEINFO_MIME_TYPE), "$LOCAL_PATH/files/$id"); -if ($mime == "application/pdf") - $name .= ".pdf"; -elseif ($mime == "image/png") - $name .= ".png"; -else - $name = ".jpg"; - -header("Content-Type: $mime"); -header("Content-Disposition: inline; filename=\"$name\""); - -readfile("$LOCAL_PATH/files/$id"); - -exit(); \ No newline at end of file diff --git a/server_files/model.php b/server_files/model.php deleted file mode 100644 index e650c24..0000000 --- a/server_files/model.php +++ /dev/null @@ -1,267 +0,0 @@ -getRole(); - - if ($user->getTeamId() !== null) { - $team = $_SESSION["team"] = Team::fromId($user->getTeamId()); - $_SESSION["tournament"] = Tournament::fromId($team->getTournamentId()); - } - - if (isset($_GET["view-as-admin"])) { - if (isset($_SESSION["admin"])) { - $_SESSION["user_id"] = $_SESSION["admin"]; - unset($_SESSION["admin"]); - } - header("Location: /"); - exit(); - } - } -} - -function quitTeam($user_id = -1) -{ - global $DB, $URL_BASE; - - header("Location: $URL_BASE"); - - /** @var User $user */ - $user = $_SESSION["user"]; - if ($user_id == -1) - $user_id = $user->getId(); - else - $user = User::fromId($user_id); - $role = $user->getRole(); - - if ($role == Role::ADMIN || $role == Role::ORGANIZER) - return; - - for ($i = 1; $i <= ($role == Role::ENCADRANT ? 3 : 6); ++$i) - /** @noinspection SqlResolve */ - $DB->exec("UPDATE `teams` SET `" . strtolower(Role::getName($role)) . "_$i` = NULL WHERE `" . strtolower(Role::getName($role)) . "_$i` = $user_id;"); - $user->setTeamId(null); - $DB->exec("UPDATE `teams` SET `encadrant_1` = `encadrant_2`, `encadrant_2` = NULL WHERE `encadrant_1` IS NULL;"); - $DB->exec("UPDATE `teams` SET `encadrant_2` = `encadrant_3`, `encadrant_3` = NULL WHERE `encadrant_2` IS NULL;"); - for ($i = 1; $i <= 5; ++$i) { - /** @noinspection SqlResolve */ - $DB->exec("UPDATE `teams` SET `participant_$i` = `participant_" . strval($i + 1) . "`, `participant_" . strval($i + 1) . "` = NULL WHERE `participant_$i` IS NULL;"); - } - - $req = $DB->query("SELECT `file_id` FROM `documents` WHERE `user` = $user_id;"); - while (($data = $req->fetch()) !== false) - unlink("$URL_BASE/files/" . $data["file_id"]); - $DB->exec("DELETE FROM `documents` WHERE `user` = $user_id;"); - - if ($DB->exec("DELETE FROM `teams` WHERE `encadrant_1` IS NULL AND `participant_1` IS NULL;") > 0) { - $team_id = $user->getTeamId(); - $req = $DB->query("SELECT `file_id` FROM `solutions` WHERE `team` = $team_id;"); - while (($data = $req->fetch()) !== false) - unlink("$URL_BASE/files/" . $data["file_id"]); - $DB->exec("DELETE FROM `solutions` WHERE `team` = $team_id;"); - - $req = $DB->query("SELECT `file_id` FROM `syntheses` WHERE `team` = $team_id;"); - while (($data = $req->fetch()) !== false) - unlink("$URL_BASE/files/" . $data["file_id"]); - $DB->exec("DELETE FROM `syntheses` WHERE `team` = $team_id;"); - } - - $_SESSION["team"] = null; - unset($_SESSION["team"]); -} - -function userExists($email) -{ - global $DB, $YEAR; - - $req = $DB->prepare("SELECT `id` FROM `users` WHERE `email` = ? AND `year` = '$YEAR';"); - $req->execute([$email]); - return $req->fetch(); -} - -function teamExists($name) -{ - global $DB, $YEAR; - - $req = $DB->prepare("SELECT `id` FROM `teams` WHERE `name` = ? AND `year` = '$YEAR';"); - $req->execute([$name]); - return $req->fetch(); -} - -function trigramExists($trigram) -{ - global $DB, $YEAR; - - $req = $DB->prepare("SELECT `id` FROM `teams` WHERE `trigram` = ? AND `year` = '$YEAR';"); - $req->execute([$trigram]); - return $req->fetch(); -} - -function tournamentExists($name) -{ - global $DB, $YEAR; - - $req = $DB->prepare("SELECT `id` FROM `tournaments` WHERE `name` = ? AND `year` = '$YEAR';"); - $req->execute([$name]); - return $req->fetch(); -} - -function canValidate(Team $team, Tournament $tournament) -{ - global $DB, $YEAR; - - $can_validate = $team->getValidationStatus() == ValidationStatus::NOT_READY; - $can_validate &= $team->getEncadrants()[0] != NULL; - $can_validate &= $team->getParticipants()[3] != NULL; - - // Le TFJM² 2020 se déroulant en ligne, les papiers ne sont plus nécessaires -/* for ($i = 1; $i <= 2; ++$i) { - if ($team->getEncadrants()[$i - 1] === NULL) - continue; - - $req = $DB->prepare("SELECT COUNT(*) AS `version` FROM `documents` WHERE `user` = ? AND `tournament` = ? AND `type` = ?;"); - $req->execute([$team->getEncadrants()[$i - 1], $tournament->getId(), "PHOTO_CONSENT"]); - $d = $req->fetch(); - $can_validate &= $d["version"] > 0; - }*/ - - - // Le TFJM² 2020 se déroulant en ligne, les papiers ne sont plus nécessaires -/* for ($i = 1; $i <= 6; ++$i) { - if ($team->getParticipants()[$i] === NULL) - continue; - - $req = $DB->prepare("SELECT COUNT(*) AS `version` FROM `documents` WHERE `user` = ? AND `tournament` = ? AND `type` = ?;"); - $req->execute([$team->getParticipants()[$i], $tournament->getId(), "PHOTO_CONSENT"]); - $d = $req->fetch(); - $can_validate &= $d["version"] > 0; - - $birth_date = $DB->query("SELECT `birth_date` FROM `users` WHERE `id` = " . $team->getParticipants()[$i] . ";")->fetch()["birth_date"]; - if ($birth_date > strval($YEAR - 18) . substr($tournament->getStartDate(), 4)) { - $req = $DB->prepare("SELECT COUNT(*) AS `version` FROM `documents` WHERE `user` = ? AND `tournament` = ? AND `type` = ?;"); - $req->execute([$team->getParticipants()[$i], $tournament->getId(), "PARENTAL_CONSENT"]); - $d = $req->fetch(); - $can_validate &= $d["version"] > 0; - - $req = $DB->prepare("SELECT COUNT(*) AS `version` FROM `documents` WHERE `user` = ? AND `tournament` = ? AND `type` = ?;"); - $req->execute([$team->getParticipants()[$i], $tournament->getId(), "SANITARY_PLUG"]); - $d = $req->fetch(); - $can_validate &= $d["version"] > 0; - } - } */ - - // La lettre de motivation n'est plus nécessaire, mais existe toujours -/* $req = $DB->prepare("SELECT COUNT(*) AS `version` FROM `documents` WHERE `team` = ? AND `tournament` = ? AND `type` = ?;"); - $req->execute([$team->getId(), $tournament->getId(), "MOTIVATION_LETTER"]); - $d = $req->fetch(); - $can_validate &= $d["version"] > 0;*/ - - $can_validate &= date("Y-m-d H:i:s") <= $tournament->getInscriptionDate(); - - return $can_validate; -} - -function printDocuments($documents) -{ - if (sizeof($documents) == 0) { - echo "
\nPas de document envoyé pour le moment.\n
\n"; - return; - } - - echo "
\n"; - foreach ($documents as $document) { - $file_id = $document->getFileId(); - $name = DocumentType::getTranslatedName($document->getType()); - $version = $document->getVersion(); - if ($document->getType() == DocumentType::MOTIVATION_LETTER) { - $team = Team::fromId($document->getTeamId()); - echo "Lettre de motivation de l'équipe " . $team->getTrigram(); - } - else { - $user = User::fromId($document->getUserId()); - $surname = $user->getSurname(); - $first_name = $user->getFirstName(); - echo "$name de $first_name $surname"; - } - - echo " (version $version) : Télécharger
\n"; - } - echo "
\n"; -} - -function getZipFile($document_type, $tournament_id, $team_id = -1) -{ - global $LOCAL_PATH; - - $tournament = Tournament::fromId($tournament_id); - - $zip = new ZipArchive(); - - $file_name = tempnam("tmp", "tfjm-"); - - if ($zip->open($file_name, ZipArchive::CREATE) !== true) { - die("Impossible de créer le fichier zip."); - } - - switch ($document_type) { - case DocumentType::SOLUTION: - $data = $tournament->getAllSolutions($team_id); - break; - case DocumentType::SYNTHESIS: - $data = $tournament->getAllSyntheses($team_id); - break; - default: - $data = $tournament->getAllDocuments($team_id); - break; - } - - /** @var Document | Solution | Synthesis $file */ - foreach ($data as $file) { - $file_id = $file->getFileId(); - $team = Team::fromId($file->getTeamId()); - switch ($document_type) { - case DocumentType::SOLUTION: - $name = "Problème " . $file->getProblem() . " " . $team->getTrigram() . ".pdf"; - break; - case DocumentType::SYNTHESIS: - $name = "Note de synthèse " . $team->getTrigram() . " pour " . ($file->getDest() == DestType::OPPOSANT ? "l'opposant" : "le rapporteur") . ".pdf"; - break; - default: - $user = User::fromId($file->getUserId()); - switch ($file->getType()) { - case DocumentType::PARENTAL_CONSENT: - $name = "Autorisation parentale de " . $user->getFirstName() . " " . $user->getSurname() . ".pdf"; - break; - case DocumentType::PHOTO_CONSENT: - $name = "Autorisation de droit à l'image de " . $user->getFirstName() . " " . $user->getSurname() . ".pdf"; - break; - case DocumentType::SCHOLARSHIP: - $name = "Notification de bourse de " . $user->getFirstName() . " " . $user->getSurname() . ".pdf"; - break; - case DocumentType::MOTIVATION_LETTER: - $name = "Lettre de motivation de l'équipe " . $team->getTrigram() . ".pdf"; - break; - default: - $name = "Fiche sanitaire de " . $user->getFirstName() . " " . $user->getSurname() . ".pdf"; - break; - } - break; - } - - $zip->addFile("$LOCAL_PATH/files/$file_id", $name); - } - - $zip->close(); - - return $file_name; -} \ No newline at end of file diff --git a/server_files/services/mail.php b/server_files/services/mail.php deleted file mode 100644 index 0c174cd..0000000 --- a/server_files/services/mail.php +++ /dev/null @@ -1,263 +0,0 @@ -\r\n"; - $headers .= "Reply-To: \"Contact TFJM²\" \r\n"; - $headers .= "Content-Type: text/html; charset=UTF-8\r\n"; - - mail($email, $subject, $content, $headers); - } - - private static function broadcastToTeam(Team $team, $subject, $content, $from = "contact") - { - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - - foreach ($team->getEncadrants() as $participant_id) { - $participant = User::fromId($participant_id); - if ($participant == null) - continue; - - $c = preg_replace("#{FIRST_NAME}#", $participant->getFirstName(), $content); - $c = preg_replace("#{SURNAME}#", $participant->getSurname(), $c); - self::sendMail($participant->getEmail(), $subject, $c, $from); - } - - foreach ($team->getParticipants() as $participant_id) { - $participant = User::fromId($participant_id); - if ($participant == null) - continue; - - $c = preg_replace("#{FIRST_NAME}#", $participant->getFirstName(), $content); - $c = preg_replace("#{SURNAME}#", $participant->getSurname(), $c); - self::sendMail($participant->getEmail(), $subject, $c, $from); - } - } - - private static function broadcastToAdmins($subject, $content, $from = "contact") - { - /** @var User $admin */ - foreach (User::getAdmins() as $admin) { - $c = preg_replace("#{FIRST_NAME}#", $admin->getFirstName(), $content); - $c = preg_replace("#{SURNAME}#", $admin->getSurname(), $c); - self::sendMail($admin->getEmail(), $subject, $c, $from); - } - } - - private static function brodcastToOrgas(Tournament $tournament, $subject, $content, $from = "contact") - { - foreach ($tournament->getOrganizers() as $orga) { - if ($orga->getRole() == Role::ADMIN) - continue; - - $c = preg_replace("#{FIRST_NAME}#", $orga->getFirstName(), $content); - $c = preg_replace("#{SURNAME}#", $orga->getSurname(), $c); - self::sendMail($orga->getEmail(), $subject, $c, $from); - } - - self::broadcastToAdmins($subject, $content, $from); - } - - private static function getTemplate($name) - { - global $LOCAL_PATH; - return file_get_contents("$LOCAL_PATH/server_files/services/mail_templates/$name.html"); - } - - public static function sendRegisterMail(NewUser $new_user) - { - global $YEAR; - - $content = self::getTemplate("register"); - $content = preg_replace("#{FIRST_NAME}#", $new_user->first_name, $content); - $content = preg_replace("#{SURNAME}#", $new_user->surname, $content); - $content = preg_replace("#{TOKEN}#", $new_user->confirm_email_token, $content); - - self::sendMail($new_user->email, "Inscription au TFJM² $YEAR", $content); - } - - public static function sendConfirmEmail(User $user) - { - global $YEAR; - - $content = self::getTemplate("confirm_email"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TOKEN}#", $user->getConfirmEmailToken(), $content); - - self::sendMail($user->getEmail(), "Confirmation d'adresse e-mail – TFJM² $YEAR", $content); - } - - public static function sendChangeEmailAddressMail(User $user) - { - $content = self::getTemplate("change_email_address"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TOKEN}#", $user->getConfirmEmailToken(), $content); - - self::sendMail($user->getEmail(), "Changement d'adresse e-mail – TFJM²", $content); - } - - public static function sendForgottenPasswordProcedureMail(User $user) - { - $content = self::getTemplate("forgotten_password"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TOKEN}#", $user->getForgottenPasswordToken(), $content); - - self::sendMail($user->getEmail(), "Mot de passe oublié – TFJM²", $content); - } - - public static function sendChangePasswordMail(User $user) - { - $content = self::getTemplate("change_password"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - - self::sendMail($user->getEmail(), "Mot de passe changé – TFJM²", $content); - } - - public static function sendAddTeamMail(User $user, Team $team, Tournament $tournament) - { - global $YEAR; - - $content = self::getTemplate("add_team"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - $content = preg_replace("#{TOURNAMENT_NAME}#", $tournament->getName(), $content); - $content = preg_replace("#{ACCESS_CODE}#", $team->getAccessCode(), $content); - - self::sendMail($user->getEmail(), "Ajout d'une équipe TFJM² $YEAR", $content); - } - - public static function sendJoinTeamMail(User $user, Team $team, Tournament $tournament) - { - global $YEAR; - - $content = self::getTemplate("join_team"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - $content = preg_replace("#{TOURNAMENT_NAME}#", $tournament->getName(), $content); - - self::sendMail($user->getEmail(), "Équipe rejointe TFJM² $YEAR", $content); - } - - public static function sendAddOrganizerMail(NewOrganizer $new_orga) - { - global $YEAR; - - $content = self::getTemplate("add_organizer"); - $content = preg_replace("#{FIRST_NAME}#", $new_orga->first_name, $content); - $content = preg_replace("#{SURNAME}#", $new_orga->surname, $content); - $content = preg_replace("#{TOKEN}#", $new_orga->token, $content); - - self::sendMail($new_orga->email, "Ajout d'un organisateur – TFJM² $YEAR", $content); - } - - public static function sendAddOrganizerForTournamentMail(User $organizer, Tournament $tournament) - { - global $YEAR; - - $content = self::getTemplate("add_organizer_for_tournament"); - $content = preg_replace("#{FIRST_NAME}#", $organizer->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $organizer->getSurname(), $content); - $content = preg_replace("#{TOURNAMENT_NAME}#", $tournament->getName(), $content); - - self::sendMail($organizer->getEmail(), "Ajout d'un organisateur pour le tournoi " . $tournament->getName() . " – TFJM² $YEAR", $content); - } - - public static function requestPaymentValidation(User $user, Team $team, Tournament $tournament, Payment $payment) - { - global $YEAR, $URL_BASE; - - $content = self::getTemplate("request_payment_validation"); - $content = preg_replace("#{USER_FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{USER_SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{USER_ID}#", $user->getId(), $content); - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - $content = preg_replace("#{TOURNAMENT_NAME}#", $tournament->getName(), $content); - $content = preg_replace("#{AMOUNT}#", $payment->getAmount(), $content); - $content = preg_replace("#{PAYMENT_METHOD}#", PaymentMethod::getTranslatedName($payment->getMethod()), $content); - if ($payment->getMethod() == PaymentMethod::SCHOLARSHIP) - $content = preg_replace("#{PAYMENT_INFOS}#", "getTransactionInfos() . "\">Voir la notification de bourse", $content); - else - $content = preg_replace("#{PAYMENT_INFOS}#", $payment->getTransactionInfos(), $content); - - self::broadcastToAdmins("Demande de validation de paiement pour le tournoi " . $tournament->getName() . " – TFJM² $YEAR", $content); - } - - public static function sendRequestValidationMail(Team $team, Tournament $tournament) - { - global $YEAR; - - $content = self::getTemplate("request_validation"); - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - $content = preg_replace("#{TOURNAMENT}#", $tournament->getName(), $content); - $content = preg_replace("#{ACCESS_CODE}#", $team->getAccessCode(), $content); - - self::brodcastToOrgas($tournament, "Demande de validation – TFJM² $YEAR", $content); - } - - public static function sendValidateTeam($team, $message) - { - global $YEAR; - - $content = self::getTemplate("validate_team"); - if (strlen($message) > 0) - $message = " L'équipe d'organisation vous transmet le message suivant :\n\n" . $message; - $message = preg_replace("#\n#", "
\n", $message); - $content = preg_replace("#{MESSAGE}#", $message, $content); - - self::broadcastToTeam($team, "Équipe validée – TFJM² $YEAR", $content); - } - - public static function sendUnvalidateTeam($team, $message) - { - global $YEAR; - - $content = self::getTemplate("unvalidate_team"); - if (strlen($message) > 0) - $message = " L'équipe d'organisation vous transmet le message suivant :\n\n" . $message; - $message = preg_replace("#\n#", "
\n", $message); - $content = preg_replace("#{MESSAGE}#", $message, $content); - - self::broadcastToTeam($team, "Équipe non validée – Correspondances des Jeunes Mathématicien·ne·s $YEAR", $content); - } - - public static function sendValidatePayment(User $user, Team $team, Tournament $tournament, Payment $payment, $message) - { - global $YEAR, $URL_BASE; - - $content = self::getTemplate($payment->getValidationStatus() == ValidationStatus::VALIDATED ? "validate_payment" : "unvalidate_payment"); - $content = preg_replace("#{FIRST_NAME}#", $user->getFirstName(), $content); - $content = preg_replace("#{SURNAME}#", $user->getSurname(), $content); - $content = preg_replace("#{TEAM_NAME}#", $team->getName(), $content); - $content = preg_replace("#{TRIGRAM}#", $team->getTrigram(), $content); - $content = preg_replace("#{TOURNAMENT_NAME}#", $tournament->getName(), $content); - $content = preg_replace("#{AMOUNT}#", $payment->getAmount(), $content); - $content = preg_replace("#{PAYMENT_METHOD}#", PaymentMethod::getTranslatedName($payment->getMethod()), $content); - if ($payment->getMethod() == PaymentMethod::SCHOLARSHIP) - $content = preg_replace("#{PAYMENT_INFOS}#", "getTransactionInfos() . "\">Voir la notification de bourse", $content); - else - $content = preg_replace("#{PAYMENT_INFOS}#", $payment->getTransactionInfos(), $content); - if (isset($message) && strlen($message) > 0) { - $content = preg_replace("#{MESSAGE}#", "L'équipe d'organisation vous transmet les informations suivantes :

" . $message . "
", $content); - } - - self::sendMail($user->getEmail(), "Paiement pour le tournoi " . $tournament->getName() . " – TFJM² $YEAR", $content); - } -} diff --git a/server_files/services/mail_templates/add_organizer.html b/server_files/services/mail_templates/add_organizer.html deleted file mode 100644 index 56ed2c5..0000000 --- a/server_files/services/mail_templates/add_organizer.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - Organisateur du TFJM² - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous recevez ce message (envoyé automatiquement) car vous êtes organisateur d'un des tournois du TFJM2.

-Un compte organisateur vous a été créé par l'un des administrateurs. Un mot de passe aléatoire vous a été attribué, mais que vous -devez changer pour des raisons de sécurité sur le lien suivant : -{URL_BASE}/connexion/reinitialiser_mdp/{TOKEN}
-
-Une fois le mot de passe changé, vous pourrez vous connecter sur la plateforme.
-
-Merci beaucoup pour votre aide !
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/add_organizer_for_tournament.html b/server_files/services/mail_templates/add_organizer_for_tournament.html deleted file mode 100644 index ee83644..0000000 --- a/server_files/services/mail_templates/add_organizer_for_tournament.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - Organisateur du tournoi de {TOURNAMENT_NAME} – TFJM² - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez d'être promu organisateur du tournoi {TOURNAMENT_NAME} du TFJM2 {YEAR}.
-Ce message vous a été envoyé automatiquement. En cas de problème, merci de répondre à ce message. -
-Cordialement,
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/add_team.html b/server_files/services/mail_templates/add_team.html deleted file mode 100644 index ffd2b50..0000000 --- a/server_files/services/mail_templates/add_team.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Nouvelle équipe TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de créer l'équipe « {TEAM_NAME} » ({TRIGRAM}) pour le TFJM2 de {TOURNAMENT_NAME} et nous vous en remercions.
-Afin de permettre aux autres membres de votre équipe de vous rejoindre, veuillez leur transmettre le code d'accès : -{ACCESS_CODE}
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/change_email_address.html b/server_files/services/mail_templates/change_email_address.html deleted file mode 100644 index 0adf015..0000000 --- a/server_files/services/mail_templates/change_email_address.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - Changement d'adresse e-mail – TFJM² - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de changer votre adresse e-mail. Veuillez désormais la confirmer en cliquant ici : {URL_BASE}/confirmer_mail/{TOKEN}
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/change_password.html b/server_files/services/mail_templates/change_password.html deleted file mode 100644 index 91d2cf1..0000000 --- a/server_files/services/mail_templates/change_password.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - Mot de passe changé – TFJM² - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Nous vous informons que votre mot de passe vient d'être modifié. Si vous n'êtes pas à l'origine de cette manipulation, -veuillez immédiatement vérifier vos accès à votre boîte mail et changer votre mot de passe sur la plateforme -d'inscription.
-
-Cordialement,
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/confirm_email.html b/server_files/services/mail_templates/confirm_email.html deleted file mode 100644 index ba75174..0000000 --- a/server_files/services/mail_templates/confirm_email.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - Inscription au TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous êtes inscrit au TFJM2 {YEAR} et nous vous en remercions.
-Pour valider votre adresse e-mail, veuillez cliquer sur le lien : {URL_BASE}/confirmer_mail/{TOKEN}
-
-Cordialement,
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/forgotten_password.html b/server_files/services/mail_templates/forgotten_password.html deleted file mode 100644 index 18c187d..0000000 --- a/server_files/services/mail_templates/forgotten_password.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - Mot de passe oublié – TFJM² - - -Bonjour,
-
-Vous avez indiqué avoir oublié votre mot de passe. Veuillez cliquer ici pour le réinitialiser : {URL_BASE}/connexion/reinitialiser_mdp/{TOKEN}
-
-Si vous n'êtes pas à l'origine de cette manipulation, vous pouvez ignorer ce message.
-
-Cordialement,
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/join_team.html b/server_files/services/mail_templates/join_team.html deleted file mode 100644 index 3e51307..0000000 --- a/server_files/services/mail_templates/join_team.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - Équipe rejointe – TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de rejoindre l'équipe « {TEAM_NAME} » ({TRIGRAM}) pour le TFJM² de {TOURNAMENT_NAME} et nous vous en -remercions.
-
-Cordialement,
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/register.html b/server_files/services/mail_templates/register.html deleted file mode 100644 index 0334c01..0000000 --- a/server_files/services/mail_templates/register.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - Inscription au TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de vous inscrire au TFJM2 {YEAR} et nous vous en remercions.
-Pour valider votre adresse e-mail, veuillez cliquer sur le lien : {URL_BASE}/confirmer_mail/{TOKEN}
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/request_payment_validation.html b/server_files/services/mail_templates/request_payment_validation.html deleted file mode 100644 index 8c23f21..0000000 --- a/server_files/services/mail_templates/request_payment_validation.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - Demande de validation de paiement pour le TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-{USER_FIRST_NAME} {USER_SURNAME} de l'équipe {TEAM_NAME} ({TRIGRAM}) annonce avoir réglé sa participation pour le tournoi {TOURNAMENT_NAME}. -Les informations suivantes ont été communiquées :

-Équipe : {TEAM_NAME} ({TRIGRAM})
-Tournoi : {TOURNAMENT_NAME}
-Moyen de paiement : {PAYMENT_METHOD}
-Montant : {AMOUNT} €
-Informations sur le paiement : {PAYMENT_INFOS}
-
-Vous pouvez désormais vérifier ces informations, puis valider (ou non) le paiement sur -la page associée à ce participant. -
-Cordialement, -
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/request_validation.html b/server_files/services/mail_templates/request_validation.html deleted file mode 100644 index 203d616..0000000 --- a/server_files/services/mail_templates/request_validation.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - Demande de validation - TFJM² - - -Bonjour {FIRST_NAME} {SURNAME},
-
-L'équipe « {TEAM_NAME} » ({TRIGRAM}) vient de demander à valider son équipe pour participer au tournoi {TOURNAMENT} du -TFJM². Vous pouvez décider d'accepter ou de refuser l'équipe en vous rendant sur la page de l'équipe : -{URL_BASE}/equipe/{TRIGRAM}
-
-Cordialement,
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/unvalidate_payment.html b/server_files/services/mail_templates/unvalidate_payment.html deleted file mode 100644 index c6e99ff..0000000 --- a/server_files/services/mail_templates/unvalidate_payment.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - Non-validation du paiement pour le TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Votre paiement pour le TFJM² {YEAR} a malheureusement été rejeté. Pour rappel, vous aviez fourni ces informations :

-Équipe : {TEAM_NAME} ({TRIGRAM})
-Tournoi : {TOURNAMENT_NAME}
-Moyen de paiement : {PAYMENT_METHOD}
-Montant : {AMOUNT} €
-Informations sur le paiement : {PAYMENT_INFOS}
-
-{MESSAGE} -
-Cordialement, -
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/unvalidate_team.html b/server_files/services/mail_templates/unvalidate_team.html deleted file mode 100644 index d9c5588..0000000 --- a/server_files/services/mail_templates/unvalidate_team.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - Équipe non validée – TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Maleureusement, votre équipe « {TEAM_NAME} » ({TRIGRAM}) n'a pas été validée. Veuillez vérifier que vos autorisations sont correctes. -{MESSAGE}
-
-N'hésitez pas à nous contacter à l'adresse contact@tfjm.org pour plus d'informations. -
-Cordialement,
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/validate_payment.html b/server_files/services/mail_templates/validate_payment.html deleted file mode 100644 index afe94ba..0000000 --- a/server_files/services/mail_templates/validate_payment.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - Validation du paiement pour le TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Votre paiement pour le TFJM² {YEAR} a bien été validé. Pour rappel, vous aviez fourni ces informations :

-Équipe : {TEAM_NAME} ({TRIGRAM})
-Tournoi : {TOURNAMENT_NAME}
-Moyen de paiement : {PAYMENT_METHOD}
-Montant : {AMOUNT} €
-Informations sur le paiement : {PAYMENT_INFOS}
-
-{MESSAGE} -
-Cordialement, -
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/services/mail_templates/validate_team.html b/server_files/services/mail_templates/validate_team.html deleted file mode 100644 index 0967488..0000000 --- a/server_files/services/mail_templates/validate_team.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - Équipe validée – TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Félicitations ! Votre équipe « {TEAM_NAME} » ({TRIGRAM}) est désormais validée ! Vous êtes désormais apte à travailler sur -vos problèmes et publier vos solutions sur la plateforme. -{MESSAGE}
-
-Cordialement,
-
-Le comité national d'organisation du TFJM2 - - \ No newline at end of file diff --git a/server_files/utils.php b/server_files/utils.php deleted file mode 100644 index 2bc4ce5..0000000 --- a/server_files/utils.php +++ /dev/null @@ -1,32 +0,0 @@ - - -
-

Ajouter une équipe

-
- - -
- Votre équipe a bien été créée ! Voici le code d'accès à transmettre aux autres membres de votre équipe : - access_code ?> -
- -
- Vous êtes déjà dans une équipe. -
- - -
-
-
- - -
- -
- - -
-
- -
- - -
- -
- -
-
- - - diff --git a/server_files/views/ajouter_organisateur.php b/server_files/views/ajouter_organisateur.php deleted file mode 100644 index 9db8a91..0000000 --- a/server_files/views/ajouter_organisateur.php +++ /dev/null @@ -1,51 +0,0 @@ - - -
-

Ajouter un organisateur

-
- - -
- Organisateur ajouté avec succès ! Ses identifiants ont été transmis par mail. -
- - -
-
-
- - -
- -
- - -
-
- -
-
- - -
-
- -
-
- - -
-
- -
- -
-
- - diff --git a/server_files/views/ajouter_tournoi.php b/server_files/views/ajouter_tournoi.php deleted file mode 100644 index 2570da3..0000000 --- a/server_files/views/ajouter_tournoi.php +++ /dev/null @@ -1,128 +0,0 @@ - - -
-

Ajouter un tournoi

-
- - -
- Tournoi de name ?> ajouté avec succès ! -
- - -
-
-
- - -
- -
- - -
-
- -
-
- - -
-
- -
-
- - -
- -
- - -
-
- -
-
- - -
-
- - -
-
- -
-
- - - -
-
- - - -
-
- - - -
-
- -
-
- - - -
-
- - - -
-
- -
-
- - -
-
- - -

- -
- -
-
- - \ No newline at end of file diff --git a/server_files/views/connexion.php b/server_files/views/connexion.php deleted file mode 100644 index f59f4ac..0000000 --- a/server_files/views/connexion.php +++ /dev/null @@ -1,65 +0,0 @@ -Le mail de récupération de mot de passe a bien été envoyé."; - elseif (isset($reset_password) && isset($_POST["password"])) - echo "
Le mot de passe a bien été changé. Vous pouvez désormais vous connecter.
"; - elseif (isset($_GET["confirmation-mail"])) - echo "
Le mail a bien été renvoyé.
"; - else if (isset($logging_in_user)) { - echo "
Connexion réussie !
"; - require_once "footer.php"; - } else if (isset($_SESSION["user_id"])) { - echo "
Vous êtes déjà connecté !
"; - require_once "footer.php"; - } -} - -if (isset($_GET["mdp_oublie"])) { ?> -
-

Réinitialisation du mot de passe

- - - -
-user != null && ($has_error || !isset($_POST["password"]))) { ?> -
-

Connexion

- "/> -
- - -
-
- - -
- -
- - -
-

Connexion

-
-
- - -
-
- - -
- -
- - - - diff --git a/server_files/views/equipe.php b/server_files/views/equipe.php deleted file mode 100644 index 6744110..0000000 --- a/server_files/views/equipe.php +++ /dev/null @@ -1,161 +0,0 @@ - - -
-

Informations sur l'équipe

-
- -
- Nom de l'équipe : getName() ?> -
-
- Trigramme : getTrigram() ?> -
- -
- getValidationStatus() != ValidationStatus::VALIDATED) { ?> - -
- -
- - Tournoi : getName() ?>"> - getTournamentId() == 0 ? "Pas de tournoi choisi" : $tournament->getName() ?> - - -
- -
getValidationStatus() == ValidationStatus::WAITING ? "warning" : "danger") ?>"> - Validation de l'équipe - : getValidationStatus()) ?> -
-
- getEncadrants()[$i - 1] == NULL) - continue; - $encadrant = User::fromId($team->getEncadrants()[$i - 1]); - $id = $encadrant->getId(); - echo "Encadrant : getFirstName() . " " . $encadrant->getSurname() . "\">" . $encadrant->getFirstName() . " " . $encadrant->getSurname() . "
"; - } - for ($i = 1; $i <= 6; ++$i) { - if ($team->getParticipants()[$i - 1] == NULL) - continue; - $participant = User::fromId($team->getParticipants()[$i - 1]); - $id = $participant->getId(); - echo "Participant $i : getFirstName() . " " . $participant->getSurname() . "\">" . $participant->getFirstName() . " " . $participant->getSurname() . "
"; - } - if ($team->isSelectedForFinal()) { - $final_name = $FINAL->getName(); - echo "Équipe sélectionnée pour la finale nationale."; - } - ?> -
- - - - - -
-
-
- - -
- -
- - -
-
- -
- - -
- -
- -
-
- -getValidationStatus() != ValidationStatus::VALIDATED) { ?> -
- - - -
- -

Documents

- - - -
- -
- -isSelectedForFinal()) { ?> -
-

Documents pour la finale

- -
- -
- - -getValidationStatus() == ValidationStatus::WAITING) { ?> -
-
- - -
- -
-
- - -
-
-
- isSelectedForFinal() && $team->getValidationStatus() == ValidationStatus::VALIDATED) { ?> -
-
- -
-getValidationStatus() == ValidationStatus::NOT_READY && $_SESSION["role"] == Role::ADMIN) { ?> -
-
- -
- - - \ No newline at end of file diff --git a/server_files/views/footer.php b/server_files/views/footer.php deleted file mode 100644 index c84f917..0000000 --- a/server_files/views/footer.php +++ /dev/null @@ -1,18 +0,0 @@ -
-
- - -
-
-
-
- Ce site a été conçu pour Animath, avec amour et passion. Il est récent et il est possible que - certaines pages ne fonctionnent pas correctement. Si vous remarquez des bugs, merci de les signaler à - l'adresse contact@tfjm.org.
- © Tournoi Français des Jeunes Mathématiciennes et Mathématiciens -
-
-
- - - diff --git a/server_files/views/header.php b/server_files/views/header.php deleted file mode 100644 index f503e23..0000000 --- a/server_files/views/header.php +++ /dev/null @@ -1,163 +0,0 @@ - - - - - - - - - Site d'inscription pour le TFJM² <?= $YEAR ?> - - - - - - - - - - - - - - - - -
- -
- - -
- -
-
- - getValidationStatus() == ValidationStatus::NOT_READY) { ?> -
- Votre équipe n'est pas validée. Rendez-vous sur la page Mon équipe pour demander à - valider votre équipe. Si vous aviez déjà effectué cette procédure par le passé, sachez qu'en raison du - changement de format de l'édition 2020 du TFJM2, toutes les validations ont été retirées, et - vous devez à nouveau demander à valider votre équipe. Plus d'informations sur la page d'accueil. -
- - - -
- Erreur : -
- - -
-
-

- Bienvenue sur le site d'inscription au 𝕋𝔽𝕁𝕄2 ! -

-

- Le Tournoi Français des Jeunes Mathématiciens et Mathématiciennes -

-
-
-
-
-

- Tu souhaites participer au tournoi ? -
- Ton équipe est déjà formée ? -

-
- -
- -
-
Attentions aux échéances
-

- Chaque tournoi a une date limite pour les inscriptions et une date limite pour - déposer vos solutions. En savoir plus -

-
- -
-
Modification du règlement
-

- Depuis l'année dernière, l'équipe doit envoyer par mail à contact@tfjm.org les informations suivantes: -

    -
  • Comment l’équipe s’est-elle formée ?
  • -
  • - Comment l’équipe va-t-elle travailler (où peut-elle se rencontrer, à quelle fréquence, rencontres - avec l’encadrant•e) ? -
  • -
- - Cette lettre permettra aux organisateurs•trices de vérifier que l’équipe dispose des conditions nécessaires - à une participation sérieuse. Sont dispensées les équipes dont la moitié ou plus des membres sont scolarisés - dans le même établissement. Le comité National d’Organisation se réserve le droit d’accepter ou non - l’inscription des équipes concernées par cette lettre. -

-
- -
- -
-
Comment ça marche ?
-

- Pour participer à l'un des tournois régionaux, il suffit de créer un compte sur la rubrique - Inscription. Il vous faudra une adresse email pour ce faire. Un mail de confirmation sera envoyé - à cette adresse. Il vous fournira un nom d'utilisateur et un mot de passe que vous allez devoir changer - par la suite. -

-

- Vous pouvez accéder à votre compte via la rubrique Connexion. Une fois connecté, vous pourrez : -

-
    -
  • rentrer des informations sur les membres de votre équipe, tant participants qu'encadrants ;
  • -
  • - enregistrer et télécharger des versions préliminaires de vos solutions (seulement la dernière - version enregistrée avant la date limite sera prise en compte pour le tournoi). -
  • -
-

- Une fois que vous aurez fourni toutes les informations demandées dans la rubrique Mon Équipe, - votre inscription pourra être validée par les organisateurs locaux. -

- -
- Attention! Votre équipe ne sera considérée comme admissible à participer au tournoi que - lorsque cette première étape aura été franchie. -
- -
- Pensez donc à former une équipe complète (minimum 4 participants et 1 encadrant) le plus tôt possible - pour avoir plus de chances de participer, compte tenu du nombre des places disponibles dans chaque - tournoi (qui sera dûment affiché sur la rubrique Liste des Tournois). Les équipes restantes - seront placées en liste d'attente. -
-

- Pour les équipes dont l'inscription aura été validée, des documents à télécharger, remplir et signer - deviendront disponibles sur votre compte. Vous allez devoir ensuite les scanner et les télécharger vers - le site pour compléter votre inscription. -

-
- Attention Les équipes qui ne respecteront pas les délais pour rendre ces documents - risquent d'être disqualifiées et de laisser leur place aux équipes placées en liste d'attente. -
-
- - -
- Ce site est récent et il est encore possible que certaines pages ne fonctionnent - pas correctement. -
- Si vous remarquez des bugs, merci de les signaler à l'adresse - contact@tfjm.org. -
- -
\ No newline at end of file diff --git a/server_files/views/index.php b/server_files/views/index.php deleted file mode 100644 index 7c8e0b0..0000000 --- a/server_files/views/index.php +++ /dev/null @@ -1,28 +0,0 @@ - -
- - - -
- -
- -
-
- -
- - Modifier la page - - - -
-

getFirstName() . " " . $user->getSurname() ?>

-
- - -
- La personne a bien été exclue de l'équipe ! -
- -
- La personne a bien rejoint l'équipe ! -
- -
- La paiement a bien été validé / rejeté ! Un mail a été transmis au participant. -
- - - -
- Rôle : getRole()) ?> -
- -getRole() == Role::PARTICIPANT || $user->getRole() == Role::ENCADRANT) { ?> -
- Équipe - : getTrigram() . "\">" - . $team->getName() . " (" . $team->getTrigram() . ")" ?> - -
-
-
- - -
-
-
- -
-
- getValidationStatus() == ValidationStatus::NOT_READY) { ?> -
- - Exclure de l'équipe -
- -
- - -getRole() == Role::PARTICIPANT || $user->getRole() == Role::ENCADRANT) { -?> -
- Date de naissance : getBirthDate()) ?>
-
- -
- Genre : getGender() == "M" ? "Masculin" : "Féminin" ?>
-
- -
- Adresse : getAddress() . ", " . $user->getPostalCode() . " " . $user->getCity() . ($user->getCountry() == "France" ? "" : ", " . $user->getCountry()) ?>
-
- - -
- Adresse e-mail : getEmail() ?>
-
- -
- Numéro de téléphone : getPhoneNumber() ?>
-
- -getRole() == Role::PARTICIPANT) { ?> -
- Lycée : getSchool() ?>
- Classe : getClass()) ?> -
- -
- Nom du responsable légal : getResponsibleName() ?> -
- -
- Numéro de téléphone du responsable légal : getResponsiblePhone() ?> -
- -
- Adresse e-mail du responsable légal : getResponsibleEmail() ?> -
- - getRole() == Role::PARTICIPANT && $user->getTeamId() > 0) { ?> -
- Récapitulatif du paiement :

- - getValidationStatus() == ValidationStatus::NOT_READY) { ?> -
- Cette personne n'a pas encore payé sa participation. -
- - Tournoi : getName() ?>
- Montant : getAmount() ?> €
- Moyen de paiement : getMethod()) ?>
- getMethod() == PaymentMethod::SCHOLARSHIP) { ?> - Notification de bourse : Télécharger

- - Informations sur le paiement : getTransactionInfos() ?>

- getValidationStatus() == ValidationStatus::WAITING) { ?> -
- Le paiement n'a pas encore été validé. - -
- - -
- - -
- - - -
-
- -
- Le paiement a été validé. -
- - -
- -
- En raison du changement de format du TFJM² 2020, le tournoi est devenu gratuit. Il n'y a plus d'informations de - paiement à donner. -
- -getDescription() != "") { ?> -
- Description : getDescription() ?> -
-getRole() == Role::ADMIN || $user->getRole() == Role::ORGANIZER) { - foreach ($user->getOrganizedTournaments() as $tournament) { - echo ""; - } -} -elseif (($user->getRole() == Role::PARTICIPANT || $user->getRole() == Role::ENCADRANT) && $user->getTeamId() !== NULL) { ?> - -

Documents

- isSelectedForFinal()) { ?> -
-

Documents pour la finale

- getRole() != Role::ADMIN && $team == null) { ?> -
- -
- -
- -
-
- getSurname() ?>"/> -
- - -
-

Formulaire d'inscription

-
- - -
- Vous êtes bien inscrit ! Merci désormais de confirmer votre boîte mail pour valider votre adresse. Pensez à vérifier - vos courriers indésirables. -
- -
- Vous êtes déjà connecté ! -
- - -
-
-
- - -
-
- -
-
- - -
- -
- - -
-
- -
-
- - -
-
- - -
-
- -
-
- - -
-
- - -
-
- -
-
- -
-
- /> - -
-
- /> - -
-
-
- - -
-
- -
-
- - -
-
- - -
-
- - -
-
- - " required/> -
-
-
-
- - -
-
- - -
-
- -
-
- - - -
-
- - - - -
-
- - - - -
- -
- -
- - - -
- -
- -
-
- - - - - - \ No newline at end of file diff --git a/server_files/views/mon_compte.php b/server_files/views/mon_compte.php deleted file mode 100644 index a086c7f..0000000 --- a/server_files/views/mon_compte.php +++ /dev/null @@ -1,266 +0,0 @@ - - -
-

Mon compte

-
- - -
- Le fichier a été correctement envoyé ! -
- - - -
- Votre compte a bien été mis à jour ! -
- getEmail() != $my_account->email) { ?> -
- Votre adresse mail a bien été changée. Veuillez vérifier votre boîte mail pour valider votre nouvelle - adresse, vous en aurez besoin pour vous reconnecter. -
- - - -
- -
-
- - -
- -
- - -
-
- -
-
- - -
-
- - -
-
- - getRole() == Role::PARTICIPANT || $user->getRole() == Role::ENCADRANT) { ?> - -
-
- -
-
- getGender() == "M" ? "checked" : "" ?> /> - -
-
- getGender() == "F" ? "checked" : "" ?> /> - -
-
-
- - -
-
- -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - - - getRole() == Role::PARTICIPANT) { ?> - -
-
- - -
-
- - -
-
- -
-
- - - -
-
- - - - -
-
- - - - -
- -
- - - -
- - - -
- - - -
- -
-
- -
- -
- -
-
- - -
- -
- - -
- -
- - -
-
- -
- -
-
- -getRole() == Role::PARTICIPANT || $user->getRole() == Role::ENCADRANT)) { - $not_validated = $_SESSION["team"]->getValidationStatus() == ValidationStatus::NOT_READY; - ?> -
-
-

Mes documents

-
- -
- Ces documents peuvent être modifiés tant que l'équipe n'est pas validée. Les fichiers doivent peser au maximum 2 Mo et doivent - être au format PDF. -
- -
- En raison du changement de format du TFJM² 2020, il n'y a plus de document nécessaire à envoyer. Seule la lettre de motivation - pourra être considérée, même si son envoi n'est plus obligatoire. Merci de ne pas prêter attention à la partie qui suit. -
- -
- Modèle de fiche sanitaire : Télécharger
- getBirthDate() > strval($YEAR - 18) . substr($tournament->getStartDate(), 4)) { ?> - Modèle d'autorisation parentale : Télécharger - - Modèle vierge
- - Modèle d'autorisation de droit à l'image : Télécharger - - Modèle vierge -
- - - -
- Les fichiers doivent être au format PDF, PNG ou JPEG et peser moins de 2 Mo. -
- -
- -
-
- - -
-
- -
-
- - -
-
- -
- -
-
- - - - \ No newline at end of file diff --git a/server_files/views/mon_equipe.php b/server_files/views/mon_equipe.php deleted file mode 100644 index b86b5d7..0000000 --- a/server_files/views/mon_equipe.php +++ /dev/null @@ -1,184 +0,0 @@ - - -
-

Mon équipe

-
- -
- Nom de l'équipe : getName() ?> -
-
- Trigramme : getTrigram() ?> -
-
- Tournoi : - getName() . "\">" . $tournament->getName() . "" ?> -
-
- getEncadrants()[$i - 1] == NULL) - continue; - $encadrant = User::fromId($team->getEncadrants()[$i - 1]); - $id = $encadrant->getId(); - echo "Encadrant $i : getFirstName() . " " . $encadrant->getSurname() . "\">" . $encadrant->getFirstName() . " " . $encadrant->getSurname() . "
"; - } - for ($i = 1; $i <= 6; ++$i) { - if ($team->getParticipants()[$i - 1] == NULL) - continue; - $participant = User::fromId($team->getParticipants()[$i - 1]); - $id = $participant->getId(); - echo "Participant $i : getFirstName() . " " . $participant->getSurname() . "\">" . $participant->getFirstName() . " " . $participant->getSurname() . "
"; - } - ?> -
- -
- Code d'accès : getAccessCode() ?> -
- -isSelectedForFinal()) { - $final_name = $FINAL->getName(); - echo "
Équipe sélectionnée pour la finale nationale.
"; -} ?> - - - -
-
-
- - -
- -
- - -
-
- -
- - -
- -
- -
-
- - - - getValidationStatus() == ValidationStatus::NOT_READY) { ?> - - - - - - getValidationStatus() == ValidationStatus::NOT_READY) { ?> -
- -
- -
- - -
-
- - -
- Attention ! Une fois votre équipe validée, vous ne pourrez plus modifier le nom - de l'équipe, le trigramme ou la composition de l'équipe. -
- -
- -
-
- Pour demander à valider votre équipe, vous devez avoir au moins un encadrant, quatre participants - et soumis une autorisation de droit à l'image, une fiche sanitaire et une autorisation - parentale (si besoin) par participant, ainsi qu'une lettre de motivation à transmettre aux organisateurs. - Les encadrants doivent également fournir une autorisation de droit à l'image. -
- -
-
- En raison du changement de format du TFJM² 2020, il n'y a plus de document obligatoire à envoyer. Les autorisations - précédemment envoyées ont été détruites. Seules les lettres de motivation ont été conservées, mais leur envoi - n'est plus obligatoire. -
- getValidationStatus() == ValidationStatus::WAITING) { ?> -
- Votre équipe est en attente de validation. -
- - -
- -

Documents de l'équipe

- isSelectedForFinal()) { ?> -
- -

Documents de l'équipe pour la finale

- - - - - -getValidationStatus() == ValidationStatus::VALIDATED) { ?> -
-

Solutions à opposer/rapporter

-
- Modèle vierge de note de synthèse (PDF -- TEX) -
- -
- Les solutions du tour 1 seront disponibles sur cette page peu après le tirage. -
- getSolutionsDate2()) { ?> -
- Les solutions du tour 2 pourront être téléchargées sur cette page à partir du getSolutionsDate2(), true) ?>. -
-getFileId(); - $problem = $sol->getProblem(); - $t = Team::fromId($sol->getTeamId()); - $trigram = $t->getTrigram(); - echo "
getSolutionsDate2() ? "danger" : "info") . "\">Problème $problem " - . " de l'équipe $trigram " . ($source == DestType::OPPOSANT ? "opposé" : "rapporté") . ", tour $round : Télécharger
\n"; - } - ?> - - - - \ No newline at end of file diff --git a/server_files/views/organisateurs.php b/server_files/views/organisateurs.php deleted file mode 100644 index 4e5ebea..0000000 --- a/server_files/views/organisateurs.php +++ /dev/null @@ -1,76 +0,0 @@ - - -
-

Liste des organisateurs

-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Nom - - Prénom - - Adresse e-mail - - Est administrateur -
- getSurname() ?>"> - getSurname() ?> - - - getSurname() ?>"> - getFirstName() ?> - - - - getEmail() ?> - - - getRole() == Role::ADMIN ? "oui" : "non" ?> -
- Nom - - Prénom - - Adresse e-mail - - Est administrateur -
- - - -
-

Paiement

-
- -getValidationStatus() == ValidationStatus::NOT_READY) { ?> -
- Le prix du tournoi est de getPrice() ?> €. Vous pouvez par carte bancaire via - la plateforme dédiée, - et indiquer sur cette page les informations de paiement qui nous permettront de le retrouver. - Si ce n'est pas possible, vous pouvez également procéder à un virement sur le compte :

- IBAN : FR76 1027 8065 0000 0206 4290 127
- BIC : CMCIFR2A

- en précisant bien en référence du virement la mention TFJMpu suivie des nom et prénom de l'élève.

- Si aucune de ces procédures n’est possible pour vous, envoyez un mail à contact@tfjm.org - pour que nous trouvions une solution à vos difficultés. -
- -
-
- - - - - - - -
-
- - -getValidationStatus() == ValidationStatus::WAITING) { ?> -
- Votre paiement est en attente de validation. -
- -
- Votre paiement a bien été validé. -
- - -
- Récapitulatif du paiement :

- - Tournoi : getName() ?>
- Montant : getAmount() ?> €
- Moyen de paiement : getMethod()) ?>
- getMethod() == PaymentMethod::SCHOLARSHIP) { ?> - Notification de bourse : Télécharger
- - Informations sur le paiement : getTransactionInfos() ?>
- -
- - - -
-

-
- -
- Cette page recense tous les utilisateurs inscrits. -
- - - -
- - - - - - - - - - - - - - - - - - - - - - - - - -
- Nom - - Rôle - - Inscrit le -
- getFirstName() . " " . $user->getSurname() ?>"> - getFirstName() . " " . $user->getSurname() ?> - - getRole()) ?>getInscriptionDate(), true) ?>
- Nom - - Rôle - - Inscrit le -
- - - -
-

Rejoindre une équipe

-
- - -
- Vous avez bien rejoint l'équipe getName() ?> ! -
- - - 0) { ?> -
- Vous êtes déjà inscrit dans une équipe. Vous pouvez toutefois encadrer plusieurs équipes. -
- - -
-
-
- - -
-
- -
- -
-
- - - - \ No newline at end of file diff --git a/server_files/views/solutions.php b/server_files/views/solutions.php deleted file mode 100644 index a567353..0000000 --- a/server_files/views/solutions.php +++ /dev/null @@ -1,62 +0,0 @@ - -
- Le fichier a été correctement envoyé ! -
- - -getSolutionsDate()) { ?> -
- -
-
- - -
- -
- - -
-
- - -
- - -
- -

Solutions soumises :

- -getFileId(); - $problem = $sol->getProblem(); - $version = $sol->getVersion(); - echo "
Problème $problem (Version $version) : Télécharger
\n"; -} - -if ($team->isSelectedForFinal()) { ?> -
- -

Solutions soumises pour la finale :

- getFileId(); - $problem = $sol->getProblem(); - $version = $sol->getVersion(); - echo "
Problème $problem (Version $version) : Télécharger
\n"; - } -} - -require_once "footer.php"; diff --git a/server_files/views/solutions_orga.php b/server_files/views/solutions_orga.php deleted file mode 100644 index aa7595d..0000000 --- a/server_files/views/solutions_orga.php +++ /dev/null @@ -1,30 +0,0 @@ - - -
-

Solutions

-
- -Tournoi de " . $tournament->getName() . "\n"; - $sols = $tournament->getAllSolutions(); - /** @var Solution $sol */ - foreach ($sols as $sol) { - $file_id = $sol->getFileId(); - $problem = $sol->getProblem(); - $version = $sol->getVersion(); - $team = Team::fromId($sol->getTeamId()); - $team_name = $team->getName(); - $team_trigram = $team->getTrigram(); - echo "
Problème n°$problem de l'équipe $team_name ($team_trigram), version $version : Télécharger
"; - } - - echo "
\n"; - echo "getId() . "\" />\n"; - echo "\n"; - echo "
\n"; -} - -require_once "server_files/views/footer.php"; \ No newline at end of file diff --git a/server_files/views/syntheses.php b/server_files/views/syntheses.php deleted file mode 100644 index 3b746a3..0000000 --- a/server_files/views/syntheses.php +++ /dev/null @@ -1,80 +0,0 @@ -getSolutionsDate()) { - echo "

Il est trop tôt pour se préoccuper des notes de synthèse, attendez le tirage des poules.

"; - require_once "server_files/views/footer.php"; -} - -if (isset($save_synthesis) && !$has_error) { ?> -
- Le fichier a été correctement envoyé ! -
- - -getSynthesesDate2()) { - if (date("Y-m-d H:i:s") < $tournament->getSynthesesDate()) { - ?> -
- Attention : la date butoir de soumission des notes de synthèse pour le tour 1 est passée. Les prochaines notes de synthèses compteront pour le second tour. -
- -
- -
-
- - -
- -
- - -
- -
- - -
-
- - -
- - -
- -

Notes de synthèse soumises :

- -getFileId(); - $dest = $synthesis->getDest(); - $round = $synthesis->getRound(); - $version = $synthesis->getVersion(); - echo "
Note de synthèse " . ($dest == DestType::OPPOSANT ? "de l'opposant" : "du rapporteur") . ", tour $round (version $version) : Télécharger
"; -} - -if ($team->isSelectedForFinal()) { ?> -
- -

Notes de synthèse soumises pour la finale :

- getFileId(); - $dest = $synthesis->getDest(); - $round = $synthesis->getRound(); - $version = $synthesis->getVersion(); - echo "
Note de synthèse " . ($dest == DestType::OPPOSANT ? "de l'opposant" : "du rapporteur") . ", tour $round (version $version) : Télécharger
"; - } -} - -require_once "footer.php"; \ No newline at end of file diff --git a/server_files/views/syntheses_orga.php b/server_files/views/syntheses_orga.php deleted file mode 100644 index 9106b65..0000000 --- a/server_files/views/syntheses_orga.php +++ /dev/null @@ -1,33 +0,0 @@ - - -
-

Notes de synthèse

-
- -Tournoi de " . $tournament->getName() . "\n"; - $syntheses = $tournament->getAllSyntheses(); - /** @var Synthesis $synthesis */ - foreach ($syntheses as $synthesis) { - $file_id = $synthesis->getFileId(); - $dest = $synthesis->getDest(); - $round = $synthesis->getRound(); - $version = $synthesis->getVersion(); - $team = Team::fromId($synthesis->getTeamId()); - $team_name = $team->getName(); - $team_trigram = $team->getTrigram(); - echo "
Note de synthèse de l'équipe $team_name ($team_trigram) pour " . ($dest == DestType::OPPOSANT ? "l'opposant" : "le rapporteur") - . ", tour $round, version $version : Télécharger
"; - } - - echo "
\n"; - echo "getId() . "\" />\n"; - echo "\n"; - echo "
\n"; -} - -require_once "server_files/views/footer.php"; diff --git a/server_files/views/tournoi.php b/server_files/views/tournoi.php deleted file mode 100644 index 9b54849..0000000 --- a/server_files/views/tournoi.php +++ /dev/null @@ -1,241 +0,0 @@ - - -
-

Tournoi de getName() ?>

-
- - - -
- Organisateur= 2 ? 's' : '' ?> : - getId(); - $orga_name = $orga->getFirstName() . " " . $orga->getSurname(); - if ($_SESSION["role"] == Role::ORGANIZER || $_SESSION["role"] == Role::ADMIN) - $s .= "$orga_name"; - else - $s .= $orga_name; - $s .= ", "; - } - echo substr($s, 0, -2); - ?> -
-
- Nombre d'équipes maximal : getSize() ?> -
-
- Lieu : getPlace() ?> -
- -
- Dates : Du getStartDate()) ?> au getEndDate()) ?> -
-
- Clôture des inscriptions : getInscriptionDate(), true) ?> -
-
- Date limite d'envoi des solutions : getSolutionsDate(), true) ?> -
-
- Date limite d'envoi des notes de synthèse - tour 1 : getSynthesesDate(), true) ?> -
-
- Date à partir de laquelle les solutions du tour 2 sont disponibles : getSolutionsDate2(), true) ?> -
-
- Date limite d'envoi des notes de synthèse - tour 2 : getSynthesesDate2(), true) ?> -
-
- Description : getDescription() ?> -
-isFinal()) - echo "
\n\tCe tournoi est la finale nationale du TFJM² 2020.\n
\n"; -?> - -organize($_SESSION["user_id"]))) { ?> - - - - - - - -
- -

Équipes inscrites à ce tournoi :

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- Équipe - - Trigramme - - Date d'inscription - - État de validation de l'inscription -
- organize($_SESSION["user_id"])))) - echo "getTrigram() . "\">" . $team->getName(). ""; - else - echo $team->getName(); - ?> - getTrigram() ?>getInscriptionDate()) ?>getValidationStatus()) ?>
- Équipe - - Trigramme - - Date d'inscription - - État de validation de l'inscription -
- - -
-
- - -
- -
- - -
- - -
-
- - -
- -
- - -
- -
- - -
-
- -
-
- - -
- -
- - -
-
- -
-
- - - -
- -
- - - -
- -
- - - -
-
- -
-
- - - -
- -
- - - -
-
- -
-
- - -
-
- - -
- - - - diff --git a/server_files/views/tournois.php b/server_files/views/tournois.php deleted file mode 100644 index 5c7526d..0000000 --- a/server_files/views/tournois.php +++ /dev/null @@ -1,52 +0,0 @@ - - -
-

Liste des tournois

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NomDatesInscription avant leDate de rendu des solutionsPlaces disponibles
- getName() ?> - Du getStartDate()) ?> au getEndDate()) ?>getInscriptionDate()) ?>getSolutionsDate()) ?>getSize() ?>
NomDatesInscription avant leDate de rendu des solutionsPlaces disponibles
- - diff --git a/setup/create_database.sql b/setup/create_database.sql deleted file mode 100644 index bc1eb1f..0000000 --- a/setup/create_database.sql +++ /dev/null @@ -1,275 +0,0 @@ --- phpMyAdmin SQL Dump --- version 4.7.5 --- https://www.phpmyadmin.net/ --- --- Host: db --- Erstellungszeit: 18. Feb 2020 um 14:32 --- Server-Version: 5.7.20 --- PHP-Version: 7.1.9 - -SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; -SET AUTOCOMMIT = 0; -START TRANSACTION; -SET time_zone = "+02:00"; - - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8mb4 */; - --- --- Datenbank: `inscription_tfjm` --- -CREATE DATABASE IF NOT EXISTS `inscription_tfjm` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; -USE `inscription_tfjm`; - --- -------------------------------------------------------- - --- --- Tabellenstruktur für Tabelle `documents` --- - -CREATE TABLE `documents` ( - `file_id` varchar(64) NOT NULL, - `user` int(11) NOT NULL, - `team` int(11) NOT NULL, - `tournament` int(11) NOT NULL, - `type` varchar(64) NOT NULL, - `uploaded_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Tabellenstruktur für Tabelle `organizers` --- - -CREATE TABLE `organizers` ( - `id` int(11) NOT NULL, - `organizer` int(11) NOT NULL, - `tournament` int(11) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Tabellenstruktur für Tabelle `payments` --- - -CREATE TABLE `payments` ( - `id` int(11) NOT NULL, - `user` int(11) NOT NULL, - `tournament` int(11) NOT NULL, - `amount` tinyint(4) NOT NULL, - `method` enum('CREDIT_CARD','BANK_CHECK','BANK_TRANSFER','CASH','SCHOLARSHIP','NOT_PAID') COLLATE utf8_unicode_ci NOT NULL, - `transaction_infos` text COLLATE utf8_unicode_ci NOT NULL, - `validation_status` enum('NOT_READY','WAITING','VALIDATED','') COLLATE utf8_unicode_ci NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - --- -------------------------------------------------------- - --- --- Tabellenstruktur für Tabelle `solutions` --- - -CREATE TABLE `solutions` ( - `file_id` varchar(64) NOT NULL, - `team` int(11) NOT NULL, - `tournament` int(11) NOT NULL, - `problem` int(11) NOT NULL, - `uploaded_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Tabellenstruktur für Tabelle `syntheses` --- - -CREATE TABLE `syntheses` ( - `file_id` varchar(64) NOT NULL, - `team` int(11) NOT NULL, - `tournament` int(11) NOT NULL, - `dest` varchar(64) NOT NULL, - `uploaded_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Tabellenstruktur für Tabelle `teams` --- - -CREATE TABLE `teams` ( - `id` int(11) NOT NULL, - `name` varchar(64) NOT NULL, - `trigram` varchar(3) NOT NULL, - `tournament` int(8) NOT NULL, - `encadrant_1` int(8) DEFAULT NULL, - `encadrant_2` int(8) DEFAULT NULL, - `encadrant_3` int(11) DEFAULT NULL, - `participant_1` int(8) DEFAULT NULL, - `participant_2` int(8) DEFAULT NULL, - `participant_3` int(8) DEFAULT NULL, - `participant_4` int(8) DEFAULT NULL, - `participant_5` int(8) DEFAULT NULL, - `participant_6` int(8) DEFAULT NULL, - `inscription_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - `validation_status` enum('NOT_READY','WAITING','VALIDATED','') NOT NULL, - `final_selection` tinyint(1) NOT NULL DEFAULT '0', - `access_code` varchar(6) NOT NULL, - `year` int(4) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Tabellenstruktur für Tabelle `tournaments` --- - -CREATE TABLE `tournaments` ( - `id` int(8) NOT NULL, - `name` varchar(64) NOT NULL, - `size` int(1) NOT NULL, - `place` varchar(255) NOT NULL, - `price` int(4) NOT NULL, - `description` varchar(255) NOT NULL, - `date_start` date NOT NULL, - `date_end` date NOT NULL, - `date_inscription` datetime NOT NULL, - `date_solutions` datetime NOT NULL, - `date_syntheses` datetime NOT NULL, - `final` tinyint(1) NOT NULL DEFAULT '0', - `year` int(4) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- -------------------------------------------------------- - --- --- Tabellenstruktur für Tabelle `users` --- - -CREATE TABLE `users` ( - `id` int(8) NOT NULL, - `email` varchar(255) NOT NULL, - `pwd_hash` varchar(64) NOT NULL, - `surname` varchar(255) NOT NULL, - `first_name` varchar(255) NOT NULL, - `birth_date` date DEFAULT NULL, - `gender` char(1) DEFAULT NULL, - `address` varchar(255) DEFAULT NULL, - `postal_code` int(5) DEFAULT NULL, - `city` varchar(255) DEFAULT NULL, - `country` varchar(255) DEFAULT 'France', - `phone_number` varchar(20) DEFAULT NULL, - `school` varchar(255) DEFAULT NULL, - `class` enum('SECONDE','PREMIERE','TERMINALE','ADULT') DEFAULT NULL, - `responsible_name` varchar(255) DEFAULT NULL, - `responsible_phone` varchar(20) DEFAULT NULL, - `responsible_email` varchar(255) DEFAULT NULL, - `description` varchar(255) DEFAULT NULL, - `role` enum('PARTICIPANT','ENCADRANT','ORGANIZER','ADMIN') NOT NULL, - `team_id` int(8) DEFAULT NULL, - `year` int(4) NOT NULL DEFAULT '2020', - `confirm_email` varchar(64) DEFAULT NULL COMMENT 'Jeton de confirmation d''e-mail', - `forgotten_password` varchar(64) DEFAULT NULL COMMENT 'Jeton de récupération de mot de passe', - `inscription_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - --- --- Indizes der exportierten Tabellen --- - --- --- Indizes für die Tabelle `documents` --- -ALTER TABLE `documents` - ADD PRIMARY KEY (`file_id`); - --- --- Indizes für die Tabelle `organizers` --- -ALTER TABLE `organizers` - ADD PRIMARY KEY (`id`), - ADD UNIQUE KEY `organizer` (`organizer`,`tournament`); - --- --- Indizes für die Tabelle `payments` --- -ALTER TABLE `payments` - ADD PRIMARY KEY (`id`), - ADD UNIQUE KEY `user` (`user`); - --- --- Indizes für die Tabelle `solutions` --- -ALTER TABLE `solutions` - ADD PRIMARY KEY (`file_id`); - --- --- Indizes für die Tabelle `syntheses` --- -ALTER TABLE `syntheses` - ADD PRIMARY KEY (`file_id`); - --- --- Indizes für die Tabelle `teams` --- -ALTER TABLE `teams` - ADD PRIMARY KEY (`id`), - ADD UNIQUE KEY `name/year` (`name`,`year`), - ADD UNIQUE KEY `trigram/year` (`trigram`,`year`); - --- --- Indizes für die Tabelle `tournaments` --- -ALTER TABLE `tournaments` - ADD PRIMARY KEY (`id`), - ADD UNIQUE KEY `Name/year` (`name`,`year`) USING BTREE; - --- --- Indizes für die Tabelle `users` --- -ALTER TABLE `users` - ADD PRIMARY KEY (`id`), - ADD UNIQUE KEY `email/year` (`email`,`year`) USING BTREE; - --- --- AUTO_INCREMENT für exportierte Tabellen --- - --- --- AUTO_INCREMENT für Tabelle `organizers` --- -ALTER TABLE `organizers` - MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=40; - --- --- AUTO_INCREMENT für Tabelle `payments` --- -ALTER TABLE `payments` - MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=111; - --- --- AUTO_INCREMENT für Tabelle `teams` --- -ALTER TABLE `teams` - MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=61; - --- --- AUTO_INCREMENT für Tabelle `tournaments` --- -ALTER TABLE `tournaments` - MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; - --- --- AUTO_INCREMENT für Tabelle `users` --- -ALTER TABLE `users` - MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=370; -COMMIT; - -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/setup/msmtprc b/setup/msmtprc deleted file mode 100644 index 3a3cc60..0000000 --- a/setup/msmtprc +++ /dev/null @@ -1,18 +0,0 @@ -defaults -auth on -tls on -tls_starttls off -tls_trust_file /etc/ssl/certs/ca-certificates.crt -syslog on -logfile /var/log/msmtp.log - -account tfjm -host ssl0.ovh.net -auth on -port 465 -from contact@tfjm.org -user contact@tfjm.org -passwordeval "echo $TFJM_MAIL_PASSWORD" - -# Set a default account -account default : tfjm diff --git a/static/Autorisation_droit_image_majeur.tex b/static/Autorisation_droit_image_majeur.tex deleted file mode 100644 index 7cb1727..0000000 --- a/static/Autorisation_droit_image_majeur.tex +++ /dev/null @@ -1,113 +0,0 @@ -\documentclass[a4paper,french,11pt]{article} - -\usepackage[T1]{fontenc} -\usepackage[utf8]{inputenc} -\usepackage{lmodern} -\usepackage[frenchb]{babel} - -\usepackage{fancyhdr} -\usepackage{graphicx} -\usepackage{amsmath} -\usepackage{amssymb} -%\usepackage{anyfontsize} -\usepackage{fancybox} -\usepackage{eso-pic,graphicx} -\usepackage{xcolor} - - -% Specials -\newcommand{\writingsep}{\vrule height 4ex width 0pt} - -% Page formating -\hoffset -1in -\voffset -1in -\textwidth 180 mm -\textheight 250 mm -\oddsidemargin 15mm -\evensidemargin 15mm -\pagestyle{fancy} - -% Headers and footers -\fancyfoot{} -\lhead{} -\rhead{} -\renewcommand{\headrulewidth}{0pt} -\lfoot{\footnotesize 11 rue Pierre et Marie Curie, 75231 Paris Cedex 05\\ Numéro siret 431 598 366 00018} -\rfoot{\footnotesize Association agréée par\\le Ministère de l'éducation nationale.} - -\begin{document} - -\includegraphics[height=2cm]{assets/logo_animath.png}\hfill{\fontsize{55pt}{55pt}{$\mathbb{TFJM}^2$}} - -\vfill - -\begin{center} - - -\LARGE -Autorisation d'enregistrement et de diffusion de l'image ({TOURNAMENT_NAME}) -\end{center} -\normalsize - - -\thispagestyle{empty} - -\bigskip - - - -Je soussign\'e {PARTICIPANT_NAME}\\ -demeurant au {ADDRESS} - -\medskip -Cochez la/les cases correspondantes.\\ -\medskip - - \fbox{\textcolor{white}{A}} Autorise l'association Animath, \`a l'occasion du $\mathbb{TFJM}^2$ du {START_DATE} au {END_DATE} {YEAR} à : {PLACE}, \`a me photographier ou \`a me filmer et \`a diffuser les photos et/ou les vid\'eos r\'ealis\'ees \`a cette occasion sur son site et sur les sites partenaires. D\'eclare c\'eder \`a titre gracieux \`a Animath le droit d’utiliser mon image sur tous ses supports d'information : brochures, sites web, r\'eseaux sociaux. Animath devient, par la pr\'esente, cessionnaire des droits pendant toute la dur\'ee pour laquelle ont \'et\'e acquis les droits d'auteur de ces photographies.\\ - -\medskip -Animath s'engage, conform\'ement aux dispositions l\'egales en vigueur relatives au droit \`a l'image, \`a ce que la publication et la diffusion de l'image ainsi que des commentaires l'accompagnant ne portent pas atteinte \`a la vie priv\'ee, \`a la dignit\'e et \`a la r\'eputation de la personne photographiée.\\ - -\medskip - \fbox{\textcolor{white}{A}} Autorise la diffusion dans les medias (Presse, T\'el\'evision, Internet) de photographies prises \`a l'occasion d’une \'eventuelle m\'ediatisation de cet événement.\\ - - \medskip - -Conform\'ement \`a la loi informatique et libert\'es du 6 janvier 1978, vous disposez d'un droit de libre acc\`es, de rectification, de modification et de suppression des donn\'ees qui vous concernent. -Cette autorisation est donc r\'evocable \`a tout moment sur volont\'e express\'ement manifest\'ee par lettre recommand\'ee avec accus\'e de r\'eception adress\'ee \`a Animath, IHP, 11 rue Pierre et Marie Curie, 75231 Paris cedex 05.\\ - -\medskip - \fbox{\textcolor{white}{A}} Autorise Animath à conserver mes données personnelles, dans le cadre défini par la loi n 78-17 du 6 janvier 1978 relative à l'informatique, aux fichiers et aux libertés et les textes la modifiant, pendant une durée de quatre ans à compter de ma dernière participation à un événement organisé par Animath.\\ - - \medskip - \fbox{\textcolor{white}{A}} J'accepte d'être tenu informé d'autres activités organisées par l'association et ses partenaires. - -\bigskip - -Signature pr\'ec\'ed\'ee de la mention \og lu et approuv\'e \fg{} - -\medskip - - - -\begin{minipage}[c]{0.5\textwidth} - -\underline{L'\'el\`eve :}\\ - -Fait \`a :\\ -le -\end{minipage} - - -\vfill -\vfill -\begin{minipage}[c]{0.5\textwidth} -\footnotesize 11 rue Pierre et Marie Curie, 75231 Paris Cedex 05\\ Numéro siret 431 598 366 00018 -\end{minipage} -\begin{minipage}[c]{0.5\textwidth} -\footnotesize -\begin{flushright} -Association agréée par\\le Ministère de l'éducation nationale. -\end{flushright} -\end{minipage} -\end{document} diff --git a/static/Autorisation_droit_image_mineur.tex b/static/Autorisation_droit_image_mineur.tex deleted file mode 100644 index 4f14a43..0000000 --- a/static/Autorisation_droit_image_mineur.tex +++ /dev/null @@ -1,122 +0,0 @@ -\documentclass[a4paper,french,11pt]{article} - -\usepackage[T1]{fontenc} -\usepackage[utf8]{inputenc} -\usepackage{lmodern} -\usepackage[frenchb]{babel} - -\usepackage{fancyhdr} -\usepackage{graphicx} -\usepackage{amsmath} -\usepackage{amssymb} -%\usepackage{anyfontsize} -\usepackage{fancybox} -\usepackage{eso-pic,graphicx} -\usepackage{xcolor} - - -% Specials -\newcommand{\writingsep}{\vrule height 4ex width 0pt} - -% Page formating -\hoffset -1in -\voffset -1in -\textwidth 180 mm -\textheight 250 mm -\oddsidemargin 15mm -\evensidemargin 15mm -\pagestyle{fancy} - -% Headers and footers -\fancyfoot{} -\lhead{} -\rhead{} -\renewcommand{\headrulewidth}{0pt} -\lfoot{\footnotesize 11 rue Pierre et Marie Curie, 75231 Paris Cedex 05\\ Numéro siret 431 598 366 00018} -\rfoot{\footnotesize Association agréée par\\le Ministère de l'éducation nationale.} - -\begin{document} - -\includegraphics[height=2cm]{assets/logo_animath.png}\hfill{\fontsize{55pt}{55pt}{$\mathbb{TFJM}^2$}} - -\vfill - -\begin{center} - - -\LARGE -Autorisation d'enregistrement et de diffusion de l'image -({TOURNAMENT_NAME}) -\end{center} -\normalsize - - -\thispagestyle{empty} - -\bigskip - - - -Je soussign\'e \dotfill (p\`ere, m\`ere, responsable l\'egal) \\ -agissant en qualit\'e de repr\'esentant de {PARTICIPANT_NAME}\\ -demeurant au {ADDRESS} - -\medskip -Cochez la/les cases correspondantes.\\ -\medskip - - \fbox{\textcolor{white}{A}} Autorise l'association Animath, \`a l'occasion du $\mathbb{TFJM}^2$ du {START_DATE} au {END_DATE} {YEAR} à : {PLACE}, \`a photographier ou \`a filmer l'enfant et \`a diffuser les photos et/ou les vid\'eos r\'ealis\'ees \`a cette occasion sur son site et sur les sites partenaires. D\'eclare c\'eder \`a titre gracieux \`a Animath le droit d’utiliser l'image de l'enfant sur tous ses supports d'information : brochures, sites web, r\'eseaux sociaux. Animath devient, par la pr\'esente, cessionnaire des droits pendant toute la dur\'ee pour laquelle ont \'et\'e acquis les droits d'auteur de ces photographies.\\ - -\medskip -Animath s'engage, conform\'ement aux dispositions l\'egales en vigueur relatives au droit \`a l'image, \`a ce que la publication et la diffusion de l'image de l'enfant ainsi que des commentaires l'accompagnant ne portent pas atteinte \`a la vie priv\'ee, \`a la dignit\'e et \`a la r\'eputation de l’enfant.\\ - -\medskip - \fbox{\textcolor{white}{A}} Autorise la diffusion dans les medias (Presse, T\'el\'evision, Internet) de photographies de mon enfant prises \`a l'occasion d’une \'eventuelle m\'ediatisation de cet événement.\\ - - \medskip - -Conform\'ement \`a la loi informatique et libert\'es du 6 janvier 1978, vous disposez d'un droit de libre acc\`es, de rectification, de modification et de suppression des donn\'ees qui vous concernent. -Cette autorisation est donc r\'evocable \`a tout moment sur volont\'e express\'ement manifest\'ee par lettre recommand\'ee avec accus\'e de r\'eception adress\'ee \`a Animath, IHP, 11 rue Pierre et Marie Curie, 75231 Paris cedex 05.\\ - -\medskip - \fbox{\textcolor{white}{A}} Autorise Animath à conserver mes données personnelles, dans le cadre défini par la loi n 78-17 du 6 janvier 1978 relative à l'informatique, aux fichiers et aux libertés et les textes la modifiant, pendant une durée de quatre ans à compter de ma dernière participation à un événement organisé par Animath.\\ - - \medskip - \fbox{\textcolor{white}{A}} J'accepte d'être tenu informé d'autres activités organisées par l'association et ses partenaires. - - \bigskip - -Signatures pr\'ec\'ed\'ees de la mention \og lu et approuv\'e \fg{} - -\medskip - - -\begin{minipage}[c]{0.5\textwidth} - -\underline{Le responsable l\'egal :}\\ - -Fait \`a :\\ -le : - -\end{minipage} -\begin{minipage}[c]{0.5\textwidth} - -\underline{L'\'el\`eve :}\\ - -Fait \`a :\\ -le -\end{minipage} - - -\vfill -\vfill -\begin{minipage}[c]{0.5\textwidth} -\footnotesize 11 rue Pierre et Marie Curie, 75231 Paris Cedex 05\\ Numéro siret 431 598 366 00018 -\end{minipage} -\begin{minipage}[c]{0.5\textwidth} -\footnotesize -\begin{flushright} -Association agréée par\\le Ministère de l'éducation nationale. -\end{flushright} -\end{minipage} -\end{document} diff --git a/static/Fiche synthèse.pdf b/static/Fiche synthèse.pdf deleted file mode 100644 index af8ed1c..0000000 Binary files a/static/Fiche synthèse.pdf and /dev/null differ diff --git a/static/Fiche synthèse.tex b/static/Fiche synthèse.tex deleted file mode 100644 index bc2daa9..0000000 --- a/static/Fiche synthèse.tex +++ /dev/null @@ -1,194 +0,0 @@ -\documentclass{article} - -\usepackage[utf8]{inputenc} -\usepackage[french]{babel} -\usepackage{graphicx} - -\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry} % marges - -\usepackage{amsthm} -\usepackage{amsmath} -\usepackage{amsfonts} -\usepackage{amssymb} -\usepackage{tikz} - -\newcommand{\N}{{\bf N}} -\newcommand{\Z}{{\bf Z}} -\newcommand{\Q}{{\bf Q}} -\newcommand{\R}{{\bf R}} -\newcommand{\C}{{\bf C}} -\newcommand{\A}{{\bf A}} - -\newtheorem{theo}{Théorème} -\newtheorem{theo-defi}[theo]{Théorème-Définition} -\newtheorem{defi}[theo]{Définition} -\newtheorem{lemme}[theo]{Lemme} -\newtheorem{slemme}[theo]{Sous-lemme} -\newtheorem{prop}[theo]{Proposition} -\newtheorem{coro}[theo]{Corollaire} -\newtheorem{conj}[theo]{Conjecture} - -\title{Note de synthèse} - -\begin{document} -\pagestyle{empty} - -\begin{center} -\begin{Huge} -$\mathbb{TFJM}^2$ -\end{Huge} - -\bigskip - -\begin{Large} -NOTE DE SYNTHESE -\end{Large} -\end{center} - -Tour \underline{~~~~} poule \underline{~~~~} - -\medskip - -Problème \underline{~~~~} défendu par l'équipe \underline{~~~~~~~~~~~~~~~~~~~~~~~~} - -\medskip - -Synthèse par l'équipe \underline{~~~~~~~~~~~~~~~~~~~~~~~~} dans le rôle de : ~ $\square$ Opposant ~ $\square$ Rapporteur - -\section*{Questions traitées} - -\begin{tabular}{r c l} - \begin{tabular}{|c|c|c|c|c|c|} - \hline - Question ~ & ER & ~PR~ & QE & NT \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - \end{tabular} -& ~~ & - \begin{tabular}{|c|c|c|c|c|c|} - \hline - Question ~ & ER & ~PR~ & QE & NT \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - & & & & \\ - \hline - \end{tabular} \\ - - & & \\ - -ER : entièrement résolue & & PR : partiellement résolue \\ - -\smallskip - -QE : quelques éléments de réponse & & NT : non traitée -\end{tabular} - -~ - -\smallskip - -Remarque : il est possible de cocher entre les cases pour un cas intermédiaire. - -\section*{Evaluation qualitative de la solution} - -Donnez votre avis concernant la solution. Mettez notamment en valeur les points positifs (des idées -importantes, originales, etc.) et précisez ce qui aurait pu améliorer la solution. - -\vfill - -\textbf{Evaluation générale :} ~ $\square$ Excellente ~ $\square$ Bonne ~ $\square$ Suffisante ~ $\square$ Passable - -\newpage - -\section*{Erreurs et imprécisions} - -Listez ci-dessous les cinq erreurs et/ou imprécisions les plus importantes selon vous, par ordre d'importance, en précisant la -question concernée, la page, le paragraphe et le type de remarque. - -\bigskip - -1. Question \underline{~~~~} Page \underline{~~~~} Paragraphe \underline{~~~~} - -$\square$ Erreur majeure ~ $\square$ Erreur mineure ~ $\square$ Imprécision ~ $\square$ Autre : \underline{~~~~~~~~} - -Description : - -\vfill - -2. Question \underline{~~~~} Page \underline{~~~~} Paragraphe \underline{~~~~} - -$\square$ Erreur majeure ~ $\square$ Erreur mineure ~ $\square$ Imprécision ~ $\square$ Autre : \underline{~~~~~~~~} - -Description : - -\vfill - -3. Question \underline{~~~~} Page \underline{~~~~} Paragraphe \underline{~~~~} - -$\square$ Erreur majeure ~ $\square$ Erreur mineure ~ $\square$ Imprécision ~ $\square$ Autre : \underline{~~~~~~~~} - -Description : - -\vfill - -4. Question \underline{~~~~} Page \underline{~~~~} Paragraphe \underline{~~~~} - -$\square$ Erreur majeure ~ $\square$ Erreur mineure ~ $\square$ Imprécision ~ $\square$ Autre : \underline{~~~~~~~~} - -Description : - -\vfill - -5. Question \underline{~~~~} Page \underline{~~~~} Paragraphe \underline{~~~~} - -$\square$ Erreur majeure ~ $\square$ Erreur mineure ~ $\square$ Imprécision ~ $\square$ Autre : \underline{~~~~~~~~} - -Description : - -\vfill - -\section*{Remarques formelles (facultatif)} - -Donnez votre avis concernant la présentation de la solution (lisibilité, etc.). - -\vfill - - - -\end{document} diff --git a/static/Fiche_sanitaire.pdf b/static/Fiche_sanitaire.pdf deleted file mode 100644 index b828b9d..0000000 Binary files a/static/Fiche_sanitaire.pdf and /dev/null differ diff --git a/static/Instructions.tex b/static/Instructions.tex deleted file mode 100644 index da293ef..0000000 --- a/static/Instructions.tex +++ /dev/null @@ -1,88 +0,0 @@ -\documentclass[a4paper,french,11pt]{article} - -\usepackage[T1]{fontenc} -\usepackage[utf8]{inputenc} -\usepackage{lmodern} -\usepackage[frenchb]{babel} - -\usepackage{fancyhdr} -\usepackage{graphicx} -\usepackage{amsmath} -\usepackage{amssymb} -%\usepackage{anyfontsize} -\usepackage{fancybox} -\usepackage{eso-pic,graphicx} -\usepackage{xcolor} -\usepackage{hyperref} - - -% Specials -\newcommand{\writingsep}{\vrule height 4ex width 0pt} - -% Page formating -\hoffset -1in -\voffset -1in -\textwidth 180 mm -\textheight 250 mm -\oddsidemargin 15mm -\evensidemargin 15mm -\pagestyle{fancy} - -% Headers and footers -\fancyfoot{} -\lhead{} -\rhead{} -\renewcommand{\headrulewidth}{0pt} -\lfoot{\footnotesize 11 rue Pierre et Marie Curie, 75231 Paris Cedex 05\\ Numéro siret 431 598 366 00018} -\rfoot{\footnotesize Association agréée par\\le Ministère de l'éducation nationale.} - -\begin{document} - -\includegraphics[height=2cm]{assets/logo_animath.png}\hfill{\fontsize{50pt}{50pt}{$\mathbb{TFJM}^2$}} - - - -\begin{center} -\Large \bf Instructions ({TOURNAMENT_NAME}) -\end{center} - -\section{Documents} -\subsection{Autorisation parentale} -Elle est nécessaire si l'élève est mineur au moment du tournoi (y compris si son anniversaire est pendant le tournoi). - -\subsection{Autorisation de prise de vue} -Si l'élève est mineur \textbf{au moment de la signature}, il convient de remplir l'autorisation pour les mineurs. En revanche, s'il est majeur \textbf{au moment de la signature}, il convient de remplir la fiche pour majeur. - -\subsection{Fiche sanitaire} -Elle est nécessaire si l'élève est mineur au moment du tournoi (y compris si son anniversaire est pendant le tournoi). - - -\section{Paiement} - -\subsection{Montant} -Les frais d'inscription sont fixés à {PRICE} euros. Vous devez vous en acquitter \textbf{avant le {END_PAYMENT_DATE} {YEAR}}. Si l'élève est boursier, il en est dispensé, vous devez alors fournir une copie de sa notification de bourse directement sur la plateforme \textbf{avant le {END_PAYMENT_DATE} {YEAR}}. - -\subsection{Procédure} - -Si le paiement de plusieurs élèves est fait en une seule opération, merci de contacter \href{mailto: contact@tfjm.org}{contact@tfjm.org} \textbf{avant le paiement} pour garantir l'identification de ce dernier - -\subsubsection*{Carte bancaire (uniquement les cartes françaises)} -Le paiement s'effectue en ligne via la plateforme à l'adresse : \url{https://www.helloasso.com/associations/animath/evenements/tfjm-2020} - -Vous devez impérativement indiquer dans le champ "Référence" la mention "TFJMpu" suivie des noms et prénoms \textbf{de l'élève}. - -\subsubsection*{Virement} -\textbf{Si vous ne pouvez pas utiliser le paiement par carte}, vous pouvez faire un virement sur le compte ci-dessous en indiquant bien dans le champ "motif" (ou autre champ propre à votre banque dont le contenu est communiqué au destinataire) la mention "TFJMpu" suivie des noms et prénoms \textbf{de l'élève}. - -IBAN FR76 1027 8065 0000 0206 4290 127 - -BIC CMCIFR2A - -\subsubsection*{Autre} - -Si aucune de ces procédures n'est possible pour vous, envoyez un mail à \href{mailto: contact@tfjm.org}{contact@tfjm.org} pour que nous trouvions une solution à vos difficultés. - - - - -\end{document} diff --git a/static/bootstrap_datepicker_plus/css/datepicker-widget.css b/static/bootstrap_datepicker_plus/css/datepicker-widget.css deleted file mode 100644 index baeec50..0000000 --- a/static/bootstrap_datepicker_plus/css/datepicker-widget.css +++ /dev/null @@ -1,121 +0,0 @@ -@font-face { - font-family: 'Glyphicons Halflings'; - src: url('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.eot'); - src: url('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), - url('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.woff2') format('woff2'), - url('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.woff') format('woff'), - url('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.ttf') format('truetype'), - url('//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg'); -} - -.glyphicon { - position: relative; - top: 1px; - display: inline-block; - font-family: 'Glyphicons Halflings'; - font-style: normal; - font-weight: normal; - line-height: 1; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -.glyphicon-time:before { - content: "\e023"; -} - -.glyphicon-chevron-left:before { - content: "\e079"; -} - -.glyphicon-chevron-right:before { - content: "\e080"; -} - -.glyphicon-chevron-up:before { - content: "\e113"; -} - -.glyphicon-chevron-down:before { - content: "\e114"; -} - -.glyphicon-calendar:before { - content: "\e109"; -} - -.glyphicon-screenshot:before { - content: "\e087"; -} - -.glyphicon-trash:before { - content: "\e020"; -} - -.glyphicon-remove:before { - content: "\e014"; -} - -.bootstrap-datetimepicker-widget .btn { - display: inline-block; - padding: 6px 12px; - margin-bottom: 0; - font-size: 14px; - font-weight: normal; - line-height: 1.42857143; - text-align: center; - white-space: nowrap; - vertical-align: middle; - -ms-touch-action: manipulation; - touch-action: manipulation; - cursor: pointer; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; - background-image: none; - border: 1px solid transparent; - border-radius: 4px; -} - -.bootstrap-datetimepicker-widget.dropdown-menu { - position: absolute; - left: 0; - z-index: 1000; - display: none; - float: left; - min-width: 160px; - padding: 5px 0; - margin: 2px 0 0; - font-size: 14px; - text-align: left; - list-style: none; - background-color: #fff; - -webkit-background-clip: padding-box; - background-clip: padding-box; - border: 1px solid #ccc; - border: 1px solid rgba(0, 0, 0, .15); - border-radius: 4px; - -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175); - box-shadow: 0 6px 12px rgba(0, 0, 0, .175); -} - -.bootstrap-datetimepicker-widget .list-unstyled { - padding-left: 0; - list-style: none; -} - -.bootstrap-datetimepicker-widget .collapse { - display: none; -} - -.bootstrap-datetimepicker-widget .collapse.in { - display: block; -} - -/* fix for bootstrap4 */ -.bootstrap-datetimepicker-widget .table-condensed > thead > tr > th, -.bootstrap-datetimepicker-widget .table-condensed > tbody > tr > td, -.bootstrap-datetimepicker-widget .table-condensed > tfoot > tr > td { - padding: 5px; -} diff --git a/static/bootstrap_datepicker_plus/js/datepicker-widget.js b/static/bootstrap_datepicker_plus/js/datepicker-widget.js deleted file mode 100644 index 2288b46..0000000 --- a/static/bootstrap_datepicker_plus/js/datepicker-widget.js +++ /dev/null @@ -1,55 +0,0 @@ -jQuery(function ($) { - var datepickerDict = {}; - var isBootstrap4 = $.fn.collapse.Constructor.VERSION.split('.').shift() == "4"; - function fixMonthEndDate(e, picker) { - e.date && picker.val().length && picker.val(e.date.endOf('month').format('YYYY-MM-DD')); - } - $("[dp_config]:not([disabled])").each(function (i, element) { - var $element = $(element), data = {}; - try { - data = JSON.parse($element.attr('dp_config')); - } - catch (x) { } - if (data.id && data.options) { - data.$element = $element.datetimepicker(data.options); - data.datepickerdata = $element.data("DateTimePicker"); - datepickerDict[data.id] = data; - data.$element.next('.input-group-addon').on('click', function(){ - data.datepickerdata.show(); - }); - if(isBootstrap4){ - data.$element.on("dp.show", function (e) { - $('.collapse.in').addClass('show'); - }); - } - } - }); - $.each(datepickerDict, function (id, to_picker) { - if (to_picker.linked_to) { - var from_picker = datepickerDict[to_picker.linked_to]; - from_picker.datepickerdata.maxDate(to_picker.datepickerdata.date() || false); - to_picker.datepickerdata.minDate(from_picker.datepickerdata.date() || false); - from_picker.$element.on("dp.change", function (e) { - to_picker.datepickerdata.minDate(e.date || false); - }); - to_picker.$element.on("dp.change", function (e) { - if (to_picker.picker_type == 'MONTH') fixMonthEndDate(e, to_picker.$element); - from_picker.datepickerdata.maxDate(e.date || false); - }); - if (to_picker.picker_type == 'MONTH') { - to_picker.$element.on("dp.hide", function (e) { - fixMonthEndDate(e, to_picker.$element); - }); - fixMonthEndDate({ date: to_picker.datepickerdata.date() }, to_picker.$element); - } - } - }); - if(isBootstrap4) { - $('body').on('show.bs.collapse','.bootstrap-datetimepicker-widget .collapse',function(e){ - $(e.target).addClass('in'); - }); - $('body').on('hidden.bs.collapse','.bootstrap-datetimepicker-widget .collapse',function(e){ - $(e.target).removeClass('in'); - }); - } -}); diff --git a/static/favicon.ico b/static/favicon.ico deleted file mode 100644 index 97757d3..0000000 Binary files a/static/favicon.ico and /dev/null differ diff --git a/static/logo.svg b/static/logo.svg deleted file mode 100644 index 699316b..0000000 --- a/static/logo.svg +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - diff --git a/static/logo_animath.png b/static/logo_animath.png deleted file mode 100644 index da4533e..0000000 Binary files a/static/logo_animath.png and /dev/null differ diff --git a/static/style.css b/static/style.css deleted file mode 100644 index 5c8d3ff..0000000 --- a/static/style.css +++ /dev/null @@ -1,47 +0,0 @@ -html, body { - height: 100%; - margin: 0; -} - -:root { - --navbar-height: 32px; -} - -.container { - min-height: 78%; -} - -.inner { - margin: 20px; -} - -.alert { - text-align: justify; -} - - -footer .alert { - text-align: center; -} - -#navbar-logo { - height: var(--navbar-height); - display: block; -} - -ul .deroule { - display: none; - position: absolute; - background: #f8f9fa !important; - list-style-type: none; - padding: 20px; - z-index: 42; -} - -li:hover ul.deroule { - display:block; -} - -a.nav-link:hover { - background-color: #d8d9da; -} diff --git a/templates/base.html b/templates/base.html deleted file mode 100644 index d52e7be..0000000 --- a/templates/base.html +++ /dev/null @@ -1,234 +0,0 @@ -{% load static i18n static getconfig %} - - - - - - - - {% block title %}{{ title }}{% endblock title %} - Inscription au TFJM² - - - - {# Favicon #} - - - {% if no_cache %} - - {% endif %} - - {# Bootstrap CSS #} - - - - - {# Custom CSS #} - - - {# JQuery, Bootstrap and Turbolinks JavaScript #} - - - - - - {# Si un formulaire requiert des données supplémentaires (notamment JS), les données sont chargées #} - {% if form.media %} - {{ form.media }} - {% endif %} - - - - {% block extracss %}{% endblock %} - - -
- -
- {% block contenttitle %}

{{ title }}

{% endblock %} -
- {% block content %} -

Default content...

- {% endblock content %} -
-
- -
-
-
-
-
- - 𝕋𝔽𝕁𝕄² — - Nous contacter — - - {% csrf_token %} - - -
-
-
- Ce site a été conçu pour Animath, avec amour et passion. Il est récent et il est possible que - certaines pages ne fonctionnent pas correctement. Si vous remarquez des bugs, merci de les signaler - à - l'adresse contact@tfjm.org.
- © {{ "TFJM_YEAR"|get_env }} Tournoi Français des Jeunes Mathématiciennes et Mathématiciens -
- -
-
-
- - - -{% block extrajavascript %} -{% endblock extrajavascript %} - - diff --git a/templates/bootstrap_datepicker_plus/date_picker.html b/templates/bootstrap_datepicker_plus/date_picker.html deleted file mode 100644 index 67a11df..0000000 --- a/templates/bootstrap_datepicker_plus/date_picker.html +++ /dev/null @@ -1,6 +0,0 @@ -
- {% include "bootstrap_datepicker_plus/input.html" %} -
-
-
-
diff --git a/templates/bootstrap_datepicker_plus/input.html b/templates/bootstrap_datepicker_plus/input.html deleted file mode 100644 index b2f8c40..0000000 --- a/templates/bootstrap_datepicker_plus/input.html +++ /dev/null @@ -1,4 +0,0 @@ - \ No newline at end of file diff --git a/templates/bootstrap_datepicker_plus/time_picker.html b/templates/bootstrap_datepicker_plus/time_picker.html deleted file mode 100644 index 2bd509a..0000000 --- a/templates/bootstrap_datepicker_plus/time_picker.html +++ /dev/null @@ -1,6 +0,0 @@ -
- {% include "bootstrap_datepicker_plus/input.html" %} -
-
-
-
diff --git a/templates/colorfield/color.html b/templates/colorfield/color.html deleted file mode 100755 index 2743359..0000000 --- a/templates/colorfield/color.html +++ /dev/null @@ -1,8 +0,0 @@ - diff --git a/templates/django_filters/rest_framework/crispy_form.html b/templates/django_filters/rest_framework/crispy_form.html deleted file mode 100644 index 171767c..0000000 --- a/templates/django_filters/rest_framework/crispy_form.html +++ /dev/null @@ -1,5 +0,0 @@ -{% load crispy_forms_tags %} -{% load i18n %} - -

{% trans "Field filters" %}

-{% crispy filter.form %} diff --git a/templates/django_filters/rest_framework/form.html b/templates/django_filters/rest_framework/form.html deleted file mode 100644 index b116e35..0000000 --- a/templates/django_filters/rest_framework/form.html +++ /dev/null @@ -1,6 +0,0 @@ -{% load i18n %} -

{% trans "Field filters" %}

-
- {{ filter.form.as_p }} - -
diff --git a/templates/django_filters/widgets/multiwidget.html b/templates/django_filters/widgets/multiwidget.html deleted file mode 100644 index 089ddb2..0000000 --- a/templates/django_filters/widgets/multiwidget.html +++ /dev/null @@ -1 +0,0 @@ -{% for widget in widget.subwidgets %}{% include widget.template_name %}{% if forloop.first %}-{% endif %}{% endfor %} diff --git a/templates/index.html b/templates/index.html deleted file mode 100644 index 9455dc1..0000000 --- a/templates/index.html +++ /dev/null @@ -1,9 +0,0 @@ -{% extends "base.html" %} - -{% load getconfig %} - -{% block content %} - {% autoescape off %} - {{ "index_page"|get_config|safe }} - {% endautoescape %} -{% endblock %} diff --git a/templates/mail_templates/add_organizer.html b/templates/mail_templates/add_organizer.html deleted file mode 100644 index 06cc500..0000000 --- a/templates/mail_templates/add_organizer.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - Organisateur du TFJM² - - -Bonjour {{ user }},
-
-Vous recevez ce message (envoyé automatiquement) car vous êtes organisateur d'un des tournois du TFJM2.

-Un compte organisateur vous a été créé par l'un des administrateurs. Avant de vous connecter, vous devez réinitialiser votre -mot de passe sur le lien suivant : https://inscription.tfjm.org{% url "password_reset" %}. -
-Une fois le mot de passe changé, vous pourrez vous connecter sur la plateforme.
-
-Merci beaucoup pour votre aide !
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/add_organizer.txt b/templates/mail_templates/add_organizer.txt deleted file mode 100644 index 2a4cde4..0000000 --- a/templates/mail_templates/add_organizer.txt +++ /dev/null @@ -1,12 +0,0 @@ -Bonjour {{ user }}, - -Vous recevez ce message (envoyé automatiquement) car vous êtes organisateur d'un des tournois du TFJM². - -Un compte organisateur vous a été créé par l'un des administrateurs. Avant de vous connecter, vous devez réinitialiser votre -mot de passe sur le lien suivant : https://inscription.tfjm.org{% url "password_reset" %}. - -Une fois le mot de passe changé, vous pourrez vous connecter sur la plateforme : https://inscription.tfjm.org{% url "login" %}. - -Merci beaucoup pour votre aide ! - -Le comité national d'organisation du TFJM² diff --git a/templates/mail_templates/add_organizer_for_tournament.html b/templates/mail_templates/add_organizer_for_tournament.html deleted file mode 100644 index ad9aa90..0000000 --- a/templates/mail_templates/add_organizer_for_tournament.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - Organisateur du tournoi de {TOURNAMENT_NAME} – TFJM² - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez d'être promu organisateur du tournoi {TOURNAMENT_NAME} du TFJM2 {YEAR}.
-Ce message vous a été envoyé automatiquement. En cas de problème, merci de répondre à ce message. -
-Avec toute notre bienveillance,
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/add_team.html b/templates/mail_templates/add_team.html deleted file mode 100644 index bb69db0..0000000 --- a/templates/mail_templates/add_team.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Nouvelle équipe TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de créer l'équipe « {TEAM_NAME} » ({TRIGRAM}) pour le TFJM2 de {TOURNAMENT_NAME} et nous vous en remercions.
-Afin de permettre aux autres membres de votre équipe de vous rejoindre, veuillez leur transmettre le code d'accès : -{ACCESS_CODE}
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/change_email_address.html b/templates/mail_templates/change_email_address.html deleted file mode 100644 index d04ed90..0000000 --- a/templates/mail_templates/change_email_address.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - Changement d'adresse e-mail – TFJM² - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de changer votre adresse e-mail. Veuillez désormais la confirmer en cliquant ici : {URL_BASE}/confirmer_mail/{TOKEN}
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/change_password.html b/templates/mail_templates/change_password.html deleted file mode 100644 index 673e80f..0000000 --- a/templates/mail_templates/change_password.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - Mot de passe changé – TFJM² - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Nous vous informons que votre mot de passe vient d'être modifié. Si vous n'êtes pas à l'origine de cette manipulation, -veuillez immédiatement vérifier vos accès à votre boîte mail et changer votre mot de passe sur la plateforme -d'inscription.
-
-Avec toute notre bienveillance,
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/confirm_email.html b/templates/mail_templates/confirm_email.html deleted file mode 100644 index d247377..0000000 --- a/templates/mail_templates/confirm_email.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - Inscription au TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous êtes inscrit au TFJM2 {YEAR} et nous vous en remercions.
-Pour valider votre adresse e-mail, veuillez cliquer sur le lien : {URL_BASE}/confirmer_mail/{TOKEN}
-
-Avec toute notre bienveillance,
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/forgotten_password.html b/templates/mail_templates/forgotten_password.html deleted file mode 100644 index 717cc8c..0000000 --- a/templates/mail_templates/forgotten_password.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - Mot de passe oublié – TFJM² - - -Bonjour,
-
-Vous avez indiqué avoir oublié votre mot de passe. Veuillez cliquer ici pour le réinitialiser : {URL_BASE}/connexion/reinitialiser_mdp/{TOKEN}
-
-Si vous n'êtes pas à l'origine de cette manipulation, vous pouvez ignorer ce message.
-
-Avec toute notre bienveillance,
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/join_team.html b/templates/mail_templates/join_team.html deleted file mode 100644 index d5628c0..0000000 --- a/templates/mail_templates/join_team.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - Équipe rejointe – TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de rejoindre l'équipe « {TEAM_NAME} » ({TRIGRAM}) pour le TFJM² de {TOURNAMENT_NAME} et nous vous en -remercions.
-
-Avec toute notre bienveillance,
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/register.html b/templates/mail_templates/register.html deleted file mode 100644 index bc4123b..0000000 --- a/templates/mail_templates/register.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - Inscription au TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Vous venez de vous inscrire au TFJM2 {YEAR} et nous vous en remercions.
-Pour valider votre adresse e-mail, veuillez cliquer sur le lien : {URL_BASE}/confirmer_mail/{TOKEN}
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/request_payment_validation.html b/templates/mail_templates/request_payment_validation.html deleted file mode 100644 index 913e490..0000000 --- a/templates/mail_templates/request_payment_validation.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - Demande de validation de paiement pour le TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-{USER_FIRST_NAME} {USER_SURNAME} de l'équipe {TEAM_NAME} ({TRIGRAM}) annonce avoir réglé sa participation pour le tournoi {TOURNAMENT_NAME}. -Les informations suivantes ont été communiquées :

-Équipe : {TEAM_NAME} ({TRIGRAM})
-Tournoi : {TOURNAMENT_NAME}
-Moyen de paiement : {PAYMENT_METHOD}
-Montant : {AMOUNT} €
-Informations sur le paiement : {PAYMENT_INFOS}
-
-Vous pouvez désormais vérifier ces informations, puis valider (ou non) le paiement sur -la page associée à ce participant. -
-Avec toute notre bienveillance, -
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/request_validation.html b/templates/mail_templates/request_validation.html deleted file mode 100644 index 7a05122..0000000 --- a/templates/mail_templates/request_validation.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - Demande de validation - TFJM² - - -Bonjour {{ user }},
-
-L'équipe « {{ team.name }} » ({{ team.trigram }}) vient de demander à valider son équipe pour participer au tournoi -{{ tournament }} du TFJM². Vous pouvez décider d'accepter ou de refuser l'équipe en vous rendant sur la page de l'équipe : -https://inscription.tfjm.org{% url "tournament:team_detail" pk=team.pk %}
-
-Avec toute notre bienveillance,
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/request_validation.txt b/templates/mail_templates/request_validation.txt deleted file mode 100644 index 88d463b..0000000 --- a/templates/mail_templates/request_validation.txt +++ /dev/null @@ -1,9 +0,0 @@ -Bonjour {{ user }}, - -L'équipe « {{ team.name }} » ({{ team.trigram }}) vient de demander à valider son équipe pour participer au tournoi -{{ tournament }} du TFJM². Vous pouvez décider d'accepter ou de refuser l'équipe en vous rendant sur la page de l'équipe : -https://inscription.tfjm.org{% url "tournament:team_detail" pk=team.pk %}. - -Avec toute notre bienveillance, - -Le comité national d'organisation du TFJM² diff --git a/templates/mail_templates/select_for_final.html b/templates/mail_templates/select_for_final.html deleted file mode 100644 index 383b527..0000000 --- a/templates/mail_templates/select_for_final.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - Sélection pour la finale - TFJM² - - -Bonjour {{ user }},
-
-Félicitations ! Votre équipe « {{ team.name }} » ({{ team.trigram }}) est sélectionnée pour la finale nationale !
-
-La finale aura lieu du {{ final.date_start }} au {{ final.date_end }}. Vous pouvez peaufiner vos solutions -si vous le souhaitez jusqu'au {{ final.date_solutions }}.
-
-Bravo encore !
-
-Avec toute notre bienveillance,
-
-Le comité national d'organisation du TFJM² - - \ No newline at end of file diff --git a/templates/mail_templates/select_for_final.txt b/templates/mail_templates/select_for_final.txt deleted file mode 100644 index a000c22..0000000 --- a/templates/mail_templates/select_for_final.txt +++ /dev/null @@ -1,12 +0,0 @@ -Bonjour {{ user }}, - -Félicitations ! Votre équipe « {{ team.name }} » ({{ team.trigram }}) est sélectionnée pour la finale nationale ! - -La finale aura lieu du {{ final.date_start }} au {{ final.date_end }}. Vous pouvez peaufiner vos solutions -si vous le souhaitez jusqu'au {{ final.date_solutions }}. - -Bravo encore ! - -Avec toute notre bienveillance, - -Le comité national d'organisation du TFJM² diff --git a/templates/mail_templates/unvalidate_payment.html b/templates/mail_templates/unvalidate_payment.html deleted file mode 100644 index 7273282..0000000 --- a/templates/mail_templates/unvalidate_payment.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - Non-validation du paiement pour le TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Votre paiement pour le TFJM² {YEAR} a malheureusement été rejeté. Pour rappel, vous aviez fourni ces informations :

-Équipe : {TEAM_NAME} ({TRIGRAM})
-Tournoi : {TOURNAMENT_NAME}
-Moyen de paiement : {PAYMENT_METHOD}
-Montant : {AMOUNT} €
-Informations sur le paiement : {PAYMENT_INFOS}
-
-{MESSAGE} -
-Avec toute notre bienveillance, -
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/unvalidate_team.txt b/templates/mail_templates/unvalidate_team.txt deleted file mode 100644 index 88c1440..0000000 --- a/templates/mail_templates/unvalidate_team.txt +++ /dev/null @@ -1,15 +0,0 @@ -Bonjour {{ user }}, - -Maleureusement, votre équipe « {{ team.name }} » ({{ team.trigram }}) n'a pas été validée. Veuillez vérifier que vos autorisations sont correctes. - -{% if message %} -Le CNO vous adresse le message suivant : - -{{ message }} -{% endif %} - -N'hésitez pas à nous contacter à l'adresse contact@tfjm.org pour plus d'informations. - -Avec toute notre bienveillance, - -Le comité national d'organisation du TFJM² diff --git a/templates/mail_templates/validate_payment.html b/templates/mail_templates/validate_payment.html deleted file mode 100644 index 2743f17..0000000 --- a/templates/mail_templates/validate_payment.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - Validation du paiement pour le TFJM² {YEAR} - - -Bonjour {FIRST_NAME} {SURNAME},
-
-Votre paiement pour le TFJM² {YEAR} a bien été validé. Pour rappel, vous aviez fourni ces informations :

-Équipe : {TEAM_NAME} ({TRIGRAM})
-Tournoi : {TOURNAMENT_NAME}
-Moyen de paiement : {PAYMENT_METHOD}
-Montant : {AMOUNT} €
-Informations sur le paiement : {PAYMENT_INFOS}
-
-{MESSAGE} -
-Avec toute notre bienveillance, -
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/validate_team.html b/templates/mail_templates/validate_team.html deleted file mode 100644 index ef23e85..0000000 --- a/templates/mail_templates/validate_team.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - Équipe validée – TFJM² {YEAR} - - -Bonjour {{ user }},
-
-Félicitations ! Votre équipe « {{ team }} » ({{ team.trigram }}) est désormais validée ! Vous êtes désormais apte à travailler sur -vos problèmes et publier vos solutions sur la plateforme. -{% if message %} -

- Le CNO vous adresse le message suivant : -

- {{ message }} -
-

-{% endif %} -
-Avec toute notre bienveillance,
-
-Le comité national d'organisation du TFJM2 - - diff --git a/templates/mail_templates/validate_team.txt b/templates/mail_templates/validate_team.txt deleted file mode 100644 index 8b4c95e..0000000 --- a/templates/mail_templates/validate_team.txt +++ /dev/null @@ -1,13 +0,0 @@ -Bonjour {{ user }}, - -Félicitations ! Votre équipe « {{ team }} » ({{ team.trigram }}) est désormais validée ! Vous êtes désormais apte à travailler sur -vos problèmes et publier vos solutions sur la plateforme. - -{% if message %} -Le CNO vous adresse le message suivant : -{{ message }} -{% endif %} - -Avec toute notre bienveillance, - -Le comité national d'organisation du TFJM² diff --git a/templates/member/my_account.html b/templates/member/my_account.html deleted file mode 100644 index 884bf2b..0000000 --- a/templates/member/my_account.html +++ /dev/null @@ -1,15 +0,0 @@ -{% extends "base.html" %} - -{% load i18n crispy_forms_filters %} - -{% block content %} -
- {% csrf_token %} - {{ form|crispy }} - -
- -
- - {% trans "Update my password" %} -{% endblock %} diff --git a/templates/member/profile_list.html b/templates/member/profile_list.html deleted file mode 100644 index 7a6f85f..0000000 --- a/templates/member/profile_list.html +++ /dev/null @@ -1,11 +0,0 @@ -{% extends "base.html" %} - -{% load django_tables2 i18n %} - -{% block content %} - {% render_table table %} - {% if type == "organizers" and user.admin %} -
- {% trans "Add an organizer" %} - {% endif %} -{% endblock %} diff --git a/templates/member/tfjmuser_detail.html b/templates/member/tfjmuser_detail.html deleted file mode 100644 index 26e63b4..0000000 --- a/templates/member/tfjmuser_detail.html +++ /dev/null @@ -1,87 +0,0 @@ -{% extends "base.html" %} - -{% load getconfig i18n django_tables2 static %} - -{% block content %} -
-
-

{{ tfjmuser }}

-
-
-
-
{% trans 'role'|capfirst %}
-
{{ tfjmuser.get_role_display }}
- - {% if tfjmuser.team %} -
{% trans 'team'|capfirst %}
-
{{ tfjmuser.team }}
- {% endif %} - - {% if tfjmuser.birth_date %} -
{% trans 'birth date'|capfirst %}
-
{{ tfjmuser.birth_date }}
- {% endif %} - - {% if tfjmuser.participates %} -
{% trans 'gender'|capfirst %}
-
{{ tfjmuser.get_gender_display }}
- {% endif %} - - {% if tfjmuser.address %} -
{% trans 'address'|capfirst %}
-
{{ tfjmuser.address }}, {{ tfjmuser.postal_code }}, {{ tfjmuser.city }}{% if tfjmuser.country != "France" %}, {{ tfjmuser.country }}{% endif %}
- {% endif %} - -
{% trans 'email'|capfirst %}
-
{{ tfjmuser.email }}
- - {% if tfjmuser.phone_number %} -
{% trans 'phone number'|capfirst %}
-
{{ tfjmuser.phone_number }}
- {% endif %} - - {% if tfjmuser.role == '3participant' %} -
{% trans 'school'|capfirst %}
-
{{ tfjmuser.school }}
- -
{% trans 'class'|capfirst %}
-
{{ tfjmuser.get_student_class_display }}
- - {% if tfjmuser.responsible_name %} -
{% trans 'responsible name'|capfirst %}
-
{{ tfjmuser.responsible_name }}
- {% endif %} - - {% if tfjmuser.responsible_phone %} -
{% trans 'responsible phone'|capfirst %}
-
{{ tfjmuser.responsible_phone }}
- {% endif %} - - {% if tfjmuser.responsible_email %} -
{% trans 'responsible email'|capfirst %}
-
{{ tfjmuser.responsible_email }}
- {% endif %} - {% endif %} - - {% if tfjmuser.role != '3participant' %} -
{% trans 'description'|capfirst %}
-
{{ tfjmuser.description|default_if_none:"" }}
- {% endif %} -
-
-
- -
- -

{% trans "Documents" %}

- - {# TODO Display documents #} - - {% if request.user.is_superuser %} -
-
- {% csrf_token %} - -
- {% endif %} -{% endblock %} diff --git a/templates/registration/email_validation_complete.html b/templates/registration/email_validation_complete.html deleted file mode 100644 index b54432f..0000000 --- a/templates/registration/email_validation_complete.html +++ /dev/null @@ -1,15 +0,0 @@ -{% extends "base.html" %} -{% load i18n %} - -{% block content %} - {% if validlink %} - {% trans "Your email have successfully been validated." %} - {% if user_object.profile.registration_valid %} - {% blocktrans %}You can now log in.{% endblocktrans %} - {% else %} - {% trans "You must pay now your membership in the Kfet to complete your registration." %} - {% endif %} - {% else %} - {% trans "The link was invalid. The token may have expired. Please send us an email to activate your account." %} - {% endif %} -{% endblock %} diff --git a/templates/registration/email_validation_email_sent.html b/templates/registration/email_validation_email_sent.html deleted file mode 100644 index bd4cf8d..0000000 --- a/templates/registration/email_validation_email_sent.html +++ /dev/null @@ -1,7 +0,0 @@ -{% extends "base.html" %} - -{% block content %} -

Account Activation

- -An email has been sent. Please click on the link to activate your account. -{% endblock %} \ No newline at end of file diff --git a/templates/registration/mails/email_validation_email.html b/templates/registration/mails/email_validation_email.html deleted file mode 100644 index 577c122..0000000 --- a/templates/registration/mails/email_validation_email.html +++ /dev/null @@ -1,15 +0,0 @@ -{% load i18n %} - -{% trans "Hi" %} {{ user.username }}, - -{% trans "You recently registered on the Note Kfet. Please click on the link below to confirm your registration." %} - -https://{{ domain }}{% url 'registration:email_validation' uidb64=uid token=token %} - -{% trans "This link is only valid for a couple of days, after that you will need to contact us to validate your email." %} - -{% trans "After that, you'll have to wait that someone validates your account before you can log in. You will need to pay your membership in the Kfet." %} - -{% trans "Thanks" %}, - -{% trans "The Note Kfet team." %} diff --git a/templates/registration/signup.html b/templates/registration/signup.html deleted file mode 100644 index ed100d0..0000000 --- a/templates/registration/signup.html +++ /dev/null @@ -1,17 +0,0 @@ - -{% extends 'base.html' %} -{% load crispy_forms_filters %} -{% load i18n %} -{% block title %}{% trans "Sign up" %}{% endblock %} - -{% block content %} -

{% trans "Sign up" %}

- -
- {% csrf_token %} - {{ form|crispy }} - -
-{% endblock %} diff --git a/templates/tournament/add_organizer.html b/templates/tournament/add_organizer.html deleted file mode 100644 index 21daee8..0000000 --- a/templates/tournament/add_organizer.html +++ /dev/null @@ -1,11 +0,0 @@ -{% extends "base.html" %} - -{% load i18n crispy_forms_filters %} - -{% block content %} -
- {% csrf_token %} - {{ form|crispy }} - -
-{% endblock %} diff --git a/templates/tournament/pool_detail.html b/templates/tournament/pool_detail.html deleted file mode 100644 index d20c2b8..0000000 --- a/templates/tournament/pool_detail.html +++ /dev/null @@ -1,94 +0,0 @@ -{% extends "base.html" %} - -{% load getconfig i18n django_tables2 static %} - -{% block content %} -
-
-

{{ title }}

-
-
-
-
{% trans 'juries'|capfirst %}
-
{{ pool.juries.all|join:", " }}
- -
{% trans 'teams'|capfirst %}
-
{{ pool.teams.all|join:", " }}
- -
{% trans 'round'|capfirst %}
-
{{ pool.round }}
- -
{% trans 'tournament'|capfirst %}
-
{{ pool.tournament }}
-
-
-
- -
- -
-
-

{% trans "Solutions" %}

-
-
- {% if pool.round == 2 %} -
- {% trans "Solutions will be available here for teams from:" %} {{ pool.tournament.date_solutions_2 }} -
- {% endif %} - -
    - {% for solution in pool.solutions.all %} -
  • {{ solution }}
  • - {% endfor %} -
-
- -
-
- -
-
-

{% trans "Syntheses" %}

-
-
-
- {% trans "Templates for syntheses are available here:" %} - PDFTEX -
- {% if user.organizes or not user.is_authenticated %} -
    - {% for synthesis in pool.syntheses.all %} -
  • {{ synthesis }}
  • - {% endfor %} -
- - {% endif %} -
-
- -
- - - - {% if user.organizes or not user.is_authenticated %} -
-
- {% trans "Give this link to juries to access this page (warning: should stay confidential and only given to juries of this pool):" %}
- - https://{{ request.get_host }}{% url "tournament:pool_detail" pk=pool.pk %}?extra_access_token={{ pool.extra_access_token }} -
- {% endif %} -{% endblock %} diff --git a/templates/tournament/pool_form.html b/templates/tournament/pool_form.html deleted file mode 100644 index 21daee8..0000000 --- a/templates/tournament/pool_form.html +++ /dev/null @@ -1,11 +0,0 @@ -{% extends "base.html" %} - -{% load i18n crispy_forms_filters %} - -{% block content %} -
- {% csrf_token %} - {{ form|crispy }} - -
-{% endblock %} diff --git a/templates/tournament/pool_list.html b/templates/tournament/pool_list.html deleted file mode 100644 index 9a15348..0000000 --- a/templates/tournament/pool_list.html +++ /dev/null @@ -1,12 +0,0 @@ -{% extends "base.html" %} - -{% load i18n django_tables2 %} - -{% block content %} - {% render_table table %} - - {% if user.admin %} -
- - {% endif %} -{% endblock %} diff --git a/templates/tournament/solutions_list.html b/templates/tournament/solutions_list.html deleted file mode 100644 index 6005d11..0000000 --- a/templates/tournament/solutions_list.html +++ /dev/null @@ -1,29 +0,0 @@ -{% extends "base.html" %} - -{% load i18n crispy_forms_filters django_tables2 %} - -{% block content %} - {% if form %} - {% if now < user.team.future_tournament.date_solutions %} -
- {% blocktrans with deadline=user.team.future_tournament.date_solutions %}You can upload your solutions until {{ deadline }}.{% endblocktrans %} -
- {% else %} -
- {% if now < real_deadline %} - {% trans "The deadline to send your solutions is reached. However, you have an extra time of 30 minutes to send your papers, no panic :)" %} - {% else %} - {% trans "You can't upload your solutions anymore." %} - {% endif %} -
- {% endif %} - -
- {% csrf_token %} - {{ form|crispy }} - -
-
- {% endif %} - {% render_table table %} -{% endblock %} diff --git a/templates/tournament/solutions_orga_list.html b/templates/tournament/solutions_orga_list.html deleted file mode 100644 index fe83b4f..0000000 --- a/templates/tournament/solutions_orga_list.html +++ /dev/null @@ -1,18 +0,0 @@ -{% extends "base.html" %} - -{% load i18n django_tables2 %} - -{% block content %} - {% render_table table %} - -
- -
- {% csrf_token %} -
- {% for tournament in tournaments.all %} - - {% endfor %} -
-
-{% endblock %} diff --git a/templates/tournament/syntheses_list.html b/templates/tournament/syntheses_list.html deleted file mode 100644 index b1cf355..0000000 --- a/templates/tournament/syntheses_list.html +++ /dev/null @@ -1,45 +0,0 @@ -{% extends "base.html" %} - -{% load i18n crispy_forms_filters django_tables2 static %} - -{% block content %} -
- {% trans "Templates for syntheses are available here:" %} - PDFTEX -
- - {% if form %} - {% if now < user.team.future_tournament.date_syntheses %} -
- {% blocktrans with deadline=user.team.future_tournament.date_syntheses round=1 %}You can upload your syntheses for round {{ round }} until {{ deadline }}.{% endblocktrans %} -
- {% elif now < real_deadline_1 %} -
- {% blocktrans with round=1 %}The deadline to send your syntheses for the round {{ round }} is reached. However, you have an extra time of 30 minutes to send your papers, no panic :){% endblocktrans %} -
- {% elif now < user.team.future_tournament.date_solutions_2 %} -
- {% blocktrans with round=1 %}You can't upload your syntheses for the round {{ round }} anymore.{% endblocktrans %} -
- {% elif now < user.team.future_tournament.date_syntheses_2 %} -
- {% blocktrans with deadline=user.team.future_tournament.date_syntheses_2 round=2 %}You can upload your syntheses for round {{ round }} until {{ deadline }}.{% endblocktrans %} -
- {% elif now < real_deadline_2 %} -
- {% blocktrans with round=2 %}The deadline to send your syntheses for the round {{ round }} is reached. However, you have an extra time of 30 minutes to send your papers, no panic :){% endblocktrans %} -
- {% else %} -
- {% blocktrans with round=2 %}You can't upload your syntheses for the round {{ round }} anymore.{% endblocktrans %} -
- {% endif %} -
- {% csrf_token %} - {{ form|crispy }} - -
-
- {% endif %} - {% render_table table %} -{% endblock %} diff --git a/templates/tournament/syntheses_orga_list.html b/templates/tournament/syntheses_orga_list.html deleted file mode 100644 index fe83b4f..0000000 --- a/templates/tournament/syntheses_orga_list.html +++ /dev/null @@ -1,18 +0,0 @@ -{% extends "base.html" %} - -{% load i18n django_tables2 %} - -{% block content %} - {% render_table table %} - -
- -
- {% csrf_token %} -
- {% for tournament in tournaments.all %} - - {% endfor %} -
-
-{% endblock %} diff --git a/templates/tournament/team_detail.html b/templates/tournament/team_detail.html deleted file mode 100644 index 21dbada..0000000 --- a/templates/tournament/team_detail.html +++ /dev/null @@ -1,156 +0,0 @@ -{% extends "base.html" %} - -{% load getconfig i18n django_tables2 static %} - -{% block content %} -
-
-

{% trans "Team" %} {{ team.name }}

-
-
-
-
{% trans 'name'|capfirst %}
-
{{ team.name }}
- -
{% trans 'trigram'|capfirst %}
-
{{ team.trigram }}
- -
{% trans 'access code'|capfirst %}
-
{{ team.access_code }}
- -
{% trans 'tournament'|capfirst %}
-
{{ team.tournament }}
- -
{% trans 'coachs'|capfirst %}
-
{% autoescape off %}{{ team.linked_coaches|join:", " }}{% endautoescape %}
- -
{% trans 'participants'|capfirst %}
-
- {% autoescape off %}{{ team.linked_participants|join:", " }}{% endautoescape %}
- -
{% trans 'validation status'|capfirst %}
-
{{ team.get_validation_status_display }}
-
-
- - {% if user.is_authenticated and user.admin %} - - {% endif %} - - {% if user.admin or user in team.tournament.organizers.all or team == user.team %} - - {% endif %} -
- - {% if user.participates and team.invalid %} -
- {% if team.can_validate %} -
- {% csrf_token %} - - -
- Attention ! Une fois votre équipe validée, vous ne pourrez plus modifier le nom - de l'équipe, le trigramme ou la composition de l'équipe. -
- -
- {% else %} -
- Pour demander à valider votre équipe, vous devez avoir au moins un encadrant, quatre participants - et soumis une autorisation de droit à l'image, une fiche sanitaire et une autorisation - parentale (si besoin) par participant, ainsi qu'une lettre de motivation à transmettre aux - organisateurs. - Les encadrants doivent également fournir une autorisation de droit à l'image. -
- {% endif %} -
-
- En raison du changement de format du TFJM² 2020, il n'y a plus de document obligatoire à envoyer. Les - autorisations - précédemment envoyées ont été détruites. Seules les lettres de motivation ont été conservées, mais leur - envoi - n'est plus obligatoire. -
- {% endif %} - - {% if team.waiting %} -
-
- {% trans "The team is waiting about validation." %} -
- - {% if user.admin %} -
- {% csrf_token %} -
- - -
- -
-
- - -
-
-
- {% endif %} - {% endif %} - -
- -

{% trans "Documents" %}

- - {% if team.motivation_letters.count %} -
- {% blocktrans %}Motivation letter:{% endblocktrans %} - {% trans "Download" %} -
- {% endif %} - - {% if team.solutions.count %} -
- -
-
-
- {% csrf_token %} - -
-
- {% endif %} -{% endblock %} diff --git a/templates/tournament/team_form.html b/templates/tournament/team_form.html deleted file mode 100644 index 21daee8..0000000 --- a/templates/tournament/team_form.html +++ /dev/null @@ -1,11 +0,0 @@ -{% extends "base.html" %} - -{% load i18n crispy_forms_filters %} - -{% block content %} -
- {% csrf_token %} - {{ form|crispy }} - -
-{% endblock %} diff --git a/templates/tournament/tournament_detail.html b/templates/tournament/tournament_detail.html deleted file mode 100644 index 2c3b617..0000000 --- a/templates/tournament/tournament_detail.html +++ /dev/null @@ -1,67 +0,0 @@ -{% extends "base.html" %} - -{% load getconfig i18n django_tables2 %} - -{% block content %} -
-
-

{{ title }}

-
-
-
-
{% trans 'organizers'|capfirst %}
-
{% autoescape off %}{{ tournament.linked_organizers|join:", " }}{% endautoescape %}
- -
{% trans 'size'|capfirst %}
-
{{ tournament.size }}
- -
{% trans 'place'|capfirst %}
-
{{ tournament.place }}
- -
{% trans 'price'|capfirst %}
-
{% if tournament.price %}{{ tournament.price }} €{% else %}{% trans "Free" %}{% endif %}
- -
{% trans 'dates'|capfirst %}
-
{% trans "From" %} {{ tournament.date_start }} {% trans "to" %} {{ tournament.date_end }}
- -
{% trans 'date of registration closing'|capfirst %}
-
{{ tournament.date_inscription }}
- -
{% trans 'date of maximal solution submission'|capfirst %}
-
{{ tournament.date_solutions }}
- -
{% trans 'date of maximal syntheses submission for the first round'|capfirst %}
-
{{ tournament.date_syntheses }}
- -
{% trans 'date when solutions of round 2 are available'|capfirst %}
-
{{ tournament.date_solutions_2 }}
- -
{% trans 'date of maximal syntheses submission for the second round'|capfirst %}
-
{{ tournament.date_syntheses_2 }}
- -
{% trans 'description'|capfirst %}
-
{{ tournament.description }}
-
- - {% if user.is_authenticated and user.admin %} - - {% endif %} -
- - {% if user.admin or user in tournament.organizers.all %} - - {% endif %} -
- -
- -

{% trans "Teams" %}

-
- {% render_table teams %} -
-{% endblock %} diff --git a/templates/tournament/tournament_form.html b/templates/tournament/tournament_form.html deleted file mode 100644 index 21daee8..0000000 --- a/templates/tournament/tournament_form.html +++ /dev/null @@ -1,11 +0,0 @@ -{% extends "base.html" %} - -{% load i18n crispy_forms_filters %} - -{% block content %} -
- {% csrf_token %} - {{ form|crispy }} - -
-{% endblock %} diff --git a/templates/tournament/tournament_list.html b/templates/tournament/tournament_list.html deleted file mode 100644 index 6a3479a..0000000 --- a/templates/tournament/tournament_list.html +++ /dev/null @@ -1,17 +0,0 @@ -{% extends "base.html" %} - -{% load django_tables2 getconfig i18n %} - -{% block content %} - {% if user.is_authenticated and user.admin %} - - {% endif %} - {% render_table table %} - {% if user.is_authenticated and user.admin %} -
- {% trans "Add a tournament" %} - {% endif %} -{% endblock %} diff --git a/tfjm.cron b/tfjm.cron new file mode 100644 index 0000000..b6ca7d2 --- /dev/null +++ b/tfjm.cron @@ -0,0 +1,20 @@ +# min hour day month weekday command +# Send pending mails +* * * * * cd /code && python manage.py send_mail -c 1 +* * * * * cd /code && python manage.py retry_deferred -c 1 +0 0 * * * cd /code && python manage.py purge_mail_log 7 -c 1 + +# Rebuild search index +0 * * * * cd /code && python manage.py update_index -v 0 + +# Recreate sympa lists +*/6 * * * * cd /code && python manage.py fix_sympa_lists &> /dev/null + +# Update matrix channels +*/6 * * * * cd /code && python manage.py fix_matrix_channels &> /dev/null + +# Check payments from Hello Asso +*/6 * * * * cd /code && python manage.py check_hello_asso &> /dev/null + +# Clean temporary files +30 * * * * rm -rf /tmp/* diff --git a/tfjm/__init__.py b/tfjm/__init__.py index e69de29..dfc9706 100644 --- a/tfjm/__init__.py +++ b/tfjm/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later diff --git a/tfjm/asgi.py b/tfjm/asgi.py index a75729d..68b875c 100644 --- a/tfjm/asgi.py +++ b/tfjm/asgi.py @@ -1,3 +1,6 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + """ ASGI config for tfjm project. diff --git a/tfjm/inputs.py b/tfjm/inputs.py deleted file mode 100644 index 67838fc..0000000 --- a/tfjm/inputs.py +++ /dev/null @@ -1,322 +0,0 @@ -from json import dumps as json_dumps - -from django.forms.widgets import DateTimeBaseInput, NumberInput, TextInput, Widget - - -class AmountInput(NumberInput): - """ - This input type lets the user type amounts in euros, but forms receive data in cents - """ - template_name = "amount_input.html" - - def format_value(self, value): - return None if value is None or value == "" else "{:.02f}".format(int(value) / 100, ) - - def value_from_datadict(self, data, files, name): - val = super().value_from_datadict(data, files, name) - return str(int(100 * float(val))) if val else val - - -class Autocomplete(TextInput): - template_name = "autocomplete_model.html" - - def __init__(self, model, attrs=None): - super().__init__(attrs) - - self.model = model - self.model_pk = None - - class Media: - """JS/CSS resources needed to render the date-picker calendar.""" - - js = ('js/autocomplete_model.js', ) - - def format_value(self, value): - if value: - self.attrs["model_pk"] = int(value) - return str(self.model.objects.get(pk=int(value))) - return "" - - -class ColorWidget(Widget): - """ - Pulled from django-colorfield. - Select a color. - """ - template_name = 'colorfield/color.html' - - class Media: - js = [ - 'colorfield/jscolor/jscolor.min.js', - 'colorfield/colorfield.js', - ] - - def format_value(self, value): - if value is None: - value = 0xFFFFFF - return "#{:06X}".format(value) - - def value_from_datadict(self, data, files, name): - val = super().value_from_datadict(data, files, name) - return int(val[1:], 16) - - -""" -The remaining of this file comes from the project `django-bootstrap-datepicker-plus` available on Github: -https://github.com/monim67/django-bootstrap-datepicker-plus -This is distributed under Apache License 2.0. - -This adds datetime pickers with bootstrap. -""" - -"""Contains Base Date-Picker input class for widgets of this package.""" - - -class DatePickerDictionary: - """Keeps track of all date-picker input classes.""" - - _i = 0 - items = dict() - - @classmethod - def generate_id(cls): - """Return a unique ID for each date-picker input class.""" - cls._i += 1 - return 'dp_%s' % cls._i - - -class BasePickerInput(DateTimeBaseInput): - """Base Date-Picker input class for widgets of this package.""" - - template_name = 'bootstrap_datepicker_plus/date_picker.html' - picker_type = 'DATE' - format = '%Y-%m-%d' - config = {} - _default_config = { - 'id': None, - 'picker_type': None, - 'linked_to': None, - 'options': {} # final merged options - } - options = {} # options extended by user - options_param = {} # options passed as parameter - _default_options = { - 'showClose': True, - 'showClear': True, - 'showTodayButton': True, - "locale": "fr", - } - - # source: https://github.com/tutorcruncher/django-bootstrap3-datetimepicker - # file: /blob/31fbb09/bootstrap3_datetime/widgets.py#L33 - format_map = ( - ('DDD', r'%j'), - ('DD', r'%d'), - ('MMMM', r'%B'), - ('MMM', r'%b'), - ('MM', r'%m'), - ('YYYY', r'%Y'), - ('YY', r'%y'), - ('HH', r'%H'), - ('hh', r'%I'), - ('mm', r'%M'), - ('ss', r'%S'), - ('a', r'%p'), - ('ZZ', r'%z'), - ) - - class Media: - """JS/CSS resources needed to render the date-picker calendar.""" - - js = ( - 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/' - 'moment-with-locales.min.js', - 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/' - '4.17.47/js/bootstrap-datetimepicker.min.js', - 'bootstrap_datepicker_plus/js/datepicker-widget.js' - ) - css = {'all': ( - 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/' - '4.17.47/css/bootstrap-datetimepicker.css', - 'bootstrap_datepicker_plus/css/datepicker-widget.css' - ), } - - @classmethod - def format_py2js(cls, datetime_format): - """Convert python datetime format to moment datetime format.""" - for js_format, py_format in cls.format_map: - datetime_format = datetime_format.replace(py_format, js_format) - return datetime_format - - @classmethod - def format_js2py(cls, datetime_format): - """Convert moment datetime format to python datetime format.""" - for js_format, py_format in cls.format_map: - datetime_format = datetime_format.replace(js_format, py_format) - return datetime_format - - def __init__(self, attrs=None, format=None, options=None): - """Initialize the Date-picker widget.""" - self.format_param = format - self.options_param = options if options else {} - self.config = self._default_config.copy() - self.config['id'] = DatePickerDictionary.generate_id() - self.config['picker_type'] = self.picker_type - self.config['options'] = self._calculate_options() - attrs = attrs if attrs else {} - if 'class' not in attrs: - attrs['class'] = 'form-control' - super().__init__(attrs, self._calculate_format()) - - def _calculate_options(self): - """Calculate and Return the options.""" - _options = self._default_options.copy() - _options.update(self.options) - if self.options_param: - _options.update(self.options_param) - return _options - - def _calculate_format(self): - """Calculate and Return the datetime format.""" - _format = self.format_param if self.format_param else self.format - if self.config['options'].get('format'): - _format = self.format_js2py(self.config['options'].get('format')) - else: - self.config['options']['format'] = self.format_py2js(_format) - return _format - - def get_context(self, name, value, attrs): - """Return widget context dictionary.""" - context = super().get_context( - name, value, attrs) - context['widget']['attrs']['dp_config'] = json_dumps(self.config) - return context - - def start_of(self, event_id): - """ - Set Date-Picker as the start-date of a date-range. - - Args: - - event_id (string): User-defined unique id for linking two fields - """ - DatePickerDictionary.items[str(event_id)] = self - return self - - def end_of(self, event_id, import_options=True): - """ - Set Date-Picker as the end-date of a date-range. - - Args: - - event_id (string): User-defined unique id for linking two fields - - import_options (bool): inherit options from start-date input, - default: TRUE - """ - event_id = str(event_id) - if event_id in DatePickerDictionary.items: - linked_picker = DatePickerDictionary.items[event_id] - self.config['linked_to'] = linked_picker.config['id'] - if import_options: - backup_moment_format = self.config['options']['format'] - self.config['options'].update(linked_picker.config['options']) - self.config['options'].update(self.options_param) - if self.format_param or 'format' in self.options_param: - self.config['options']['format'] = backup_moment_format - else: - self.format = linked_picker.format - # Setting useCurrent is necessary, see following issue - # https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1075 - self.config['options']['useCurrent'] = False - self._link_to(linked_picker) - else: - raise KeyError( - 'start-date not specified for event_id "%s"' % event_id) - return self - - def _link_to(self, linked_picker): - """ - Executed when two date-inputs are linked together. - - This method for sub-classes to override to customize the linking. - """ - pass - - -class DatePickerInput(BasePickerInput): - """ - Widget to display a Date-Picker Calendar on a DateField property. - - Args: - - attrs (dict): HTML attributes of rendered HTML input - - format (string): Python DateTime format eg. "%Y-%m-%d" - - options (dict): Options to customize the widget, see README - """ - - picker_type = 'DATE' - format = '%Y-%m-%d' - format_key = 'DATE_INPUT_FORMATS' - - -class TimePickerInput(BasePickerInput): - """ - Widget to display a Time-Picker Calendar on a TimeField property. - - Args: - - attrs (dict): HTML attributes of rendered HTML input - - format (string): Python DateTime format eg. "%Y-%m-%d" - - options (dict): Options to customize the widget, see README - """ - - picker_type = 'TIME' - format = '%H:%M' - format_key = 'TIME_INPUT_FORMATS' - template_name = 'bootstrap_datepicker_plus/time_picker.html' - - -class DateTimePickerInput(BasePickerInput): - """ - Widget to display a DateTime-Picker Calendar on a DateTimeField property. - - Args: - - attrs (dict): HTML attributes of rendered HTML input - - format (string): Python DateTime format eg. "%Y-%m-%d" - - options (dict): Options to customize the widget, see README - """ - - picker_type = 'DATETIME' - format = '%Y-%m-%d %H:%M' - format_key = 'DATETIME_INPUT_FORMATS' - - -class MonthPickerInput(BasePickerInput): - """ - Widget to display a Month-Picker Calendar on a DateField property. - - Args: - - attrs (dict): HTML attributes of rendered HTML input - - format (string): Python DateTime format eg. "%Y-%m-%d" - - options (dict): Options to customize the widget, see README - """ - - picker_type = 'MONTH' - format = '01/%m/%Y' - format_key = 'DATE_INPUT_FORMATS' - - -class YearPickerInput(BasePickerInput): - """ - Widget to display a Year-Picker Calendar on a DateField property. - - Args: - - attrs (dict): HTML attributes of rendered HTML input - - format (string): Python DateTime format eg. "%Y-%m-%d" - - options (dict): Options to customize the widget, see README - """ - - picker_type = 'YEAR' - format = '01/01/%Y' - format_key = 'DATE_INPUT_FORMATS' - - def _link_to(self, linked_picker): - """Customize the options when linked with other date-time input""" - yformat = self.config['options']['format'].replace('-01-01', '-12-31') - self.config['options']['format'] = yformat diff --git a/tfjm/lists.py b/tfjm/lists.py new file mode 100644 index 0000000..667d372 --- /dev/null +++ b/tfjm/lists.py @@ -0,0 +1,26 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +import os + +_client = None + + +def get_sympa_client(): + global _client + if _client is None: + if os.getenv("SYMPA_PASSWORD", None) is not None: # pragma: no cover + from sympasoap import Client + _client = Client("https://" + os.getenv("SYMPA_URL")) + _client.login(os.getenv("SYMPA_EMAIL"), os.getenv("SYMPA_PASSWORD")) + else: + _client = FakeSympaSoapClient() + return _client + + +class FakeSympaSoapClient: + """ + Simulate a Sympa Soap client to run tests, if no Sympa instance is connected. + """ + def __getattribute__(self, item): + return lambda *args, **kwargs: None diff --git a/tfjm/matrix.py b/tfjm/matrix.py new file mode 100644 index 0000000..1a65311 --- /dev/null +++ b/tfjm/matrix.py @@ -0,0 +1,433 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from enum import Enum +import os + +from asgiref.sync import async_to_sync + + +class Matrix: + """ + Utility class to manage interaction with the Matrix homeserver. + This log in the @tfjmbot account (must be created before). + The access token is then stored. + All is done with this bot account, that is a server administrator. + Tasks are normally asynchronous, but for compatibility we make + them synchronous. + """ + _token = None + _device_id = None + + @classmethod + async def _get_client(cls): # pragma: no cover + """ + Retrieve the bot account. + If not logged, log in and store access token. + """ + if not os.getenv("SYNAPSE_PASSWORD"): + return FakeMatrixClient() + + from nio import AsyncClient + client = AsyncClient("https://tfjm.org", "@tfjmbot:tfjm.org") + client.user_id = "@tfjmbot:tfjm.org" + + if os.path.isfile(".matrix_token"): + with open(".matrix_device", "r") as f: + cls._device_id = f.read().rstrip(" \t\r\n") + client.device_id = cls._device_id + with open(".matrix_token", "r") as f: + cls._token = f.read().rstrip(" \t\r\n") + client.access_token = cls._token + return client + + await client.login(password=os.getenv("SYNAPSE_PASSWORD"), device_name="Plateforme") + cls._token = client.access_token + cls._device_id = client.device_id + with open(".matrix_token", "w") as f: + f.write(cls._token) + with open(".matrix_device", "w") as f: + f.write(cls._device_id) + return client + + @classmethod + @async_to_sync + async def set_display_name(cls, name: str): + """ + Set the display name of the bot account. + """ + client = await cls._get_client() + return await client.set_displayname(name) + + @classmethod + @async_to_sync + async def set_avatar(cls, avatar_url: str): # pragma: no cover + """ + Set the display avatar of the bot account. + """ + client = await cls._get_client() + return await client.set_avatar(avatar_url) + + @classmethod + @async_to_sync + async def upload( + cls, + data_provider, + content_type: str = "application/octet-stream", + filename: str = None, + encrypt: bool = False, + monitor=None, + filesize: int = None, + ): # pragma: no cover + """ + Upload a file to the content repository. + + Returns a tuple containing: + + - Either a `UploadResponse` if the request was successful, or a + `UploadError` if there was an error with the request + + - A dict with file decryption info if encrypt is ``True``, + else ``None``. + Args: + data_provider (Callable, SynchronousFile, AsyncFile): A function + returning the data to upload or a file object. File objects + must be opened in binary mode (``mode="r+b"``). Callables + returning a path string, Path, async iterable or aiofiles + open binary file object allow the file data to be read in an + asynchronous and lazy way (without reading the entire file + into memory). Returning a synchronous iterable or standard + open binary file object will still allow the data to be read + lazily, but not asynchronously. + + The function will be called again if the upload fails + due to a server timeout, in which case it must restart + from the beginning. + Callables receive two arguments: the total number of + 429 "Too many request" errors that occured, and the total + number of server timeout exceptions that occured, thus + cleanup operations can be performed for retries if necessary. + + content_type (str): The content MIME type of the file, + e.g. "image/png". + Defaults to "application/octet-stream", corresponding to a + generic binary file. + Custom values are ignored if encrypt is ``True``. + + filename (str, optional): The file's original name. + + encrypt (bool): If the file's content should be encrypted, + necessary for files that will be sent to encrypted rooms. + Defaults to ``False``. + + monitor (TransferMonitor, optional): If a ``TransferMonitor`` + object is passed, it will be updated by this function while + uploading. + From this object, statistics such as currently + transferred bytes or estimated remaining time can be gathered + while the upload is running as a task; it also allows + for pausing and cancelling. + + filesize (int, optional): Size in bytes for the file to transfer. + If left as ``None``, some servers might refuse the upload. + """ + client = await cls._get_client() + return await client.upload(data_provider, content_type, filename, encrypt, monitor, filesize) \ + if not isinstance(client, FakeMatrixClient) else None, None + + @classmethod + @async_to_sync + async def create_room( + cls, + visibility=None, + alias=None, + name=None, + topic=None, + room_version=None, + federate=True, + is_direct=False, + preset=None, + invite=(), + initial_state=(), + power_level_override=None, + ): + """ + Create a new room. + + Returns either a `RoomCreateResponse` if the request was successful or + a `RoomCreateError` if there was an error with the request. + + Args: + visibility (RoomVisibility): whether to have the room published in + the server's room directory or not. + Defaults to ``RoomVisibility.private``. + + alias (str, optional): The desired canonical alias local part. + For example, if set to "foo" and the room is created on the + "example.com" server, the room alias will be + "#foo:example.com". + + name (str, optional): A name to set for the room. + + topic (str, optional): A topic to set for the room. + + room_version (str, optional): The room version to set. + If not specified, the homeserver will use its default setting. + If a version not supported by the homeserver is specified, + a 400 ``M_UNSUPPORTED_ROOM_VERSION`` error will be returned. + + federate (bool): Whether to allow users from other homeservers from + joining the room. Defaults to ``True``. + Cannot be changed later. + + is_direct (bool): If this should be considered a + direct messaging room. + If ``True``, the server will set the ``is_direct`` flag on + ``m.room.member events`` sent to the users in ``invite``. + Defaults to ``False``. + + preset (RoomPreset, optional): The selected preset will set various + rules for the room. + If unspecified, the server will choose a preset from the + ``visibility``: ``RoomVisibility.public`` equates to + ``RoomPreset.public_chat``, and + ``RoomVisibility.private`` equates to a + ``RoomPreset.private_chat``. + + invite (list): A list of user id to invite to the room. + + initial_state (list): A list of state event dicts to send when + the room is created. + For example, a room could be made encrypted immediatly by + having a ``m.room.encryption`` event dict. + + power_level_override (dict): A ``m.room.power_levels content`` dict + to override the default. + The dict will be applied on top of the generated + ``m.room.power_levels`` event before it is sent to the room. + """ + client = await cls._get_client() + return await client.room_create( + visibility, alias, name, topic, room_version, federate, is_direct, preset, invite, initial_state, + power_level_override) + + @classmethod + async def resolve_room_alias(cls, room_alias: str): + """ + Resolve a room alias to a room ID. + Return None if the alias does not exist. + """ + client = await cls._get_client() + resp = await client.room_resolve_alias(room_alias) + return resp.room_id if resp and hasattr(resp, "room_id") else None + + @classmethod + @async_to_sync + async def invite(cls, room_id: str, user_id: str): + """ + Invite a user to a room. + + Returns either a `RoomInviteResponse` if the request was successful or + a `RoomInviteError` if there was an error with the request. + + Args: + room_id (str): The room id of the room that the user will be + invited to. + user_id (str): The user id of the user that should be invited. + """ + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + return await client.room_invite(room_id, user_id) + + @classmethod + @async_to_sync + async def send_message(cls, room_id: str, body: str, formatted_body: str = None, + msgtype: str = "m.text", html: bool = True): + """ + Send a message to a room. + """ + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + content = { + "msgtype": msgtype, + "body": body, + "formatted_body": formatted_body or body, + } + if html: + content["format"] = "org.matrix.custom.html" + return await client.room_send( + room_id=room_id, + message_type="m.room.message", + content=content, + ) + + @classmethod + @async_to_sync + async def add_integration(cls, room_id: str, widget_url: str, state_key: str, + widget_type: str = "customwidget", widget_name: str = "Custom widget", + widget_title: str = ""): + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + content = { + "type": widget_type, + "url": widget_url, + "name": widget_name, + "data": { + "curl": widget_url, + "title": widget_title, + }, + "creatorUserId": client.user, + "roomId": room_id, + "id": state_key, + } + return await client.room_put_state( + room_id=room_id, + event_type="im.vector.modular.widgets", + content=content, + state_key=state_key, + ) + + @classmethod + @async_to_sync + async def remove_integration(cls, room_id: str, state_key: str): + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + return await client.room_put_state( + room_id=room_id, + event_type="im.vector.modular.widgets", + content={}, + state_key=state_key, + ) + + @classmethod + @async_to_sync + async def kick(cls, room_id: str, user_id: str, reason: str = None): + """ + Kick a user from a room, or withdraw their invitation. + + Kicking a user adjusts their membership to "leave" with an optional + reason. +² + Returns either a `RoomKickResponse` if the request was successful or + a `RoomKickError` if there was an error with the request. + + Args: + room_id (str): The room id of the room that the user will be + kicked from. + user_id (str): The user_id of the user that should be kicked. + reason (str, optional): A reason for which the user is kicked. + """ + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + return await client.room_kick(room_id, user_id, reason) + + @classmethod + @async_to_sync + async def set_room_power_level(cls, room_id: str, user_id: str, power_level: int): # pragma: no cover + """ + Put a given power level to a user in a certain room. + + Returns either a `RoomPutStateResponse` if the request was successful or + a `RoomPutStateError` if there was an error with the request. + + Args: + room_id (str): The room id of the room where the power level + of the user should be updated. + user_id (str): The user_id of the user which power level should + be updated. + power_level (int): The target power level to give. + """ + client = await cls._get_client() + if isinstance(client, FakeMatrixClient): + return None + + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + resp = await client.room_get_state_event(room_id, "m.room.power_levels") + content = resp.content + content["users"][user_id] = power_level + return await client.room_put_state(room_id, "m.room.power_levels", content=content, state_key=resp.state_key) + + @classmethod + @async_to_sync + async def set_room_power_level_event(cls, room_id: str, event: str, power_level: int): # pragma: no cover + """ + Define the minimal power level to have to send a certain event type + in a given room. + + Returns either a `RoomPutStateResponse` if the request was successful or + a `RoomPutStateError` if there was an error with the request. + + Args: + room_id (str): The room id of the room where the power level + of the event should be updated. + event (str): The event name which minimal power level should + be updated. + power_level (int): The target power level to give. + """ + client = await cls._get_client() + if isinstance(client, FakeMatrixClient): + return None + + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + resp = await client.room_get_state_event(room_id, "m.room.power_levels") + content = resp.content + if event.startswith("m."): + content["events"][event] = power_level + else: + content[event] = power_level + return await client.room_put_state(room_id, "m.room.power_levels", content=content, state_key=resp.state_key) + + @classmethod + @async_to_sync + async def set_room_avatar(cls, room_id: str, avatar_uri: str): + """ + Define the avatar of a room. + + Returns either a `RoomPutStateResponse` if the request was successful or + a `RoomPutStateError` if there was an error with the request. + + Args: + room_id (str): The room id of the room where the avatar + should be changed. + avatar_uri (str): The internal avatar URI to apply. + """ + client = await cls._get_client() + if room_id.startswith("#"): + room_id = await cls.resolve_room_alias(room_id) + return await client.room_put_state(room_id, "m.room.avatar", content={ + "url": avatar_uri + }, state_key="") + + +if os.getenv("SYNAPSE_PASSWORD"): # pragma: no cover + from nio import RoomVisibility, RoomPreset + RoomVisibility = RoomVisibility + RoomPreset = RoomPreset +else: + # When running tests, faking matrix-nio classes to don't include the module + class RoomVisibility(Enum): + private = 'private' + public = 'public' + + class RoomPreset(Enum): + private_chat = "private_chat" + trusted_private_chat = "trusted_private_chat" + public_chat = "public_chat" + + +class FakeMatrixClient: + """ + Simulate a Matrix client to run tests, if no Matrix homeserver is connected. + """ + + def __getattribute__(self, item): + async def func(*_, **_2): + return None + return func diff --git a/tfjm/middlewares.py b/tfjm/middlewares.py index c5b8987..c26c733 100644 --- a/tfjm/middlewares.py +++ b/tfjm/middlewares.py @@ -1,12 +1,10 @@ -from django.conf import settings -from django.contrib.auth.models import AnonymousUser +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later from threading import local -from django.contrib.sessions.backends.db import SessionStore - -from member.models import TFJMUser -from tournament.models import Pool +from django.conf import settings +from django.contrib.auth.models import AnonymousUser, User USER_ATTR_NAME = getattr(settings, 'LOCAL_USER_ATTR_NAME', '_current_user') SESSION_ATTR_NAME = getattr(settings, 'LOCAL_SESSION_ATTR_NAME', '_current_session') @@ -21,23 +19,17 @@ def _set_current_user_and_ip(user=None, session=None, ip=None): setattr(_thread_locals, IP_ATTR_NAME, ip) -def get_current_user() -> TFJMUser: +def get_current_user() -> User: return getattr(_thread_locals, USER_ATTR_NAME, None) -def get_current_session() -> SessionStore: - return getattr(_thread_locals, SESSION_ATTR_NAME, None) - - def get_current_ip() -> str: return getattr(_thread_locals, IP_ATTR_NAME, None) def get_current_authenticated_user(): current_user = get_current_user() - if isinstance(current_user, AnonymousUser): - return None - return current_user + return None if isinstance(current_user, AnonymousUser) else current_user class SessionMiddleware(object): @@ -50,13 +42,10 @@ class SessionMiddleware(object): def __call__(self, request): if "_fake_user_id" in request.session: - request.user = TFJMUser.objects.get(pk=request.session["_fake_user_id"]) + request.user = User.objects.get(pk=request.session["_fake_user_id"]) user = request.user - if 'HTTP_X_FORWARDED_FOR' in request.META: - ip = request.META.get('HTTP_X_FORWARDED_FOR') - else: - ip = request.META.get('REMOTE_ADDR') + ip = request.META.get('HTTP_X_REAL_IP' if 'HTTP_X_REAL_IP' in request.META else 'REMOTE_ADDR') _set_current_user_and_ip(user, request.session, ip) response = self.get_response(request) @@ -65,29 +54,7 @@ class SessionMiddleware(object): return response -class ExtraAccessMiddleware(object): - """ - This middleware allows some non authenticated people to access to pool data. - """ - - def __init__(self, get_response): - self.get_response = get_response - - def __call__(self, request): - if "extra_access_token" in request.GET: - request.session["extra_access_token"] = request.GET["extra_access_token"] - if request.user.is_authenticated: - pool = Pool.objects.filter(extra_access_token=request.GET["extra_access_token"]) - if pool.exists(): - pool = pool.get() - pool.juries.add(request.user) - pool.save() - else: - request.session.setdefault("extra_access_token", "") - return self.get_response(request) - - -class TurbolinksMiddleware(object): +class TurbolinksMiddleware(object): # pragma: no cover """ Send the `Turbolinks-Location` header in response to a visit that was redirected, and Turbolinks will replace the browser's topmost history entry. diff --git a/tfjm/settings.py b/tfjm/settings.py index af3f842..76f5f9b 100644 --- a/tfjm/settings.py +++ b/tfjm/settings.py @@ -1,3 +1,6 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + """ Django settings for tfjm project. @@ -50,17 +53,30 @@ INSTALLED_APPS = [ 'django.contrib.staticfiles', 'django.forms', - 'django_extensions', - 'polymorphic', + 'address', + 'bootstrap_datepicker_plus', 'crispy_forms', 'django_tables2', + 'haystack', + 'logs', + 'phonenumber_field', + 'polymorphic', 'rest_framework', 'rest_framework.authtoken', - 'member', - 'tournament', + 'api', + 'eastereggs', + 'registration', + 'participation', ] +if "test" not in sys.argv: # pragma: no cover + INSTALLED_APPS += [ + 'cas_server', + 'django_extensions', + 'mailer', + ] + MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', @@ -72,7 +88,6 @@ MIDDLEWARE = [ 'django.middleware.locale.LocaleMiddleware', 'django.contrib.sites.middleware.CurrentSiteMiddleware', 'tfjm.middlewares.SessionMiddleware', - 'tfjm.middlewares.ExtraAccessMiddleware', 'tfjm.middlewares.TurbolinksMiddleware', ] @@ -83,8 +98,7 @@ LOGIN_REDIRECT_URL = "index" TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [os.path.join(BASE_DIR, 'templates')] - , + 'DIRS': [os.path.join(BASE_DIR, 'tfjm/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ @@ -120,13 +134,13 @@ AUTH_PASSWORD_VALIDATORS = [ }, ] -AUTH_USER_MODEL = 'member.TFJMUser' - PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', ] +CAS_AUTH_CLASS = 'registration.auth.CustomAuthUser' + REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser' @@ -159,8 +173,6 @@ USE_TZ = True LOCALE_PATHS = [os.path.join(BASE_DIR, "locale")] -FIXTURE_DIRS = [os.path.join(BASE_DIR, "tfjm/fixtures")] - # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ @@ -168,9 +180,11 @@ FIXTURE_DIRS = [os.path.join(BASE_DIR, "tfjm/fixtures")] STATIC_URL = '/static/' STATICFILES_DIRS = [ - os.path.join(BASE_DIR, "static"), + os.path.join(BASE_DIR, "tfjm/static"), ] +STATIC_ROOT = os.path.join(BASE_DIR, "static") + MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") @@ -179,9 +193,18 @@ CRISPY_TEMPLATE_PACK = 'bootstrap4' DJANGO_TABLES2_TEMPLATE = 'django_tables2/bootstrap4.html' +HAYSTACK_CONNECTIONS = { + 'default': { + 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', + 'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'), + } +} + +HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' + _db_type = os.getenv('DJANGO_DB_TYPE', 'sqlite').lower() -if _db_type == 'mysql' or _db_type.startswith('postgres') or _db_type == 'psql': +if _db_type == 'mysql' or _db_type.startswith('postgres') or _db_type == 'psql': # pragma: no cover DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql' if _db_type == 'mysql' else 'django.db.backends.postgresql_psycopg2', @@ -200,7 +223,19 @@ else: } } -if os.getenv("TFJM_STAGE", "dev") == "prod": - from .settings_prod import * +if os.getenv("TFJM_STAGE", "dev") == "prod": # pragma: no cover + from .settings_prod import * # noqa: F401,F403 else: - from .settings_dev import * + from .settings_dev import * # noqa: F401,F403 + +# Custom phone number format +PHONENUMBER_DB_FORMAT = 'NATIONAL' +PHONENUMBER_DEFAULT_REGION = 'FR' + +GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") + +# Use local Jquery +JQUERY_URL = False + +# Custom parameters +PROBLEM_COUNT = 8 diff --git a/tfjm/settings_dev.py b/tfjm/settings_dev.py index bf6e856..e20ecbb 100644 --- a/tfjm/settings_dev.py +++ b/tfjm/settings_dev.py @@ -1,3 +1,6 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases diff --git a/tfjm/settings_prod.py b/tfjm/settings_prod.py index fde3682..ac9168b 100644 --- a/tfjm/settings_prod.py +++ b/tfjm/settings_prod.py @@ -1,15 +1,19 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + import os # Break it, fix it! DEBUG = False # Mandatory ! -ALLOWED_HOSTS = ['inscription.tfjm.org'] +ALLOWED_HOSTS = ['inscription.tfjm.org', 'plateforme.tfjm.org'] SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'CHANGE_ME_IN_ENV_SETTINGS') # Emails -EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' +EMAIL_BACKEND = 'mailer.backend.DbBackend' +MAILER_EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_SSL = True EMAIL_HOST = os.getenv("SMTP_HOST") EMAIL_PORT = os.getenv("SMTP_PORT") diff --git a/tfjm/static/Fiche_sanitaire.pdf b/tfjm/static/Fiche_sanitaire.pdf new file mode 100644 index 0000000..c4f8c7e Binary files /dev/null and b/tfjm/static/Fiche_sanitaire.pdf differ diff --git a/assets/Fiche synthèse.pdf b/tfjm/static/Fiche_synthèse.pdf similarity index 100% rename from assets/Fiche synthèse.pdf rename to tfjm/static/Fiche_synthèse.pdf diff --git a/assets/Fiche synthèse.tex b/tfjm/static/Fiche_synthèse.tex similarity index 100% rename from assets/Fiche synthèse.tex rename to tfjm/static/Fiche_synthèse.tex diff --git a/tfjm/static/favicon.ico b/tfjm/static/favicon.ico new file mode 100644 index 0000000..f1126a6 Binary files /dev/null and b/tfjm/static/favicon.ico differ diff --git a/tfjm/static/logo.png b/tfjm/static/logo.png new file mode 100644 index 0000000..5cd274a Binary files /dev/null and b/tfjm/static/logo.png differ diff --git a/assets/logo_animath.png b/tfjm/static/logo_animath.png similarity index 100% rename from assets/logo_animath.png rename to tfjm/static/logo_animath.png diff --git a/assets/logo.svg b/tfjm/static/tfjm.svg similarity index 100% rename from assets/logo.svg rename to tfjm/static/tfjm.svg diff --git a/templates/400.html b/tfjm/templates/400.html similarity index 70% rename from templates/400.html rename to tfjm/templates/400.html index 3560652..7e5c934 100644 --- a/templates/400.html +++ b/tfjm/templates/400.html @@ -4,5 +4,5 @@ {% block content %}

{% trans "Bad request" %}

- {% blocktrans %}Sorry, your request was bad. Don't know what could be wrong. An email has been sent to webmasters with the details of the error. You can now drink a coke.{% endblocktrans %} + {% blocktrans %}Sorry, your request was bad. Don't know what could be wrong. An email has been sent to webmasters with the details of the error. You can now think about other solutions.{% endblocktrans %} {% endblock %} \ No newline at end of file diff --git a/templates/403.html b/tfjm/templates/403.html similarity index 100% rename from templates/403.html rename to tfjm/templates/403.html diff --git a/templates/404.html b/tfjm/templates/404.html similarity index 100% rename from templates/404.html rename to tfjm/templates/404.html diff --git a/templates/500.html b/tfjm/templates/500.html similarity index 70% rename from templates/500.html rename to tfjm/templates/500.html index 7cc0063..e1fdc24 100644 --- a/templates/500.html +++ b/tfjm/templates/500.html @@ -4,5 +4,5 @@ {% block content %}

{% trans "Server error" %}

- {% blocktrans %}Sorry, an error occurred when processing your request. An email has been sent to webmasters with the detail of the error, and this will be fixed soon. You can now drink a beer.{% endblocktrans %} + {% blocktrans %}Sorry, an error occurred when processing your request. An email has been sent to webmasters with the detail of the error, and this will be fixed soon. You can now think about other solutions.{% endblocktrans %} {% endblock %} diff --git a/tfjm/templates/about.html b/tfjm/templates/about.html new file mode 100644 index 0000000..0441db9 --- /dev/null +++ b/tfjm/templates/about.html @@ -0,0 +1,42 @@ +{% extends "base.html" %} + +{% block contenttitle %} +

À propos

+{% endblock %} + +{% block content %} +
+

+ La plateforme d'inscription du TFJM² a été développée entre 2019 et 2021 + par Yohann D'ANELLO, bénévole pour l'association Animath. Elle est vouée à être utilisée par les participants + pour intéragir avec les organisateurs et les autres participants. +

+ +

+ La plateforme est développée avec le framework Django et le code + source est accessible librement sur Gitlab. + Le code est distribué sous la licence GNU GPL v3, + qui vous autorise à consulter le code, à le partager, à réutiliser des parties du code et à contribuer. +

+ +

+ Le site principal présent sur https://inscription.tfjm.org + est hébergé chez Scaleway. +

+ +

+ Les données collectées par cette plateforme sont utilisées uniquement dans le cadre du TFJM² et sont + détruites dès l'action touche à sa fin, soit au plus tard 1 an après le début de l'action. Sur autorisation + explicite, des informations de contact peuvent être conservées afin d'être tenu au courant des actions futures + de l'association Animath. Aucune information personnelle n'est collectée à votre insu. Aucune information + personnelle n'est cédée à des tiers. +

+ +

+ Pour toute demande ou réclammation, merci de nous contacter à l'adresse + + contact@tfjm.org + . +

+
+{% endblock %} diff --git a/templates/amount_input.html b/tfjm/templates/amount_input.html similarity index 100% rename from templates/amount_input.html rename to tfjm/templates/amount_input.html diff --git a/templates/autocomplete_model.html b/tfjm/templates/autocomplete_model.html similarity index 100% rename from templates/autocomplete_model.html rename to tfjm/templates/autocomplete_model.html diff --git a/tfjm/templates/base.html b/tfjm/templates/base.html new file mode 100644 index 0000000..2c9f2f3 --- /dev/null +++ b/tfjm/templates/base.html @@ -0,0 +1,293 @@ +{% load static i18n static %} + + +{% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} + + + + + + {% block title %}{{ title }}{% endblock title %} - Plateforme du TFJM² + + + + {# Favicon #} + + + {% if no_cache %} + + {% endif %} + + {# Bootstrap CSS #} + + + + + {# JQuery, Bootstrap and Turbolinks JavaScript #} + + + + + {# Si un formulaire requiert des données supplémentaires (notamment JS), les données sont chargées #} + {% if form.media %} + {{ form.media }} + {% endif %} + + {% block extracss %}{% endblock %} + + +
+ + {% block fullcontent %} +
+ {% block contenttitle %}{% endblock %} + {% if user.is_authenticated and not user.registration.email_confirmed %} +
+ + {% url "registration:email_validation_resend" pk=user.pk as send_email_url %} + {% blocktrans trimmed %} + Your email address is not validated. Please click on the link you received by email. + You can resend a mail by clicking on this link. + {% endblocktrans %} +
+ {% endif %} +
+
+ {% block content %} +

Default content...

+ {% endblock content %} +
+
+ {% endblock %} +
+ +
+
+
+
+
+ + {% trans "Contact us" %} + + {% csrf_token %} +   +   + {% trans "About" %}   —   + + + +
+
+
+ + + +
+
+
+
+ +{% trans "All tournaments" as modal_title %} +{% include "base_modal.html" with modal_id="tournamentList" modal_additional_class="modal-lg" %} + +{% if user.is_authenticated %} + {% trans "All teams" as modal_title %} + {% include "base_modal.html" with modal_id="teams" modal_additional_class="modal-lg" %} + + {% trans "Search results" as modal_title %} + {% include "base_modal.html" with modal_id="search" modal_form_method="get" modal_additional_class="modal-lg" %} + + {% trans "Join team" as modal_title %} + {% trans "Join" as modal_button %} + {% url "participation:join_team" as modal_action %} + + {% include "base_modal.html" with modal_id="joinTeam" %} + {% trans "Create team" as modal_title %} + {% trans "Create" as modal_button %} + {% url "participation:create_team" as modal_action %} + {% include "base_modal.html" with modal_id="createTeam" modal_button_type="success" %} +{% else %} + {% trans "Log in" as modal_title %} + {% trans "Log in" as modal_button %} + {% url "login" as modal_action %} + {% include "base_modal.html" with modal_id="login" %} +{% endif %} + + + +{% block extrajavascript %}{% endblock %} + + diff --git a/tfjm/templates/base_modal.html b/tfjm/templates/base_modal.html new file mode 100644 index 0000000..ab9cf2a --- /dev/null +++ b/tfjm/templates/base_modal.html @@ -0,0 +1,24 @@ +{% load i18n %} + + \ No newline at end of file diff --git a/tfjm/templates/index.html b/tfjm/templates/index.html new file mode 100644 index 0000000..bc2c01d --- /dev/null +++ b/tfjm/templates/index.html @@ -0,0 +1,82 @@ +{% extends "base.html" %} + +{% block content %} +
+ +
+
+

+ Bienvenue sur le site d'inscription au 𝕋𝔽𝕁𝕄² ! +

+
+
+
+
+

+ Tu souhaites participer au 𝕋𝔽𝕁𝕄² ? +
+ Ton équipe est déjà formée ? +

+
+ +
+ +
+

Grande nouveauté :

+ Cette année, après avoir appris de l'édition complètement à distance de 2020, la communication se simplifie : + retrouvez-nous sur Element, disponible sur tous vos appareils, ou sur votre navigateur à l'adresse + element.tfjm.org + (connectez-vous avec les identifiants de cette plateforme une fois inscrits) +
+ +
+
Comment ça marche ?
+

+ Pour participer au 𝕋𝔽𝕁𝕄², il suffit de créer un compte sur la rubrique Inscription. + Vous devrez ensuite confirmer votre adresse e-mail. +

+ +

+ Vous pouvez accéder à votre compte via la rubrique Connexion. + Une fois connecté, vous pourrez créer une équipe ou en rejoindre une déjà créée par l'un de vos camarades + via un code d'accès qui vous aura été transmis. Vous serez ensuite invité à soumettre une autorisation de droit à l'image, + indispensable au bon déroulement du 𝕋𝔽𝕁𝕄². Une fois que votre équipe comporte au moins 3 participants (maximum 5) + et un encadrant, vous pourrez demander à valider votre équipe pour être apte à travailler sur le problème de votre choix. +

+ +

Je ne trouve pas d'équipe, aidez-moi !

+ +

+ En ayant créé un compte sur cette plateforme, vous créez également un compte sur la plateforme de chat dédiée + au 𝕋𝔽𝕁𝕄², basée sur le protocole Matrix et le client + Element. Cette interface de chat vous permet de communiquer avec les membres + de votre équipe, mais surtout de pouvoir participer au tirage au sort et discuter avec les autres équipes et + les organisateurs. +

+ +

+ Ce chat contient également un salon #je-cherche-une-equipe où vous pouvez crier à l'aide pour trouver + une équipe, ou compléter la votre s'il vous manque des participants. C'est un petit coin auprès du feu, un parc à + jeu où vous pouvez descendre en toboggan (en le désinfectant après utilisation), ne cherchez pas à être trop formel. +

+ +

J'ai une question

+ +

+ Pour toute question, vous pouvez soit la poser dans #faq dans l'onglet chat comme indiqué ci-dessus, soit nous + contacter par mail à l'adresse contact@tfjm.org. +

+ +
+ Attention aux dates ! Si vous ne finalisez pas votre inscription dans le délai indiqué, vous + ne pourrez malheureusement pas participer au 𝕋𝔽𝕁𝕄². +
+
+ +
+{% endblock %} diff --git a/templates/registration/logged_out.html b/tfjm/templates/registration/logged_out.html similarity index 100% rename from templates/registration/logged_out.html rename to tfjm/templates/registration/logged_out.html diff --git a/templates/registration/login.html b/tfjm/templates/registration/login.html similarity index 75% rename from templates/registration/login.html rename to tfjm/templates/registration/login.html index 64c5c26..db50a06 100644 --- a/templates/registration/login.html +++ b/tfjm/templates/registration/login.html @@ -17,9 +17,11 @@ SPDX-License-Identifier: GPL-2.0-or-later

{% endif %}
- {% csrf_token %} - {{ form | crispy }} +
+ {% csrf_token %} + {{ form | crispy }} + {% trans 'Forgotten your password or username?' %} +
- {% trans 'Forgotten your password or username?' %}
{% endblock %} diff --git a/tfjm/templates/search/search.html b/tfjm/templates/search/search.html new file mode 100644 index 0000000..d3f41f1 --- /dev/null +++ b/tfjm/templates/search/search.html @@ -0,0 +1,28 @@ +{% extends 'base.html' %} + +{% load crispy_forms_filters highlight i18n search_results_tables django_tables2 %} + +{% block content %} +

{% trans "Search" %}

+ +
+ {{ form|crispy }} + +
+ +
+ +

{% trans "Results" %}

+ +
+ {% regroup object_list by model_name as categories %} + {% for category in categories %} +

{% trans category.grouper|capfirst %}

+ {% with table=category.list|search_table %} + {% render_table table %} + {% endwith %} + {% empty %} +

{% trans "No results found." %}

+ {% endfor %} +
+{% endblock %} \ No newline at end of file diff --git a/tfjm/tests.py b/tfjm/tests.py new file mode 100644 index 0000000..3db574e --- /dev/null +++ b/tfjm/tests.py @@ -0,0 +1,27 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +import os + +from django.core.handlers.asgi import ASGIHandler +from django.core.handlers.wsgi import WSGIHandler +from django.test import TestCase + + +class TestLoadModules(TestCase): + """ + Load modules that are not used in development mode in order to increase coverage. + """ + def test_asgi(self): + from tfjm import asgi + self.assertTrue(isinstance(asgi.application, ASGIHandler)) + + def test_wsgi(self): + from tfjm import wsgi + self.assertTrue(isinstance(wsgi.application, WSGIHandler)) + + def test_load_production_settings(self): + os.putenv("TFJM_STAGE", "prod") + os.putenv("DJANGO_DB_TYPE", "postgres") + from tfjm import settings_prod + self.assertFalse(settings_prod.DEBUG) diff --git a/tfjm/tokens.py b/tfjm/tokens.py new file mode 100644 index 0000000..e0b4b33 --- /dev/null +++ b/tfjm/tokens.py @@ -0,0 +1,30 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.contrib.auth.tokens import PasswordResetTokenGenerator + + +class AccountActivationTokenGenerator(PasswordResetTokenGenerator): + """ + Create a unique token generator to confirm email addresses. + """ + def _make_hash_value(self, user, timestamp): + """ + Hash the user's primary key and some user state that's sure to change + after an account validation to produce a token that invalidated when + it's used: + 1. The user.profile.email_confirmed field will change upon an account + validation. + 2. The last_login field will usually be updated very shortly after + an account validation. + Failing those things, settings.PASSWORD_RESET_TIMEOUT_DAYS eventually + invalidates the token. + """ + # Truncate microseconds so that tokens are consistent even if the + # database doesn't support microseconds. + login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None) + return str(user.pk) + str(user.email) + str(user.registration.email_confirmed)\ + + str(login_timestamp) + str(timestamp) + + +email_validation_token = AccountActivationTokenGenerator() diff --git a/tfjm/urls.py b/tfjm/urls.py index e9903a6..00e1559 100644 --- a/tfjm/urls.py +++ b/tfjm/urls.py @@ -1,3 +1,6 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + """tfjm URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: @@ -13,43 +16,51 @@ Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ -import re - from django.conf import settings from django.contrib import admin -from django.contrib.staticfiles.views import serve -from django.urls import path, include, re_path -from django.views.defaults import bad_request, permission_denied, page_not_found, server_error -from django.views.generic import TemplateView, RedirectView +from django.urls import include, path +from django.views.defaults import bad_request, page_not_found, permission_denied, server_error +from django.views.generic import TemplateView +from registration.views import HealthSheetView, ParentalAuthorizationView, PhotoAuthorizationView, \ + ScholarshipView, SolutionView, SynthesisView -from member.views import DocumentView +from .views import AdminSearchView urlpatterns = [ - path('', TemplateView.as_view(template_name="index.html"), name="index"), + path('', TemplateView.as_view(template_name="index.html"), name='index'), + path('about/', TemplateView.as_view(template_name="about.html"), name='about'), path('i18n/', include('django.conf.urls.i18n')), path('admin/doc/', include('django.contrib.admindocs.urls')), path('admin/', admin.site.urls, name="admin"), path('accounts/', include('django.contrib.auth.urls')), - - path('member/', include('member.urls')), - path('tournament/', include('tournament.urls')), - - path("media//", DocumentView.as_view(), name="document"), + path('search/', AdminSearchView.as_view(), name="haystack_search"), path('api/', include('api.urls')), + path('participation/', include('participation.urls')), + path('registration/', include('registration.urls')), - re_path(r'^{prefix}(?P.*)$'.format(prefix=re.escape(settings.STATIC_URL.lstrip('/'))), serve), + path('media/authorization/photo//', PhotoAuthorizationView.as_view(), + name='photo_authorization'), + path('media/authorization/health//', HealthSheetView.as_view(), + name='health_sheet'), + path('media/authorization/parental//', ParentalAuthorizationView.as_view(), + name='parental_authorization'), + path('media/authorization/scholarship//', ScholarshipView.as_view(), + name='scholarship'), - # Supporting old paths - path('inscription/', RedirectView.as_view(pattern_name="member:signup")), - path('connexion/', RedirectView.as_view(pattern_name="login")), - path('tournois/', RedirectView.as_view(pattern_name="tournament:list")), - path('mon-compte/', RedirectView.as_view(pattern_name="member:my_account")), - path('mon-equipe/', RedirectView.as_view(pattern_name="member:my_team")), - path('solutions/', RedirectView.as_view(pattern_name="tournament:solutions")), - path('syntheses/', RedirectView.as_view(pattern_name="tournament:syntheses")), + path('media/solutions//', SolutionView.as_view(), + name='solution'), + path('media/syntheses//', SynthesisView.as_view(), + name='synthesis'), + + path('', include('eastereggs.urls')), ] +if 'cas_server' in settings.INSTALLED_APPS: # pragma: no cover + urlpatterns += [ + path('cas/', include('cas_server.urls', namespace="cas_server")), + ] + handler400 = bad_request handler403 = permission_denied handler404 = page_not_found diff --git a/tfjm/views.py b/tfjm/views.py new file mode 100644 index 0000000..5160bd9 --- /dev/null +++ b/tfjm/views.py @@ -0,0 +1,31 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + +from django.contrib.auth.mixins import LoginRequiredMixin +from haystack.generic_views import SearchView + + +class AdminMixin(LoginRequiredMixin): + def dispatch(self, request, *args, **kwargs): + if request.user.is_authenticated and not request.user.registration.is_admin: + self.handle_no_permission() + return super().dispatch(request, *args, **kwargs) + + +class VolunteerMixin(LoginRequiredMixin): + def dispatch(self, request, *args, **kwargs): + if request.user.is_authenticated and not request.user.registration.is_volunteer: + self.handle_no_permission() + return super().dispatch(request, *args, **kwargs) + + +class UserMixin(LoginRequiredMixin): + def dispatch(self, request, *args, **kwargs): + user = request.user + if user.is_authenticated and not user.registration.is_admin and user.registration.pk != kwargs["pk"]: + self.handle_no_permission() + return super().dispatch(request, *args, **kwargs) + + +class AdminSearchView(AdminMixin, SearchView): + pass diff --git a/tfjm/wsgi.py b/tfjm/wsgi.py index 7fd654c..5a0ea81 100644 --- a/tfjm/wsgi.py +++ b/tfjm/wsgi.py @@ -1,3 +1,6 @@ +# Copyright (C) 2020 by Animath +# SPDX-License-Identifier: GPL-3.0-or-later + """ WSGI config for tfjm project. diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..55a8978 --- /dev/null +++ b/tox.ini @@ -0,0 +1,60 @@ +[tox] +envlist = + py38 + py39 + + linters +skipsdist = True + +[testenv] +sitepackages = False +deps = + coverage + Django~=3.1 + django-address~=0.2 + django-bootstrap-datepicker-plus~=3.0 + django-crispy-forms~=1.9 + django-filter~=2.3 + django-haystack~=3.0 + django-phonenumber-field~=5.0.0 + django-polymorphic~=3.0 + django-tables2~=2.3 + djangorestframework~=3.12 + django-rest-polymorphic~=0.1 + phonenumbers~=8.9.10 + PyPDF3~=1.0.2 + python-magic==0.4.18 + whoosh~=2.7 +commands = + coverage run --source=apps,tfjm ./manage.py test apps/ tfjm/ + coverage report -m + +[testenv:linters] +deps = + flake8 + flake8-colors + flake8-django + flake8-import-order + flake8-typing-imports + pep8-naming + pyflakes +commands = + flake8 apps/ tfjm/ + +[flake8] +exclude = + .tox, + .git, + __pycache__, + build, + dist, + *.pyc, + *.egg-info, + .cache, + .eggs, + *migrations* +max-complexity = 10 +max-line-length = 160 +import-order-style = google +application-import-names = flake8 +format = ${cyan}%(path)s${reset}:${yellow_bold}%(row)d${reset}:${green_bold}%(col)d${reset}: ${red_bold}%(code)s${reset} %(text)s