
// **************************** 7.3.1  *******************8

newDoc = db.orders.findAndModify({
     query: {
       user_id: ObjectId("4c4b1476238d3b4dd5000001"),
       state: 'CART'
     },
     update: {
       $set: {
         state: 'PRE-AUTHORIZE'
       }
     },
     'new': true
   })

/*  Wynik: 

{
        "_id" : ObjectId("6a5b1476238d3b4dd5000048"),
        "user_id" : ObjectId("4c4b1476238d3b4dd5000001"),
        "purchase_data" : ISODate("2014-08-01T07:00:00Z"),
        "state" : "PRE-AUTHORIZE",
        "line_items" : [
                {
                        "_id" : ObjectId("4c4b1476238d3b4dd5003981"),
                        "sku" : "9092",
                        "name" : "Bardzo duża taczka",
                        "quantity" : 2,
                        "pricing" : {
                                "retail" : 5897,
                                "sale" : 4897
                        }
                },
                {
                        "_id" : ObjectId("4c4b1476238d3b4dd5003982"),
                        "sku" : "10027",
                        "name" : "Gumowe rękawice robocze, kolor czarny",
                        "quantity" : 1,
                        "pricing" : {
                                "retail" : 1499,
                                "sale" : 1299
                        }
                }
        ],
        "shipping_address" : {
                "street" : "588 5th Street",
                "city" : "Brooklyn",
                "state" : "NY",
                "zip" : 11215
        },
        "sub_total" : 6196,
        "tax" : 600
}
*/

// Symulacja obliczenia wartości całkowitej zamówienia i ustalenia jej na 99000.
// To nie zostało pokazane w książce.
query = {
       user_id: ObjectId("4c4b1476238d3b4dd5000001"),
       state: "PRE-AUTHORIZE"
     }
update = {"$set" : {total: 99000}}
db.orders.update(query,update)

// Przejście do stanu AUTHORIZING, tylko jeśli wartość całkowita zamówienia nie uległa zmianie.
oldDoc = db.orders.findAndModify({
     query: {
       user_id: ObjectId("4c4b1476238d3b4dd5000001"),
       total: 99000,
       state: "PRE-AUTHORIZE"
     },
     update: {
       '$set': {
         state: "AUTHORIZING"
       }
     }
   })

// I wreszcie przejście do stanu PRE-SHIPPING.
auth_doc = {
   ts: new Date(),
   cc: 3432003948293040, 
   id: 2923838291029384483949348,
   gateway: "Authorize.net"
 }
 db.orders.findAndModify({
     query: {
       user_id: ObjectId("4c4b1476238d3b4dd5000001"),
       state: "AUTHORIZING"
     },
     update: {
       $set: {
         state: "PRE-SHIPPING",
         authorization: auth_doc
       }
     }
   })
   
// Sprawdzenie wyniku - otrzymanie nowego zamówienia.
query = {
       user_id: ObjectId("4c4b1476238d3b4dd5000001"),
       state: "PRE-SHIPPING"
     }
     
db.orders.find(query).pretty()


       
       
