The equality $2$ can be determined using the observation that the sum of all elements belonging to each set $S_i$ is the sum of all residues so:$$ \overbrace{\frac{N}{r_1}a_1+r_1.\frac{N}{2r_1}(\frac{N}{r_1}-1)}^{\text{The sum of residus }\in S_1}+\cdots\cdots+\overbrace{\frac{N}{r_n}a_n+r_n.\frac{N}{2r_n}(\frac{N}{r_1}-1)}^{\text{The sum of residus }\in S_n}=\overbrace{\frac{N(N-1)}{2}}^{\text{The sum of all residus }}$$
with some simplification you get $(2)$