In chapter 678, why did Madara suddenly turn into Kaguya? Was this all planned from beginning?
When Black Zetsu impaled Madara, he transfered Kaguya's will into Madara. By this process, Kaguya was revived by using Madara's body as the host vessel. And yes, it was planned from beginning by Zetsu.
Black Zetsu's history:
He was created by Kaguya and served only her. He acted as if he was Madara's creation, so he could facilitate the revival of his "mother", aka Kaguya. To do this, he planned the activation of Infinite Tsukuyomi by influencing Madara and the Akatsuki.
Further reading: Kaguya Ōtsutsuki
Black Zetsu is a shapeless manifestation of Kaguya's will, created before she was sealed by Hagoromo and Hamura. It planned to manipulate Indra Otsutsuki and his descendants to one day wield the Rinnegan and activate the Infinite Tsukuyomi.
Once Madara activated the Infinite Tsukuyomi and trapped everyones chakra inside the God Tree, Black Zetsu then stabbed Madara while he was sapped of his chakra, and uses his Ten Tail Jinchuriki body and combined his will to create a pseudo Kaguya.