I will take for example a person who has been sentenced to go to prison and if he wants to avoid it, he has to deal with socially useful work for a certain period of time as a substitute.
How do we call this person or what term to use?
This is known as community service.
People convicted of a crime may be required to perform community service
It also mentions:
Community service is distinct from volunteering, since it is not always performed on a voluntary basis.
When I Googled
meaning of community service, it listed a meaning from Oxford that reads:
com·mu·ni·ty serv·ice noun
voluntary work intended to help people in a particular area.
unpaid work, intended to be of social use, that an offender is required to do instead of going to prison.
That second definition seems to be what you're looking for, but it's worth mentioning that we need to rely on context to determine if we are talking about volunteer vs. mandated community service. But usually that's not an issue:
The Boy Scouts repaired the hiking trail bridges as part of their community service.
The convicted suspect was ordered to fifty hours of community service in lieu of a short prison sentence.
As for the name of the person, I don't think there's a common name for that. I would likely use a term that would be the same as if the person was serving a stint in prison (excluding the term prisoner, of course). The word might change depending on the nature of the crime and punishment; some examples might include: convict, felon, criminal, parolee, offender, or perhaps (if the person is a minor) convicted juvenile delinquent.