When someone gets exactly what it seems like they deserve, it's poetic justice. When poetic justice happens in a book (or in life), the bad guys end up being punished.
When being good is rewarded with good luck or a happy ending — or doing something awful results in punishment — you can call it poetic justice. If a bullied computer geek grows up to be happy and successful, it's poetic justice. A seventeenth century drama critic came up with this phrase, emphasizing that books should model good morals to their readers by always doling out poetic justice, so that evil never goes unpunished and good characters live happily ever after.