The song is in D Maj
I can't understand how that B Maj at bar 12 came out
G maj7(IV), A(V) then B maj (VI) ?
How does this work ?
The song is definitely in D major, it just doesn't resolve to D major chords very often in this excerpt.
The B chord is a secondary dominant as part of a deceptive resolution (IV-V-VI). It's kind of like ii-V-iii-vi-IV...* in that the deceptive resolution is there, skipping the iii in that circle of fifths example. The B chord normally would be minor, but making it major gives it that color, and also its tendency to resolve to Em (though in this case it's G major, but they're both subdominants, so it doesn't matter).
Also worth noting is that the A6 noted there also contains the 9th, so I'd call it A6/9, and it already contains the note B, which sets up the B major chord.