How to override Grand total calculations on Invoice or SalesOrder

We want to add one new field used credits field in total calculations.
These credits will be added in case of refund.
if any customer has credits in his grand total should be reduced by the credit amount.

E.g. Customer got a refund of 100 bucks
New service amount is 5000
Discount on this service is 200
tax =0
Grand total should be 5000-200-100=4700

How I can override function from cscript to incorporate custom field calculations.