When a patent is invalidated, what happens to all the proceeds generated by the company through licensing and legal compensations? Does the company have to pay back all the money obtained through that invalid patent, or it doesn't matter and what is done is done?
It depends on the contract
A well-drafted contract would have allowed for this contingency and set out the rights and obligations of each party.
If the contract is silent then it depends on if the patent was revoked or invalidated.
A revoked patent was valid until the date of its revocation and the contract would operate normally up until that date. After revocation, the (previous) patent holder is now in breach of their contract - they promised to licence a patent and they can't. This would allow the (previous) licensee to terminate the contract and/or sue for damages.
An invalid patent was never a patent and therefore never good consideration for a contract. If there was some other consideration alongside the patent, the contract would be valid and the licensor would have been in breach from the beginning - see above. If there was no other consideration, there never was a contract and there is no remedy in contract law for either party, that is, contract law cannot intervene so the status-quo remains. However, its possible the licensee could make a claim in equity on the basis of unjust enrichment. It's a 50-50 call whether such a claim would succeed because it's by no means obvious that the situation is unjust given the outcome if the patent was revoked rather than invalid.
As to refunds, at common law, you are only entitled to a refund if there is a total failure of consideration. So, for example, if you embark on a 10 day cruise and the ship sinks after 2 days, you might be (probably are) entitled to damages but you are not entitled to a refund because you got some of what you paid for. In many places, modern consumer protection law has extended the basis for a refund beyond the common law but it is unlikely that consumer protection law will apply to a purely business transaction like a patent licence.