320bc7194e1cb181aefa72334a7032761787a960
[feisty_meow.git] / huffware / huffotronic_scripts / vendor_sales_manager_v3.1.txt
1 
2 // huffware script: vendor sales manager, by fred huffhines.
3 //
4 // handles the vending of one set of items which are contained inside the vendor
5 // object.  when the customer pays for it, they get a copy in a folder named after
6 // the object, and the owner gets an instant message describing the purchase.
7 //
8 // parts of this script were gratefully snagged from Ilse's Basic Vendor version 1.3, by Ilse Mannonen.
9 //
10 // fred's changes are licensed by:
11 //   this script is licensed by the GPL v3 which is documented at: http://www.gnu.org/licenses/gpl.html
12 //   do not use it in objects without fully realizing you are implicitly accepting that license.
13 //
14
15 // usage notes:
16 //
17 // the config notecard is hopefully pretty self explanatory.
18 // here's an example config for a random gift vendor...
19 //   price=<18, 37, 0>
20 //   seller_name=gorp
21 //   thank_you=Thank you very much fer your purchase!
22 //   emails=foop@norgrufextorp.cog
23 //   single=random
24 //   text=Random Prize Machine\nPay the random price and get a random prize!
25 //
26 // here's an example config for a normal vendor (that gives out all of
27 // the contents to a customer on purchase)...
28 //   price=82
29 //   seller_name=gorp
30 //   thank_you=Thank you very much fer your purchase!
31 //   emails=foop@norgrufextorp.cog
32 //   text=Buy an anti-ape machine for your garage!
33 //
34 // the split notecard requires a set of lines in the format:
35 //   KEY|PERCENT
36 // for example: 0000000000bad|30 would give 30 percent of purchases to
37 // the bogus key.  be sure to find out the real keys involved.
38
39 // initial defaults; these need to be overridden by the notecard.
40 integer price = 9999;
41 string str_thank_you = "Default thank you message.  Thanks.";
42 string seller_name = "Frodo's Rings";
43 string emails = "";
44
45 // if we're allowed to randomly charge in a range, then this records our range.
46 integer lowest_price = 0;
47 integer highest_price = 0;
48
49 // variables for split notecard.
50 integer splitline = 0;
51 key splitrequestid;
52
53 // variables for config notecard.
54 integer configline = 0;
55 key configrequestid;
56
57 // keys and percentages that profits should be split with.
58 list splitkeys;
59 list splitpercents;
60
61 // this is set to true if the vendor should select a single item
62 // at random from the contents and give it to the customer.
63 integer single_random_give = FALSE;
64
65 list current_giving_list;  // if there is a transaction occurring, this has the contents to be given.
66
67 float REPRICING_PERIOD = 20.0;  // how frequently we redo the price of the object, if it's random.
68
69 // lets the potential customer know what is being sold.
70 describe_product()
71 {
72     if (lowest_price != 0)
73         llSay(0, "Cost is random and will be between L$" + (string)lowest_price
74             + " and L$" + (string)highest_price + ".");
75     else
76         llSay(0, "Cost is L$" + (string)price + ".");
77     if (single_random_give)
78         llSay(0, "This vendor is in random grab-bag mode; purchasers will receive one random object from the contents.");
79 }
80
81 // process the customer's attempt to hand us their money.
82 take_their_moolah(key customer, integer amount)
83 {
84     // check the amount they paid.
85     if ( (amount == price) || ( (lowest_price != 0) && (amount > lowest_price) ) ) {
86         integer worked = give_objects_appropriately(customer);
87         if (!worked) {
88             llSay(0, "Oh my, this is not good.  There were no objects left to give out.  We'll refund your money now.");
89             llGiveMoney(customer, amount);
90             return;
91         }
92
93         // thank the purchaser.
94         llSay(0, str_thank_you);
95         // IM the seller.
96         llInstantMessage(llGetOwner(), "Yay! " + llKey2Name(customer)
97             + " just paid me L$" + (string)amount
98             + " in " + llGetRegionName() + ".");
99         // do the split.
100         integer n;
101         for (n = 0; n < llGetListLength(splitkeys); n++) {
102             float percentage = llList2Float(splitpercents, n) / 100.0;
103             integer payout = llRound(price * percentage);
104             key payee = llList2Key(splitkeys, n);
105             llInstantMessage(llGetOwner(), "Paying L$" + (string)payout
106                 + " to key " + (string)payee + " in commission.");
107             llGiveMoney(payee,payout);
108             string text_percentage = (string)((integer)(percentage * 1000.0) / 10);
109             llInstantMessage(payee, "Woot!  You have been paid a L$"
110                 + (string)payout
111                 + " (" + text_percentage + "%) commission for a sale in "
112                 + llGetRegionName()
113                 + "--customer name is " + llKey2Name(customer)
114                 + ".");
115         }
116         // send out email alerts if there are any recipients.
117         list email_addrs = llParseString2List(emails, ["|"], []);
118         for (n = 0; n < llGetListLength(email_addrs); n++) {
119             string curr = llList2String(email_addrs, n);
120             llEmail(curr, llGetObjectName() + " made a sale in " + llGetRegionName(),
121                 "Wheee, there was a sale in " + llGetRegionName() + " of these items "
122                 + dump_list(current_giving_list) + " to a customer named "
123                 + llKey2Name(customer) + ".");
124         }
125     } else {
126         // oops, something stupid.  give it all back.
127         llInstantMessage(customer, "I'm sorry, but you paid L$" + (string)amount + ", and this item costs only L$" + (string)price + ".  We'll refund your money right away.");
128         llGiveMoney(customer, amount);
129     }
130     
131     if (lowest_price != 0) {
132         // reset the timer to fire soon and change the price.
133         llSetTimerEvent(0.5);
134     }
135 }
136   
137 // hands out objects according to the configured process.
138 integer give_objects_appropriately(key customer)
139 {
140     current_giving_list = [];  // clear out last gifts.
141     if (!single_random_give) {
142         // this mode is only for the normal non random picker.
143         // if it's right, give everything but scripts and config notecards.
144         integer m;
145         for (m = 0; m < llGetInventoryNumber(INVENTORY_ALL); m++) {
146             string itemname = llGetInventoryName(INVENTORY_ALL, m);
147             if (llGetInventoryType(itemname) == INVENTORY_NOTECARD) {
148                 //only add notecards if they don't start with ~
149                 if (llGetSubString(itemname, 0, 0) != "~") {
150                     current_giving_list += [itemname];
151                 }
152             } else {
153                 if (llGetInventoryType(itemname) != INVENTORY_SCRIPT) {
154                     current_giving_list += [itemname];
155                 }
156             }
157         }
158     } else {
159         // aha, the freaky random gift giving model.
160         if (llGetInventoryNumber(INVENTORY_OBJECT) >= 1) {
161             // we made sure we have something to give out.
162             integer which = (integer)randomize_within_range(0, llGetInventoryNumber(INVENTORY_OBJECT) - 1, FALSE);
163             if (which >= 0) {
164                 current_giving_list += [ llGetInventoryName(INVENTORY_OBJECT, which) ];
165             }
166         }
167     }
168     
169 //llOwnerSay("about to give out " + (string)current_giving_list);
170     if (llGetListLength(current_giving_list) > 0) {
171         if (single_random_give)
172             llGiveInventory(customer, llList2String(current_giving_list, 0));
173         else
174             llGiveInventoryList(customer, seller_name + " - " + llGetObjectName(), current_giving_list);
175         return TRUE;
176     } else return FALSE;  // oops.
177 }
178
179 // a wrapper for setting the object's text, but handling carriage returns.
180 set_text(string object_label)
181 {
182     // reset the label to a decorated version of object name if it was default.
183     if (object_label == "default") object_label = llGetObjectName();
184     integer indy;
185     integer keep_going = TRUE;
186     while (keep_going) {
187         indy = find_substring(object_label, "\\n");
188         if (indy < 0) {
189             keep_going = FALSE;
190         } else {
191             object_label = llGetSubString(object_label, 0, indy - 1)
192                 + "\n" + llGetSubString(object_label, indy + 2, -1);
193         }
194     }
195 //log_it("setting text: " + object_label);
196     llSetText(object_label, <0.4, 0.7, 0.95>, 1.0);
197 }
198
199 // eats config items that are read from the notecard.
200 process_configuration_items(string data)
201 {
202     string token = llList2String(llParseString2List(data, ["="], []), 0);
203     string value = llList2String(llParseString2List(data, ["="], []), 1);
204     if (token == "price") {
205         if (is_prefix(value, "<")) {
206             // we have a random price range definition.
207             vector ranger = (vector)value;
208             lowest_price = (integer)ranger.x;
209             highest_price = (integer)ranger.y;
210             price = lowest_price;
211             // we run a timer to keep the price fluctuating for the user.
212             if (lowest_price != 0) {
213                 // zap the timer event really soon.
214                 llSetTimerEvent(0.5);
215             }
216         } else {
217             // this is hopefully a simple price definition.
218             price = (integer)value;
219             lowest_price = 0;  // reset so no one gets wrong ideas.
220         }
221         if (price == 0) {
222             llOwnerSay("Failure in setting price; object will be defective until config is fixed.");
223         } else {
224             llSetPayPrice(PAY_HIDE, [price, PAY_HIDE, PAY_HIDE, PAY_HIDE]);
225             llMessageLinked(LINK_SET, price, "price", NULL_KEY);
226             describe_product();
227         }
228     } else if (token == "thank_you") {
229         str_thank_you = value;
230     } else if (token == "seller_name") {
231         seller_name = value;
232     } else if (token == "emails") {
233         emails = value;
234     } else if (token == "single") {
235         if (value == "random") {
236             single_random_give = TRUE;
237             describe_product();
238         }
239     } else if (token == "text") {
240         set_text(value);
241 //        llSetText(value, <.4, .9, .7>, 1.0);        
242     }
243     configline++;
244     configrequestid = llGetNotecardLine("~CONFIG", configline);
245 }
246
247 //////////////
248 // from hufflets...
249
250 // returns the index of the first occurrence of "pattern" inside
251 // the "full_string".  if it is not found, then a negative number is returned.
252 integer find_substring(string full_string, string pattern)
253 { return llSubStringIndex(llToLower(full_string), llToLower(pattern)); }
254
255 // returns a printable form of the list.
256 string dump_list(list to_show)
257 {
258     integer len = llGetListLength(to_show);
259     integer i;
260     string text;
261     for (i = 0; i < len; i++) {
262         string next_line = llList2String(to_show, i);
263         if (find_substring(next_line, " ") >= 0) {
264             // this guy has a space in it, so quote it.
265             next_line = "'" + next_line + "'";
266         }
267         text += next_line;
268         if (i < len - 1) text += " ";
269     }
270     return text;
271 }
272
273 // returns TRUE if the "prefix" string is the first part of "compare_with".
274 integer is_prefix(string compare_with, string prefix)
275 { return find_substring(compare_with, prefix) == 0; }
276
277 // returns a number at most "maximum" and at least "minimum".
278 // if "allow_negative" is TRUE, then the return may be positive or negative.
279 float randomize_within_range(float minimum, float maximum, integer allow_negative)
280 {
281     if (minimum > maximum) {
282         // flip the two if they are reversed.
283         float temp = minimum; minimum = maximum; maximum = temp;
284     }
285     float to_return = minimum + llFrand(maximum - minimum);
286     if (allow_negative) {
287         if (llFrand(1.0) < 0.5) to_return *= -1.0;
288     }
289     return to_return;
290 }
291
292 //////////////
293 // huffware script: auto-retire, by fred huffhines, version 2.5.
294 // distributed under BSD-like license.
295 //   !!  keep in mind that this code must be *copied* into another
296 //   !!  script that you wish to add auto-retirement capability to.
297 // when a script has auto_retire in it, it can be dropped into an
298 // object and the most recent version of the script will destroy
299 // all older versions.
300 //
301 // the version numbers are embedded into the script names themselves.
302 // the notation for versions uses a letter 'v', followed by two numbers
303 // in the form "major.minor".
304 // major and minor versions are implicitly considered as a floating point
305 // number that increases with each newer version of the script.  thus,
306 // "hazmap v0.1" might be the first script in the "hazmap" script continuum,
307 // and "hazmap v3.2" is a more recent version.
308 //
309 // example usage of the auto-retirement script:
310 //     default {
311 //         state_entry() {
312 //            auto_retire();  // make sure newest addition is only version of script.
313 //        }
314 //     }
315 // this script is partly based on the self-upgrading scripts from markov brodsky
316 // and jippen faddoul.
317 //////////////
318 auto_retire() {
319     string self = llGetScriptName();  // the name of this script.
320     list split = compute_basename_and_version(self);
321     if (llGetListLength(split) != 2) return;  // nothing to do for this script.
322     string basename = llList2String(split, 0);  // script name with no version attached.
323     string version_string = llList2String(split, 1);  // the version found.
324     integer posn;
325     // find any scripts that match the basename.  they are variants of this script.
326     for (posn = llGetInventoryNumber(INVENTORY_SCRIPT) - 1; posn >= 0; posn--) {
327 //log_it("invpo=" + (string)posn);
328         string curr_script = llGetInventoryName(INVENTORY_SCRIPT, posn);
329         if ( (curr_script != self) && (llSubStringIndex(curr_script, basename) == 0) ) {
330             // found a basic match at least.
331             list inv_split = compute_basename_and_version(curr_script);
332             if (llGetListLength(inv_split) == 2) {
333                 // see if this script is more ancient.
334                 string inv_version_string = llList2String(inv_split, 1);  // the version found.
335                 // must make sure that the retiring script is completely the identical basename;
336                 // just matching in the front doesn't make it a relative.
337                 if ( (llList2String(inv_split, 0) == basename)
338                     && ((float)inv_version_string < (float)version_string) ) {
339                     // remove script with same name from inventory that has inferior version.
340                     llRemoveInventory(curr_script);
341                 }
342             }
343         }
344     }
345 }
346 //
347 // separates the base script name and version number.  used by auto_retire.
348 list compute_basename_and_version(string to_chop_up)
349 {
350     // minimum script name is 2 characters plus a version.
351     integer space_v_posn;
352     // find the last useful space and 'v' combo.
353     for (space_v_posn = llStringLength(to_chop_up) - 3;
354         (space_v_posn >= 2) && (llGetSubString(to_chop_up, space_v_posn, space_v_posn + 1) != " v");
355         space_v_posn--) {
356         // look for space and v but do nothing else.
357 //log_it("pos=" + (string)space_v_posn);
358     }
359     if (space_v_posn < 2) return [];  // no space found.
360 //log_it("space v@" + (string)space_v_posn);
361     // now we zoom through the stuff after our beloved v character and find any evil
362     // space characters, which are most likely from SL having found a duplicate item
363     // name and not so helpfully renamed it for us.
364     integer indy;
365     for (indy = llStringLength(to_chop_up) - 1; indy > space_v_posn; indy--) {
366 //log_it("indy=" + (string)space_v_posn);
367         if (llGetSubString(to_chop_up, indy, indy) == " ") {
368             // found one; zap it.  since we're going backwards we don't need to
369             // adjust the loop at all.
370             to_chop_up = llDeleteSubString(to_chop_up, indy, indy);
371 //log_it("saw case of previously redundant item, aieee.  flattened: " + to_chop_up);
372         }
373     }
374     string full_suffix = llGetSubString(to_chop_up, space_v_posn, -1);
375     // ditch the space character for our numerical check.
376     string chop_suffix = llGetSubString(full_suffix, 1, llStringLength(full_suffix) - 1);
377     // strip out a 'v' if there is one.
378     if (llGetSubString(chop_suffix, 0, 0) == "v")
379         chop_suffix = llGetSubString(chop_suffix, 1, llStringLength(chop_suffix) - 1);
380     // if valid floating point number and greater than zero, that works for our version.
381     string basename = to_chop_up;  // script name with no version attached.
382     if ((float)chop_suffix > 0.0) {
383         // this is a big success right here.
384         basename = llGetSubString(to_chop_up, 0, -llStringLength(full_suffix) - 1);
385         return [ basename, chop_suffix ];
386     }
387     // seems like we found nothing useful.
388     return [];
389 }
390 //
391 //////////////
392
393 default {
394     state_entry() { if (llSubStringIndex(llGetObjectName(), "huffotronic") < 0) state real_default; }
395     on_rez(integer parm) { state rerun; }
396 }
397 state rerun { state_entry() { state default; } }
398
399 state real_default
400 {
401     state_entry()
402     {
403         auto_retire();  // make sure newest addition is only version of script.
404         splitrequestid = llGetNotecardLine("~SPLIT", splitline);
405         configrequestid = llGetNotecardLine("~CONFIG", configline);
406         llSetPayPrice(PAY_HIDE, [price, PAY_HIDE, PAY_HIDE, PAY_HIDE]);
407         llSetText("garp", <0, 0, 0>, 0);
408     }
409     
410     on_rez(integer start_param) { llResetScript(); }
411         
412     timer() {
413         llSetTimerEvent(0);
414         price = (integer)randomize_within_range(lowest_price, highest_price, FALSE);
415         llSetPayPrice(PAY_HIDE, [price, PAY_HIDE, PAY_HIDE, PAY_HIDE]);
416         llSetTimerEvent(REPRICING_PERIOD);
417     }    
418             
419     money(key customer, integer amount) { take_their_moolah(customer, amount); }
420
421     // restart if something was added to the vendor.    
422     changed(integer change) {
423         if (change & CHANGED_INVENTORY) { llSleep(3.14159265358); llResetScript(); }
424     }
425     
426     touch_start(integer total_number)
427     {
428         // give the first non-config notecard.
429         integer n;
430         for (n = 0; n < llGetInventoryNumber(INVENTORY_NOTECARD); n++) {
431             if (llGetSubString(llGetInventoryName(INVENTORY_NOTECARD, n), 0, 0) != "~") {
432                 llGiveInventory(llDetectedKey(0), llGetInventoryName(INVENTORY_NOTECARD, n));
433                 return;
434             }
435         }
436         describe_product();
437     }    
438
439     // read the two configuration notecards.
440     dataserver(key queryid, string data)
441     {
442         if ( (queryid == splitrequestid) && (data != EOF) ) {
443             list tmp = llParseString2List(data, ["|"], [""]);
444             if (llGetListLength(tmp) > 1) {
445                 splitpercents += llList2Integer(tmp,1);
446                 splitkeys += llList2Key(tmp,0);
447                 if (splitline == 0) {
448                     llRequestPermissions(llGetOwner(), PERMISSION_DEBIT);
449                 }
450                 splitline++;
451                 splitrequestid = llGetNotecardLine("~SPLIT",splitline);                
452             }
453         } else if ( (queryid == configrequestid) && (data != EOF) ) {
454             process_configuration_items(data);
455         }
456     }
457 }
458