A sales desk: the engineer turned salesdroid, the shark, or the CEO

From customer level 2, one person runs sales at a time, next to the NOC intern:
- The engineer turned salesdroid ($9k/mo) books you into every network operators' meeting 30 days
  ahead at the usual ticket price, brings 40% more offers (half as many again while a meeting's glow
  lasts) but never the huge deals, and their customers leave less often at renewal (half as often
  for the nerdy ones: HFT, ISPs, universities, L2). Haggles badly.
- The shark ($15k/mo) brings bigger sizes at 25% more, takes a month of each deal as commission,
  oversells half of them with a requirement the network does not meet yet, never brings technical
  customers, makes selective peering desks want 25% more traffic, wins most haggles, and their
  customers leave 50% more often.
- The CEO (free) signs the biggest internet customer the network can take on the golf course every
  50-80 days at 30% off, often with a promise nobody checked, signs about a third of the offers you
  decline anyway, and has opinions. He cannot be fired: a board meeting brings a VP of Sales a month
  later.
Customers remember who signed them (by), which the renewals read. Every roll is a hash of the day
or the deal, so games without a salesperson keep their random stream.

The differential fuzz also leaves out buttons for actions main does not have yet.
This commit is contained in:
Frederic Jung 2026-11-05 09:32:24 +01:00
parent b9860edc77
commit 27c4977412
No known key found for this signature in database
25 changed files with 470 additions and 14 deletions

View file

@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
- A sales desk joins the NOC intern: from customer level 2 you can put one person in charge of sales, and each brings deals their own way. The engineer turned salesdroid books you into every network operators' meeting (you pay the ticket), brings more small and mid deals but never the huge ones, and only sells what your network can do, so their customers stay longer; they haggle badly. The shark lands bigger deals at a quarter more and takes a month of each as commission, but oversells promises your network does not keep yet, ignores technical customers and meetings, and makes peering desks want more traffic from you. Or the CEO runs sales himself, for free: a huge discounted deal on the golf course every couple of months, the odd offer you declined signed anyway, opinions, and no way to fire him short of asking the board for a VP of Sales.
- Customers now sign contracts, and when one ends they renew, grow, haggle or leave, not always because of you (#178). Most renew at today's bandwidth price, which falls about 10% a year but rises when hardware is short; happy customers often take a bigger size, and some ask for a discount you can match, meet halfway or turn down in Deals. Others are acquired, go bust, build their own network, move away (they stay if you have a POP where they go), split their traffic with a second provider or end their project, and now and then one leaves for a stranger reason. Nothing changes during a customer's first contract, renewals in an old save are spread over the next year, your happiest long-time customers send you referrals, and the NOC dashboard shows customers won and lost each month and why.
- Sweden gets Gothenburg, Malmö and Haparanda (#206). Gothenburg sits between Oslo and Copenhagen with its own exchange, Malmö faces Copenhagen across the Øresund, and Haparanda on the Finnish border is where the fibre crosses over land to Finland, with no exchange yet for you to found one. A Nordic fibre carrier sells transit along that route from Berlin to the border, and Swedish home networks reach the new cities.
- The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts.

View file

@ -31,7 +31,7 @@ hoisted across files, and top-level statements run in path order. Find code by n
| `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) |
| `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) |
| `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` |
| `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`) |
| `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`), the sales desk (`S.sales`, `salesDay()`, `salesShape()` on new offers) |
| `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering desk (requests answered by policy), peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank |
| `80-simulation/` | Dijkstra, RouteScript, where a DDoS flood goes (`ddosLoad()`/`ddosAfter()`, called by `compute()`), `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, the customer lifecycle (contracts, renewals, the bandwidth market, why customers leave), geography pricing and latency, second sites and service |
| `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) |

View file

@ -177,5 +177,6 @@
if (keep) UI.rkR = R;
return { a, b, c };
};
window.__fz = { direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen };
const acts = () => Object.keys(ACT);
window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sDigest, sParts, check, errs, modalOpen };
})();

View file

@ -98,7 +98,10 @@ function playGame(pages, seed, opts = {}) {
if (!div) compare('start');
// A screen's buttons on both pages; the same list or a divergence.
const screen = (w) => { const [a, b] = both('screen', w); same('buttons of ' + JSON.stringify(w), a, b); return a || []; };
// Buttons for actions main's page does not have (a new feature's) are left out: the driver only presses what both have.
let baseActs = null;
const screen = (w) => { const [a, b0] = both('screen', w); baseActs = baseActs || new Set(base.call('acts'));
const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act)) : b0; same('buttons of ' + JSON.stringify(w), a, b); return a || []; };
const press = (b, where) => { acts[b.act] = (acts[b.act] || 0) + 1; const [e1, e2] = both('press', b); same('press ' + where, e1, e2); note(where + ' ' + b.act + JSON.stringify(b.args) + (e1 ? ' !' + e1 : '')); };
// Answer whatever window opened, a few levels deep, then close it.
const modal = (bias) => {

View file

@ -3904,6 +3904,42 @@
"rules.rules_are_locked_for_this_network":"{rules}: Die Regeln sind für dieses Netz festgelegt.",
"rules.the_real_thing_your_pager_has":"Das echte Spiel. Dein Pager hat Meinungen.",
"rules.your_pager_never_sleeps":"Dein Pager schläft nie.",
"sales.ask_vp":"Beim Vorstand einen VP Sales beantragen · {cost}",
"sales.at_desk":"{name} leitet den Vertrieb",
"sales.ceo_d":"Kostenlos, und überzeugt davon. Alle paar Monate unterschreibt er auf dem Golfplatz einen Riesendeal mit 30 % Rabatt, oft mit einem Versprechen, das niemand geprüft hat, und ab und zu ein Angebot, das du abgelehnt hast. Hat Meinungen. Kann nicht entlassen werden.",
"sales.ceo_golf":"Der CEO hat {name} auf dem Golfplatz unterschrieben: {bw} in {city} für {price}/Monat, 30 % unter Liste.",
"sales.ceo_n":"Der CEO, der besser verkauft als alle",
"sales.ceo_override":"Du hast {name} abgelehnt, aber der CEO hatte schon eingeschlagen. Jetzt sind sie Kunde.",
"sales.ceo_promised":"Er hat auch versprochen: {req}.",
"sales.ceo_s":"der CEO",
"sales.ceo_say_airport":"Gerade gelandet. Nichts unterschrieben, aber beim Lounge-WLAN hatte ich ein sehr gutes Gefühl.",
"sales.ceo_say_blockchain":"Haben wir mal überlegt, die Routingtabelle auf eine Blockchain zu legen?",
"sales.ceo_say_golf":"Die besten Deals passieren am neunten Loch. Das NOC sollte mehr Golf spielen.",
"sales.ceo_say_mbps":"Warum verkaufen wir Gigabit? Megabit klingt nach mehr.",
"sales.ceo_say_napkin":"Ich habe den nächsten Deal auf einer Serviette kalkuliert. Die Technik kann die Details klären.",
"sales.ceo_say_synergy":"Wir verkaufen keine Bandbreite, wir verkaufen Synergie. Schreibt das auf die Website.",
"sales.ceo_says":"Der CEO: „{say}“",
"sales.ceo_took_over":"{name} hat den Vertrieb persönlich übernommen. Er ist sicher, dass er besser verkauft als alle.",
"sales.commission":"{name} hat unterschrieben. Provision für den Hai: {cost}.",
"sales.desk":"Vertrieb",
"sales.eng_booked":"{name} hat dich für {conf} in {city} angemeldet ({cost}). Das Badge liegt schon bereit.",
"sales.eng_d":"War Netzwerkingenieur und hat jetzt ein Badge von jeder NOG. Meldet dich zu jeder an (das Ticket zahlst du), bringt viele kleine und mittlere Deals, aber nie die richtig großen, und verkauft nur, was das Netz kann, also bleiben die Kunden. Die Nerds lieben Dave. Verhandelt schlecht.",
"sales.eng_n":"Der Ingenieur, jetzt Salesdroide",
"sales.eng_s":"Dave",
"sales.fired":"{name} hat den Schreibtisch geräumt. Der Vertrieb ist frei.",
"sales.hire_sales":"Vertrieb einstellen",
"sales.hired":"{name} ist jetzt im Vertrieb. Rechne mit Deals in diesem Stil.",
"sales.intro":"Eine Person leitet den Vertrieb. Jede holt Deals auf ihre Art, und die Kunden, die sie abschließt, erinnern sich daran, wenn ihr Vertrag ausläuft.",
"sales.let_ceo":"Den CEO machen lassen",
"sales.locked":"Der Vertrieb öffnet ab Kundenstufe {lv}.",
"sales.one_at_a_time":"Immer nur eine Person: Lass sie gehen, um jemand anderen einzustellen.",
"sales.pitch":"Eine Person im Vertrieb holt Deals auf ihre eigene Art. Such sie aus.",
"sales.shark_d":"Holt die größten Deals zu einem Viertel mehr und kassiert einen Monat jedes Deals als Provision. Verkauft zu viel: Die Hälfte kommt mit einem Versprechen, das dein Netz noch nicht hält, und diese Kunden gehen früher. Ignoriert die Nerds: keine technischen Kunden, keine Meetings, und Peering-Desks wollen ein Viertel mehr Verkehr von dir. Gewinnt die meisten Verhandlungen.",
"sales.shark_n":"Der Hai",
"sales.shark_s":"Chad",
"sales.vp_arrived":"Der VP Sales hat angefangen, und der CEO ist zurück bei der Strategie. Der Vertrieb ist frei: Stell jemanden ein.",
"sales.vp_asked":"Der Vorstand hat zugestimmt, nach dem Mittagessen. Ein VP Sales fängt in {n} Tagen an; bis dahin verkauft der CEO weiter.",
"sales.vp_coming":"Ein VP Sales übernimmt in {n} Tagen.",
"save.cash_in_the_bank":"{cash} auf der Bank",
"save.import_failed_err":"<b>Import fehlgeschlagen.</b><br>{err}",
"save.load_name":"{name} laden?",

View file

@ -3902,6 +3902,42 @@
"rules.rules_are_locked_for_this_network":"{rules}: las reglas están fijadas para esta red.",
"rules.the_real_thing_your_pager_has":"El juego de verdad. Tu busca tiene opiniones.",
"rules.your_pager_never_sleeps":"Tu busca no duerme nunca.",
"sales.ask_vp":"Pedir al consejo un VP de Ventas · {cost}",
"sales.at_desk":"{name} lleva las ventas",
"sales.ceo_d":"Gratis, y convencido. Cada par de meses firma un trato enorme en el campo de golf con un 30 % de descuento, a menudo con una promesa que nadie comprobó, y de vez en cuando firma una oferta que tú rechazaste. Tiene opiniones. No se le puede despedir.",
"sales.ceo_golf":"El CEO firmó a {name} en el campo de golf: {bw} en {city} por {price}/mes, un 30 % por debajo de tarifa.",
"sales.ceo_n":"El CEO, que vende mejor que nadie",
"sales.ceo_override":"Rechazaste a {name}, pero el CEO ya había dado la mano. Ahora son clientes.",
"sales.ceo_promised":"También prometió: {req}.",
"sales.ceo_s":"el CEO",
"sales.ceo_say_airport":"Acabo de aterrizar. No he firmado nada, pero el Wi-Fi de la sala VIP me dio muy buena espina.",
"sales.ceo_say_blockchain":"¿Hemos pensado en poner la tabla de rutas en una blockchain?",
"sales.ceo_say_golf":"Los mejores tratos se cierran en el hoyo nueve. El NOC debería jugar más al golf.",
"sales.ceo_say_mbps":"¿Por qué vendemos gigabits? Megabits suena a más.",
"sales.ceo_say_napkin":"He calculado el próximo trato en una servilleta. Ingeniería puede resolver los detalles.",
"sales.ceo_say_synergy":"No vendemos ancho de banda, vendemos sinergia. Ponedlo en la web.",
"sales.ceo_says":"El CEO: «{say}»",
"sales.ceo_took_over":"{name} se ha hecho cargo de las ventas en persona. Está seguro de que vende mejor que nadie.",
"sales.commission":"{name} firmó. Comisión para el tiburón: {cost}.",
"sales.desk":"Ventas",
"sales.eng_booked":"{name} te apuntó a {conf} en {city} ({cost}). Ya tiene la acreditación.",
"sales.eng_d":"Era ingeniero de redes y ahora tiene la acreditación de cada NOG. Te apunta a todas (la entrada la pagas tú), trae muchos tratos pequeños y medianos pero nunca los grandes de verdad, y solo vende lo que la red puede hacer, así que los clientes se quedan. Los nerds adoran a Dave. Negocia fatal.",
"sales.eng_n":"El ingeniero convertido en vendedroide",
"sales.eng_s":"Dave",
"sales.fired":"{name} ha vaciado su mesa. Ventas está libre.",
"sales.hire_sales":"Contratar ventas",
"sales.hired":"{name} se unió a ventas. Espera tratos a su estilo.",
"sales.intro":"Una persona lleva las ventas. Cada una trae tratos a su manera, y los clientes que firma lo recuerdan cuando les toca renovar.",
"sales.let_ceo":"Dejar que lo lleve el CEO",
"sales.locked":"Ventas se abre en el nivel de clientes {lv}.",
"sales.one_at_a_time":"Solo una a la vez: despídela para contratar a otra.",
"sales.pitch":"Una persona de ventas trae tratos a su manera. Elige quién.",
"sales.shark_d":"Consigue los tratos más grandes a un cuarto más, y se lleva un mes de cada trato de comisión. Vende de más: la mitad llega con una promesa que tu red aún no cumple, y esos clientes se van antes. Ignora a los nerds: nada de clientes técnicos ni de reuniones, y los equipos de peering te piden un cuarto más de tráfico. Gana casi todas las negociaciones.",
"sales.shark_n":"El tiburón",
"sales.shark_s":"Chad",
"sales.vp_arrived":"El VP de Ventas ya empezó, y el CEO ha vuelto a la estrategia. Ventas está libre: contrata a alguien.",
"sales.vp_asked":"El consejo aceptó, después de comer. Un VP de Ventas empieza en {n} días; hasta entonces el CEO sigue vendiendo.",
"sales.vp_coming":"Un VP de Ventas toma el relevo en {n} días.",
"save.cash_in_the_bank":"{cash} en el banco",
"save.import_failed_err":"<b>Falló la importación.</b><br>{err}",
"save.load_name":"¿Cargar {name}?",

View file

@ -3902,6 +3902,42 @@
"rules.rules_are_locked_for_this_network":"{rules} : les règles sont verrouillées pour ce réseau.",
"rules.the_real_thing_your_pager_has":"Le vrai jeu. Ton bipeur a des opinions.",
"rules.your_pager_never_sleeps":"Ton bipeur ne dort jamais.",
"sales.ask_vp":"Demander un VP Ventes au conseil · {cost}",
"sales.at_desk":"{name} gère les ventes",
"sales.ceo_d":"Gratuit, et convaincu. Tous les deux mois, il signe un énorme contrat sur le terrain de golf à -30 %, souvent avec une promesse que personne n'a vérifiée, et de temps en temps une offre que vous aviez refusée. A des avis sur tout. Impossible à licencier.",
"sales.ceo_golf":"Le PDG a signé {name} sur le terrain de golf : {bw} à {city} pour {price}/mois, 30 % sous le tarif.",
"sales.ceo_n":"Le PDG, qui vend mieux que personne",
"sales.ceo_override":"Vous avez refusé {name}, mais le PDG avait déjà topé. C'est maintenant un client.",
"sales.ceo_promised":"Il a aussi promis : {req}.",
"sales.ceo_s":"le PDG",
"sales.ceo_say_airport":"Je viens d'atterrir. Rien signé, mais j'ai eu un très bon pressentiment avec le Wi-Fi du salon.",
"sales.ceo_say_blockchain":"Avons-nous pensé à mettre la table de routage sur une blockchain ?",
"sales.ceo_say_golf":"Les meilleurs contrats se signent au neuvième trou. Le NOC devrait jouer plus au golf.",
"sales.ceo_say_mbps":"Pourquoi vendre des gigabits ? Des mégabits, ça fait plus.",
"sales.ceo_say_napkin":"J'ai chiffré le prochain contrat sur une serviette. L'ingénierie réglera les détails.",
"sales.ceo_say_synergy":"Nous ne vendons pas de la bande passante, nous vendons de la synergie. Mettez ça sur le site.",
"sales.ceo_says":"Le PDG : « {say} »",
"sales.ceo_took_over":"{name} a pris les ventes en main personnellement. Il est sûr de vendre mieux que personne.",
"sales.commission":"{name} a signé. Commission du requin : {cost}.",
"sales.desk":"Service commercial",
"sales.eng_booked":"{name} vous a inscrit à {conf} à {city} ({cost}). Le badge est déjà prêt.",
"sales.eng_d":"Ancien ingénieur réseau, il a un badge de chaque NOG. Il vous inscrit à toutes (vous payez le billet), apporte beaucoup de petits et moyens contrats mais jamais les très gros, et ne vend que ce que le réseau sait faire : les clients restent. Les geeks adorent Dave. Il négocie mal.",
"sales.eng_n":"L'ingénieur devenu commercial-droïde",
"sales.eng_s":"Dave",
"sales.fired":"{name} a vidé son bureau. Le service commercial est libre.",
"sales.hire_sales":"Recruter un commercial",
"sales.hired":"{name} rejoint le service commercial. Attendez-vous à des contrats dans son style.",
"sales.intro":"Une seule personne gère les ventes. Chacune apporte des contrats à sa façon, et les clients qu'elle signe s'en souviennent à l'échéance.",
"sales.let_ceo":"Laisser le PDG s'en charger",
"sales.locked":"Le service commercial ouvre au niveau clients {lv}.",
"sales.one_at_a_time":"Une seule à la fois : laissez-la partir pour en recruter une autre.",
"sales.pitch":"Un commercial apporte des contrats à sa façon. Choisissez qui.",
"sales.shark_d":"Décroche les plus gros contrats un quart plus cher, et prend un mois de chaque contrat en commission. Survend : la moitié arrive avec une promesse que votre réseau ne tient pas encore, et ces clients partent plus tôt. Ignore les geeks : pas de clients techniques, pas de NOG, et les équipes peering vous demandent un quart de trafic en plus. Gagne la plupart des négociations.",
"sales.shark_n":"Le requin",
"sales.shark_s":"Chad",
"sales.vp_arrived":"Le VP Ventes a pris son poste, et le PDG est retourné à la stratégie. Le service commercial est libre : recrutez quelqu'un.",
"sales.vp_asked":"Le conseil a dit oui, après le déjeuner. Un VP Ventes arrive dans {n} jours ; d'ici là, le PDG continue de vendre.",
"sales.vp_coming":"Un VP Ventes prend le relais dans {n} jours.",
"save.cash_in_the_bank":"{cash} en banque",
"save.import_failed_err":"<b>Échec de l’import.</b><br>{err}",
"save.load_name":"Charger {name} ?",

View file

@ -3902,6 +3902,42 @@
"rules.rules_are_locked_for_this_network":"{rules}: le regole sono bloccate per questa rete.",
"rules.the_real_thing_your_pager_has":"Il gioco vero. Il tuo cercapersone ha delle opinioni.",
"rules.your_pager_never_sleeps":"Il tuo cercapersone non dorme mai.",
"sales.ask_vp":"Chiedi al consiglio un VP vendite · {cost}",
"sales.at_desk":"{name} gestisce le vendite",
"sales.ceo_d":"Gratis, e convinto. Ogni paio di mesi firma un contratto enorme sul campo da golf con il 30% di sconto, spesso con una promessa che nessuno ha controllato, e ogni tanto firma un'offerta che avevi rifiutato. Ha opinioni. Non si può licenziare.",
"sales.ceo_golf":"Il CEO ha firmato {name} sul campo da golf: {bw} a {city} per {price}/mese, il 30% sotto listino.",
"sales.ceo_n":"Il CEO, che vende meglio di chiunque",
"sales.ceo_override":"Hai rifiutato {name}, ma il CEO aveva già stretto la mano. Ora sono clienti.",
"sales.ceo_promised":"Ha anche promesso: {req}.",
"sales.ceo_s":"il CEO",
"sales.ceo_say_airport":"Appena atterrato. Non ho firmato niente, ma il Wi-Fi della lounge mi ha dato ottime sensazioni.",
"sales.ceo_say_blockchain":"Abbiamo pensato di mettere la tabella di routing su una blockchain?",
"sales.ceo_say_golf":"I contratti migliori si chiudono alla nona buca. Il NOC dovrebbe giocare più a golf.",
"sales.ceo_say_mbps":"Perché vendiamo gigabit? I megabit sembrano di più.",
"sales.ceo_say_napkin":"Ho fatto il prezzo del prossimo contratto su un tovagliolo. L'ingegneria sistemerà i dettagli.",
"sales.ceo_say_synergy":"Non vendiamo banda, vendiamo sinergia. Mettetelo sul sito.",
"sales.ceo_says":"Il CEO: «{say}»",
"sales.ceo_took_over":"{name} ha preso in mano le vendite di persona. È sicuro di vendere meglio di chiunque.",
"sales.commission":"{name} ha firmato. Provvigione per lo squalo: {cost}.",
"sales.desk":"Ufficio vendite",
"sales.eng_booked":"{name} ti ha iscritto a {conf} a {city} ({cost}). Ha già il badge.",
"sales.eng_d":"Era un ingegnere di rete e ora ha il badge di ogni NOG. Ti iscrive a tutti (il biglietto lo paghi tu), porta tanti contratti piccoli e medi ma mai quelli davvero grandi, e vende solo ciò che la rete sa fare, così i clienti restano. I nerd adorano Dave. Tratta male.",
"sales.eng_n":"L'ingegnere diventato venditore-droide",
"sales.eng_s":"Dave",
"sales.fired":"{name} ha svuotato la scrivania. L'ufficio vendite è libero.",
"sales.hire_sales":"Assumi un venditore",
"sales.hired":"{name} è entrato nelle vendite. Aspettati contratti nel suo stile.",
"sales.intro":"Una persona alla volta gestisce le vendite. Ognuna porta contratti a modo suo, e i clienti che firma se ne ricordano alla scadenza.",
"sales.let_ceo":"Lascia fare al CEO",
"sales.locked":"L'ufficio vendite apre al livello clienti {lv}.",
"sales.one_at_a_time":"Uno alla volta: lascialo andare per assumerne un altro.",
"sales.pitch":"Un venditore porta contratti a modo suo. Scegli chi.",
"sales.shark_d":"Porta i contratti più grandi a un quarto in più, e si prende un mese di ogni contratto come provvigione. Vende troppo: metà arriva con una promessa che la tua rete non mantiene ancora, e quei clienti se ne vanno prima. Ignora i nerd: niente clienti tecnici, niente incontri, e i peering desk ti chiedono un quarto di traffico in più. Vince quasi tutte le trattative.",
"sales.shark_n":"Lo squalo",
"sales.shark_s":"Chad",
"sales.vp_arrived":"Il VP vendite ha iniziato, e il CEO è tornato alla strategia. L'ufficio vendite è libero: assumi qualcuno.",
"sales.vp_asked":"Il consiglio ha detto sì, dopo pranzo. Un VP vendite inizia tra {n} giorni; fino ad allora il CEO continua a vendere.",
"sales.vp_coming":"Un VP vendite subentra tra {n} giorni.",
"save.cash_in_the_bank":"{cash} in cassa",
"save.import_failed_err":"<b>Importazione fallita.</b><br>{err}",
"save.load_name":"Caricare {name}?",

View file

@ -3902,6 +3902,42 @@
"rules.rules_are_locked_for_this_network":"{rules}: as regras estão travadas para esta rede.",
"rules.the_real_thing_your_pager_has":"O jogo de verdade. O seu pager tem opiniões.",
"rules.your_pager_never_sleeps":"O seu pager nunca dorme.",
"sales.ask_vp":"Pedir ao conselho um VP de Vendas · {cost}",
"sales.at_desk":"{name} cuida das vendas",
"sales.ceo_d":"De graça, e convicto. A cada dois meses fecha um contrato enorme no campo de golfe com 30% de desconto, muitas vezes com uma promessa que ninguém conferiu, e de vez em quando assina uma oferta que você recusou. Tem opiniões. Não pode ser demitido.",
"sales.ceo_golf":"O CEO fechou com {name} no campo de golfe: {bw} em {city} por {price}/mês, 30% abaixo da tabela.",
"sales.ceo_n":"O CEO, que vende melhor que ninguém",
"sales.ceo_override":"Você recusou {name}, mas o CEO já tinha apertado a mão. Agora são clientes.",
"sales.ceo_promised":"Ele também prometeu: {req}.",
"sales.ceo_s":"o CEO",
"sales.ceo_say_airport":"Acabei de pousar. Não assinei nada, mas tive um ótimo pressentimento com o Wi-Fi da sala VIP.",
"sales.ceo_say_blockchain":"Já pensamos em colocar a tabela de rotas numa blockchain?",
"sales.ceo_say_golf":"Os melhores negócios saem no nono buraco. O NOC devia jogar mais golfe.",
"sales.ceo_say_mbps":"Por que vendemos gigabits? Megabits parecem mais.",
"sales.ceo_say_napkin":"Fiz o preço do próximo contrato num guardanapo. A engenharia resolve os detalhes.",
"sales.ceo_say_synergy":"Não vendemos banda, vendemos sinergia. Coloquem isso no site.",
"sales.ceo_says":"O CEO: “{say}”",
"sales.ceo_took_over":"{name} assumiu as vendas pessoalmente. Tem certeza de que vende melhor que ninguém.",
"sales.commission":"{name} assinou. Comissão do tubarão: {cost}.",
"sales.desk":"Vendas",
"sales.eng_booked":"{name} inscreveu você no {conf} em {city} ({cost}). O crachá já está pronto.",
"sales.eng_d":"Era engenheiro de redes e agora tem o crachá de cada NOG. Inscreve você em todas (o ingresso é por sua conta), traz muitos negócios pequenos e médios, mas nunca os realmente grandes, e só vende o que a rede consegue entregar, então os clientes ficam. Os nerds adoram o Dave. Negocia mal.",
"sales.eng_n":"O engenheiro que virou vendedroide",
"sales.eng_s":"Dave",
"sales.fired":"{name} esvaziou a mesa. Vendas está livre.",
"sales.hire_sales":"Contratar vendas",
"sales.hired":"{name} entrou em vendas. Espere negócios no estilo dele.",
"sales.intro":"Uma pessoa por vez cuida das vendas. Cada uma traz negócios do seu jeito, e os clientes que ela fecha lembram disso quando o contrato vence.",
"sales.let_ceo":"Deixar o CEO cuidar",
"sales.locked":"Vendas abre no nível de clientes {lv}.",
"sales.one_at_a_time":"Uma por vez: dispense para contratar outra.",
"sales.pitch":"Uma pessoa de vendas traz negócios do jeito dela. Escolha quem.",
"sales.shark_d":"Fecha os maiores negócios por um quarto a mais, e leva um mês de cada contrato de comissão. Vende demais: metade chega com uma promessa que sua rede ainda não cumpre, e esses clientes saem mais cedo. Ignora os nerds: nada de clientes técnicos nem de encontros, e as equipes de peering pedem um quarto a mais de tráfego. Ganha quase todas as negociações.",
"sales.shark_n":"O tubarão",
"sales.shark_s":"Chad",
"sales.vp_arrived":"O VP de Vendas começou, e o CEO voltou para a estratégia. Vendas está livre: contrate alguém.",
"sales.vp_asked":"O conselho aprovou, depois do almoço. Um VP de Vendas começa em {n} dias; até lá o CEO continua vendendo.",
"sales.vp_coming":"Um VP de Vendas assume em {n} dias.",
"save.cash_in_the_bank":"{cash} no banco",
"save.import_failed_err":"<b>Falha na importação.</b><br>{err}",
"save.load_name":"Carregar {name}?",

View file

@ -27,6 +27,7 @@ const API_DOMAINS={
metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']},
egress:{table:'PREF',kind:'key'},
routeMode:{table:'RT',kind:'key'},
salesPersona:{table:'SALES',kind:'key'},
site:{kind:'enum',values:['a','b','ab']},
step:{kind:'enum',values:[1,-1]},
connKind:{kind:'enum',values:['t','p','ix','c','nni']},

View file

@ -218,6 +218,12 @@ const API_CMD={
doc:'Sign a pending offer. Rejected without a POP in every city it needs, without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'},
decline:{args:[['id','entityId']],
doc:'Throw an offer away.'},
salesHire:{args:[['id','salesPersona']],
doc:'Put one salesperson at the sales desk: eng (engineer turned salesdroid: books every NOG at the usual ticket price, more small and mid deals, never the huge ones, customers stay longer), shark (bigger deals at higher prices plus a month of commission, oversells promises, no nerdy customers, peering desks want more traffic) or ceo (free, signs huge discounted deals on the golf course, sometimes signs what you declined, cannot be fired). One at a time; from customer level 2.'},
salesFire:{args:[],confirm:'double',
doc:'Let the salesperson go (not the CEO: ask the board for a VP of Sales instead).'},
salesVp:{args:[],
doc:'With the CEO running sales: pay for a board meeting that brings a VP of Sales, who frees the desk a month later.'},
renewMatch:{args:[['id','entityId']],watch:['biz.#id'],
doc:'Answer a renewal haggle (a customer with hag): renew at the price they asked. Unanswered, this happens on its own when the term ends.'},
renewMeet:{args:[['id','entityId']],watch:['biz.#id'],
@ -466,6 +472,7 @@ const API_VIEW={
keys:{args:[],doc:'Open the list of keyboard shortcuts (the ? key).'},
routingOpen:{args:[],doc:'Open the Routing & DDoS window: backbone, Auto-TE and DDoS settings (the button at the top of the NOC tab).'},
opsOpen:{args:[],doc:'Open the Ops sheet: the NOC intern\'s mood, weekly shift report and standing orders.'},
salesOpen:{args:[],doc:'Open the sales desk sheet: the three kinds of salesperson, who is at the desk and what they cost.'},
opsCity:{args:[['v','cityId',false]],doc:'Show one POP\'s standing-order exceptions in the Ops sheet.'},
utilities:{args:[['city','cityId',false]],doc:'Open the utilities sheet: route servers, the redundancy kit, caches and bulk peering, for one city or the whole network.'},
pniAllOpen:{args:[['net','pniAllNet']],doc:'Open the bulk PNI order sheet for one network (or every network with null).'},

View file

@ -34,6 +34,7 @@ const API_STATE_DOC={
nni:{type:'array',doc:'Fabric ports: city, provider, tier.'},
biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates (te: the day the term ends, mk: the bandwidth market it was priced in, hag: an open renewal haggle {rate, until}).'},
offers:{type:'array',doc:'Pending customer offers, each expiring on a day (mk: the bandwidth market they were priced in; refN: the customer who referred them).'},
sales:{type:'map',doc:'The sales desk: p (eng, shark, ceo or null), hired (day), vp (the day a VP of Sales takes over from the CEO), golf and say (the CEO\'s next golf deal and opinion). Offers and customers carry by: who brought or signed them.'},
cl:{type:'map',doc:'Customer lifecycle (#178): odd (the day of the last unusual departure) and mo, one entry a month of customers won, renewed, grown, haggling and lost by reason.'},
done:{type:'map',doc:'Goals landed, by goal id → day.'},
ach:{type:'map',doc:'Badges earned this game, by badge id → day.'},

View file

@ -26,7 +26,7 @@ function apiJson(v){
carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders
each recipe's script, because the source is a function and some read the live network. The
recipes' relevance score is not exposed: judging which one fits is the agent's job. */
const API_TABLES={CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG};
const API_TABLES={SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG};
const API_MADE={
BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id];
return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}),

View file

@ -0,0 +1,75 @@
/* ---------- The sales desk: one salesperson, three kinds you meet in this industry ----------
Next to the NOC intern, you can put one person in charge of sales. Each brings deals in their own way and leaves
their mark on the customers they sign (b.by), which the contracts (75-customer-lifecycle.js) remember at renewal.
- The engineer turned salesdroid goes to every network operators' meeting (you pay the ticket), brings plenty of
small and mid deals and never the huge ones, and only sells what the network can do: their customers stay longer,
the nerdy ones most of all. They haggle badly.
- The shark brings the biggest deals at a higher price and takes a commission, but oversells: many come with a
promise your network does not keep yet. Ignores the nerds: no technical customers, no meetings, and peering desks
want more traffic from you. Wins most haggles.
- The CEO runs sales himself, for free: now and then a huge deal signed on the golf course at a discount, with a
promise nobody checked, the odd declined offer signed anyway, and opinions. He cannot be fired; the board can
be asked for a VP of Sales instead.
Every roll is a hash of the day and the deal, so a game without a salesperson keeps its random stream. */
const SALES={
eng:{i:'🤓',n:N_('sales.eng_n'),s:N_('sales.eng_s'),d:N_('sales.eng_d'),mo:9000},
shark:{i:'🦈',n:N_('sales.shark_n'),s:N_('sales.shark_s'),d:N_('sales.shark_d'),mo:15000},
ceo:{i:'👔',n:N_('sales.ceo_n'),s:N_('sales.ceo_s'),d:N_('sales.ceo_d'),mo:0},
};
const SALES_LV=2,SALES_VP=50000,SALES_VP_DAYS=30;
// The ones the engineer never lands, and the nerds the shark never calls back.
const salesBig=t=>{const T=BIZ_T[t];return !!T&&(!!T.mega||(T.lv||1)>=4);};
const SALES_NERDS=['hft','edu','isp','l2vpn','bulk','provedor','fabl2','wwave','dfpair'];
const SALES_SAY=[N_('sales.ceo_say_synergy'),N_('sales.ceo_say_golf'),N_('sales.ceo_say_blockchain'),N_('sales.ceo_say_napkin'),N_('sales.ceo_say_mbps'),N_('sales.ceo_say_airport')];
const slP=()=>S&&S.sales&&own(SALES,S.sales.p)?S.sales.p:null;
const slName=(long)=>{const p=slP();return p?tr(long?SALES[p].n:SALES[p].s):'';};
// The short name at the start of a sentence: Dave, Chad, The CEO.
const slCap=()=>{const t=slName();return t?t[0].toUpperCase()+t.slice(1):'';};
const slR=q=>(hstr(((S&&S.asn)||0)+'|sales|'+q)%100000)/100000;
const salesMo=()=>{const p=slP();return p?SALES[p].mo:0;};
const salesCanHire=()=>lvl()>=SALES_LV;
// How often offers come in: the engineer brings more, half as many again while a meeting's glow lasts.
function salesSpawn(){const p=slP();if(p==='eng')return 1.4*(S.conf&&S.conf.until>S.day?1.5:1);if(p==='shark')return 1.2;return 1;}
// What the salesperson does to the offers that just came in (from index n0): who brought them, which they drop,
// and how the shark dresses them up.
function salesShape(n0){const p=slP();if(!p)return;for(let i=S.offers.length-1;i>=n0;i--){const o=S.offers[i],T=BIZ_T[o.type];if(!T||o.ref)continue;
if(p==='eng'&&salesBig(o.type)){S.offers.splice(i,1);continue;}
if(p==='shark'&&SALES_NERDS.includes(o.type)){S.offers.splice(i,1);continue;}
o.by=p;
if(p==='shark'&&!T.event&&!T.cap){const up=(T.opts||[]).find(x=>x>o.bw);if(up&&!T.fiber)o.bw=up;o.rate=Math.round(o.rate*1.25);
if(slR('over|'+o.id)<0.5){const k=salesPromise(o);if(k)o.reqs=(o.reqs||[]).concat(k);}}}}
// A promise nobody checked: a requirement this deal can have, that the network does not meet today.
function salesPromise(o){const T=BIZ_T[o.type],pool=Object.keys(REQS).filter(k=>!(o.reqs||[]).includes(k)&&!REQS[k].only&&(!REQS[k].l2||T.l2)&&(!REQS[k].ip||!T.l2)&&reqCan(k,o)).sort();
const no=pool.filter(k=>{try{return !REQS[k].ok(o);}catch(e){return false;}});return no.length?no[Math.floor(slR('promise|'+o.id)*no.length)]:null;}
// Their mark at renewal: how much likelier the customers they signed are to leave.
function salesLeaveMul(b){if(b.by==='eng')return SALES_NERDS.includes(b.type)?0.5:0.75;if(b.by==='shark')return 1.5;if(b.by==='ceo')return 1.25;return 1;}
// Haggles with whoever is at the desk now: how deep the discount they ask, and how often meeting halfway works.
const salesAsk=()=>slP()==='eng'?0.72:0.8;
const salesMeet=()=>({shark:0.9,eng:0.5,ceo:0.55})[slP()]||0.65;
// Peering desks notice who you send to meetings: with the shark, selective networks want a quarter more traffic.
const salesPeerMul=()=>slP()==='shark'?1.25:1;
/* A day at the sales desk: the engineer books the next meeting (30 days ahead, the same day the invitation comes),
the CEO plays golf and has opinions, and a VP of Sales takes over from him when the board says so. */
function salesDay(d){const L=S.sales;if(!L)return;
if(L.vp&&d>=L.vp){L.p=null;L.vp=null;toast(tr('sales.vp_arrived'),'good',[{l:tr('sales.desk'),act:'salesOpen',args:{}}]);return;}
const p=slP();if(!p)return;
if(p==='eng')for(const cf of upcomingConfs(30)){if(cf.cap||cf.day-d!==30||(S.confReg||{})[cf.key])continue;
if(S.cash>=CONF_COST){S.cash-=CONF_COST;(S.confReg=S.confReg||{})[cf.key]=true;toast(tr('sales.eng_booked',{name:esc(slCap()),conf:esc(cf.n),city:esc(CITY[cf.c].name),cost:fmt$(CONF_COST)}),'');}}
if(p==='ceo'){if(!(L.golf>=d))L.golf=d+50+Math.floor(slR('golf|'+d)*30);else if(d===L.golf){salesGolf(d);L.golf=d+50+Math.floor(slR('golf|'+d)*30);}
if(!(L.say>=d))L.say=d+20+Math.floor(slR('say|'+d)*15);else if(d===L.say){toast(tr('sales.ceo_says',{say:tr(SALES_SAY[Math.floor(slR('sayl|'+d)*SALES_SAY.length)])}),'');L.say=d+20+Math.floor(slR('say|'+d)*15);}}}
// The golf course: the biggest internet customer this network can take, in its biggest city, at 30% off, signed on the spot.
const SALES_GOLF=['metav','cgame','gpu','stream','isp','edu','host','dia'];
function salesGolf(d){const mine=Object.keys(S.pops).filter(c=>popUp(c)&&bizCity(c));if(!mine.length)return;
const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl());if(!t)return;const T=BIZ_T[t],city=mine.sort((a,b)=>CITY[b].P-CITY[a].P||(a<b?-1:1))[0];
const list=(T.names||BIZ_N).filter(n=>!S.usedNames.includes(n));const name=list.length?list[Math.floor(slR('golfn|'+d)*list.length)]:(T.names||BIZ_N)[0];useName(name);
const o={id:uid(),city,city2:null,name,type:t,bw:T.opts[T.opts.length-1],rate:Math.round((CITY[city].au?T.rate*AU_ARPU:T.rate)*mkt()*0.7),reqs:[],exp:d+40};
const k=salesPromise(o);if(k)o.reqs.push(k);const b=offerCustomer(o);b.by='ceo';b.mk=mkt();S.biz.push(clSign(b));
toast(tr('sales.ceo_golf',{name:esc(name),city:esc(CITY[city].name),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)})+(k?' '+tr('sales.ceo_promised',{req:esc(typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l)}):''),'goal',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);sfx('coin');}
// Declining an offer the CEO likes: about one in three, he already shook hands on it.
function salesOverride(o){if(slP()!=='ceo'||!o||!bHas(o)||BIZ_T[o.type].event||slR('veto|'+o.id)>=0.33)return false;
const b=offerCustomer(o);if(o.mk)b.mk=o.mk;b.by='ceo';S.offers=S.offers.filter(x=>x!==o);S.biz.push(clSign(b));toast(tr('sales.ceo_override',{name:esc(o.name)}),'');return true;}
// Saves: who is at the desk, the VP on the way, the CEO's calendar; who brought each offer and signed each customer.
function salesFix(s){const L=s.sales&&typeof s.sales==='object'&&!Array.isArray(s.sales)?s.sales:{},n=v=>Number.isInteger(v)&&v>=0&&v<1e7?v:null;
s.sales={p:own(SALES,L.p)?L.p:null,hired:n(L.hired)||0,vp:L.p==='ceo'?n(L.vp):null,golf:n(L.golf),say:n(L.say)};
for(const x of [...s.biz,...s.offers])if(x.by!==undefined&&!own(SALES,x.by))delete x.by;}

View file

@ -16,7 +16,7 @@ function peerOk(id,via,city){
if(via==='ix'&&city&&isRemote(city)&&noRemote(id))return {ok:false,remote:true,why:REMOTE_WHY[hstr(id)%REMOTE_WHY.length]};
if(n.pol==='open')return {ok:true};
// In the Cogentle Spat, Goggle's peering desk wants eight times the usual traffic first, so cheap Cogentle-only transit really costs you Goggle (playtest).
if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id)*(id==='ggl'&&scnRule('spat')?8:1));return dem>=need?{ok:true}:{ok:false,why:tr('sold_out.wants_need_gbps_of_traffic_from',{need,dem:dem.toFixed(1)})};}
if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id)*salesPeerMul()*(id==='ggl'&&scnRule('spat')?8:1));return dem>=need?{ok:true}:{ok:false,why:tr('sold_out.wants_need_gbps_of_traffic_from',{need,dem:dem.toFixed(1)})};}
if(n.pol==='paid'&&paidFree(n))return via==='pni'?{ok:true,free:true}:{ok:false,why:tr('sold_out.peers_with_you_for_free_now')};
if(n.pol==='paid')return via==='pni'?{ok:true,fee:n.paidFee}:{ok:false,why:n.perG?tr('sold_out.sender_pays_a_paid_pni_only',{fee:fmt$(n.paidFee),g:fmt$(n.perG)}):tr('sold_out.paid_peering_only_over_a_pni')};
if(n.type!=='t1'){if(via!=='pni')return {ok:false,why:tr('sold_out.only_peers_over_pnis_and_only')};const need=Math.round(60*confBoost(id));return dem>=need||isTier2()?{ok:true}:{ok:false,why:tr('sold_out.wants_you_to_be_a_tier',{need,dem:dem.toFixed(1)})};}

View file

@ -361,7 +361,7 @@ function computeMoney(R2){
C.pni=S.pni.reduce((a,p)=>a+pniMo(p,R2.usePni[p.id]||0),0);
C.caches=cachesMo();
C.loans=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.model==='transit'?Math.round((C.transit||0)*(l.cut||0.3)):l.pay)+loanFees(l),0);
C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+scrubMo()+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO+Object.values(S.pops).filter(p=>p.site2).length*SITE2_MO+(S.te?TE_MO:0)+(S.ops&&S.ops.intern?INTERN_MO:0);
C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+scrubMo()+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO+Object.values(S.pops).filter(p=>p.site2).length*SITE2_MO+(S.te?TE_MO:0)+(S.ops&&S.ops.intern?INTERN_MO:0)+salesMo();
V.eyeballs=0;V.business=0;V.ix=0;V.grant=grantOn(R2)?GRANT_MO:0;
C.wholesale=0;C.levy=0;const lev=scnRule('levy');for(const c in S.pops){const sf=sfOf(R2,c)*(R2.bbF[c]??1),v=R2.cityEye[c]*sf*EYE_RATE*arpuOf(c);V.eyeballs+=v;if(CITY[c].au){if(lev)C.levy+=v*AU_LEVY;else C.wholesale+=v*AU_WHOLESALE;}}
const ids=linkIds();for(const b of S.biz){if(capPend(b))continue;const sf=BIZ_T[b.type].fiber?(fiberOk(b,ids)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city)*(R2.tgtF[b.id]??1);V.business+=b.bw*b.rate*Math.min(1,sf/0.95);}

View file

@ -57,7 +57,7 @@ function sanitize(s){
const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;return b;};
{const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>clFix(s,unpackBiz(fixBiz(b),ids)));}s.offers=s.offers.filter(okBiz).map(fixBiz);
// Contracts (#178): the bandwidth market an offer was priced in, who referred it, and the month-by-month tally.
for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s);
for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s);salesFix(s);
// Sponsorships and capacity conferences (#168): registrations are true or 'sp', the glow and the pending deals are checked.
for(const k of Object.keys(s.confReg))s.confReg[k]=s.confReg[k]==='sp'?'sp':!!s.confReg[k];
if(s.conf){const c=s.conf;if(typeof c!=='object'||!own(REG,c.reg))s.conf=null;else s.conf={until:num(c.until,0),reg:c.reg,name:String(c.name||'').slice(0,40),sp:!!c.sp};}

View file

@ -79,10 +79,10 @@ function clDay(d){if(!S.cl)S.cl={odd:-1e9,mo:[]};const out={ren:0,grew:0,ok:[],l
if(b.hag){if(d>=b.hag.until){clRenew(b,b.hag.rate);clNote('ren');out.ren++;}continue;}
if(d<b.te-30)continue;
if(d<b.te){if(b.hr===b.te)continue;b.hr=b.te;const comp=clComp(b),cf=Math.min(1,comp/6);
if(open<CL_HAG_MAX&&comp>=2&&b.mood>=40&&clR(b,'hag')<(0.05+0.15*cf)*pat){const fair=clFair(b),ask=Math.round(fair*(0.8+0.12*clR(b,'ask')));
if(open<CL_HAG_MAX&&comp>=2&&b.mood>=40&&clR(b,'hag')<(0.05+0.15*cf)*pat){const fair=clFair(b),ask=Math.round(fair*(salesAsk()+0.12*clR(b,'ask')));
if(ask>0&&ask<b.rate){b.hag={rate:ask,until:b.te};open++;clNote('hag');out.hag.push(b);}}
continue;}
const cf=Math.min(1,clComp(b)/6),u=(100-b.mood)/100,leave=(0.04+0.08*cf+0.35*u*u)*pat;
const cf=Math.min(1,clComp(b)/6),u=(100-b.mood)/100,leave=(0.04+0.08*cf+0.35*u*u)*pat*salesLeaveMul(b);
if(clR(b,'leave')<leave){clLeave(b,d,out);continue;}
const g=clR(b,'grow');if((b.mood>=80&&g<0.3)||(b.mood>=60&&g<0.12)){if(clGrow(b)){clRenew(b,clFair(b));clNote('grew');out.grew++;out.ok.push(tr('lifecycle.renewed_and_grew',{name:esc(b.name),city:esc(clWhere(b)),bw:fmtG(b.bw)}));continue;}}
clRenew(b,clFair(b));clNote('ren');out.ren++;}

View file

@ -59,6 +59,8 @@ function dayPost(d){
if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}
// contracts: renewals, growth, haggles and leaving (75-customer-lifecycle.js)
clDay(d);
// the sales desk: meetings booked, golf played (38-sales-desk.js)
salesDay(d);
// own IX members join
for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.length<myFab(c).max){
const cands=NETS.filter(n=>n.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg)));
@ -69,7 +71,7 @@ function dayPost(d){
// offers
S.offers=S.offers.filter(o=>o.exp>d);
brTick();
if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)){const n0=S.offers.length;spawnOffer();mktPrice(n0);}
if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)*salesSpawn()){const n0=S.offers.length;spawnOffer();mktPrice(n0);salesShape(n0);}
// failures & events
// Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never.
let dirty=false;const cm=chaosMul();

View file

@ -12,9 +12,11 @@ Object.assign(ACT,{
const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name);
if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots);
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;}
S.offers=S.offers.filter(x=>x!==o);if(o.mk)customer.mk=o.mk;S.biz.push(clSign(customer));
S.offers=S.offers.filter(x=>x!==o);if(o.mk)customer.mk=o.mk;if(o.by)customer.by=o.by;S.biz.push(clSign(customer));
// The shark's commission: one month of what the deal pays, on signing.
if(o.by==='shark'){const c=Math.round(bizMo(customer));if(c>0){S.cash-=c;toast(tr('sales.commission',{name:esc(o.name),cost:fmt$(c)}),'');}}
floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();},
decline:({id})=>{S.offers=S.offers.filter(x=>x.id!==id);after();},
decline:({id})=>{if(salesOverride(S.offers.find(x=>x.id===id))){after();return;}S.offers=S.offers.filter(x=>x.id!==id);after();},
dropBiz:({id})=>{const b0=S.biz.find(x=>x.id===id);if(!b0)return;if(BIZ_T[b0.type].event&&S.day>=b0.start){toast(tr('customers.the_event_is_already_running_the'),'bad');sfx('err');return;}if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.biz=S.biz.filter(b=>b.id!==id);UI.confirm=null;after();},
});
/* The renewal haggle (#178, 75-customer-lifecycle.js): match their price, meet halfway (they take it about two times
@ -23,7 +25,7 @@ function clHagOf(id){const b=S.biz.find(x=>x.id===id);return b&&b.hag?b:null;}
Object.assign(ACT,{
renewMatch:({id})=>{const b=clHagOf(id);if(!b)return;clRenew(b,b.hag.rate);clNote('ren');toast(tr('lifecycle.matched',{name:esc(b.name)}),'good');sfx('coin');after();},
renewMeet:({id})=>{const b=clHagOf(id);if(!b)return;const mid=Math.round((b.hag.rate+clFair(b))/2);
if(clR(b,'meet')<0.65){clRenew(b,mid);clNote('ren');toast(tr('lifecycle.meet_yes',{name:esc(b.name),price:fmt$(BIZ_T[b.type].fiber?b.rate:b.bw*b.rate)}),'good');sfx('coin');}
if(clR(b,'meet')<salesMeet()){clRenew(b,mid);clNote('ren');toast(tr('lifecycle.meet_yes',{name:esc(b.name),price:fmt$(BIZ_T[b.type].fiber?b.rate:b.bw*b.rate)}),'good');sfx('coin');}
else{clGone(b,'cheap');toast(tr('lifecycle.meet_no',{name:esc(b.name)}),'bad');sfx('err');}after();},
renewLet:({id})=>{const b=clHagOf(id);if(!b)return;clGone(b,'cheap');toast(tr('lifecycle.let_go',{name:esc(b.name)}),'');after();},
});

View file

@ -0,0 +1,12 @@
// The sales desk (38-sales-desk.js): hiring one salesperson, letting them go, and asking the board for a VP of Sales
// when the CEO has taken over.
Object.assign(ACT,{
salesOpen:()=>{if(S)salesModal();},
salesHire:({id})=>{if(!S||!own(SALES,id)||slP()||!salesCanHire()||!rule('clock'))return;const P=SALES[id];if(P.mo&&!spend(P.mo))return;
S.sales=Object.assign(S.sales||{},{p:id,hired:S.day,vp:null,golf:null,say:null});UI.confirm=null;
toast(id==='ceo'?tr('sales.ceo_took_over',{name:esc(slCap())}):tr('sales.hired',{name:esc(slCap())}),'good');sfx('coin');after();salesModal();},
salesFire:()=>{const p=slP();if(!p||p==='ceo')return;if(UI.confirm!=='salesFire'){UI.confirm='salesFire';salesModal();return;}UI.confirm=null;const nm=slCap();S.sales.p=null;
toast(tr('sales.fired',{name:esc(nm)}),'');after();salesModal();},
// The CEO cannot be fired. A board meeting (and its catering) can get you a VP of Sales, who takes over a month later.
salesVp:()=>{if(slP()!=='ceo'||S.sales.vp)return;if(!spend(SALES_VP))return;S.sales.vp=S.day+SALES_VP_DAYS;toast(tr('sales.vp_asked',{n:SALES_VP_DAYS}),'');after();salesModal();},
});

View file

@ -42,7 +42,7 @@ function renderLeft(){checkLayer();
h+=badgeGrid();
}else if(UI.left==='deals'){
{const st=custStats();if(st.n)h+=`<div class="row" style="margin-bottom:8px"><div class="grow"><div class="nm">${tr('common.your_customers')} <span class="meta">${st.n} · ${tr('hud_and_panels.happiness_p',{p:Math.round(st.avg)})}</span></div><div class="bar ${moodCls(st.avg)}"><i style="width:${st.avg}%"></i></div>${st.unhappy?`<div class="why">${trn('hud_and_panels.n_unhappy_customer_price_mo_at',st.unhappy,{price:fmt$(st.risk)})}</div>`:''}</div>${btn(st.unhappy?tr('common.see_who'):tr('common.all_customers'),'custOpen',{sad:st.unhappy?1:0},st.unhappy?'pink sm':'ghost sm')}</div>`;}
h+=clDealsHtml()+confSection()+seatSection();
h+=salesCard()+clDealsHtml()+confSection()+seatSection();
{const lv=S.lvl||1,nx=LEVELS[lv];h+=`<div class="inc" style="background:#FFF6CF"><div class="nm">${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}</div><div class="meta">${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}</div></div>`;}
if(!S.offers.length)h+=`<p class="empty">${tr('hud_and_panels.no_open_offers_right_now_businesses')}</p>`;
for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o);

View file

@ -0,0 +1,17 @@
// The sales desk in Deals, and its sheet: the three kinds of salesperson, who is at the desk, and what they cost.
function salesCard(){if(!S||!rule('clock'))return '';const p=slP(),L=S.sales||{};
return `<div class="ops-card"><div class="nm">${p?`${SALES[p].i} ${esc(tr('sales.at_desk',{name:slCap()}))}`:`💼 ${tr('sales.desk')}`}</div>
<div class="meta">${p?(L.vp?tr('sales.vp_coming',{n:Math.max(0,L.vp-S.day)}):tr(SALES[p].d)):salesCanHire()?tr('sales.pitch'):tr('sales.locked',{lv:SALES_LV})}</div>
<div class="btns">${btn(p?tr('sales.desk'):tr('sales.hire_sales'),'salesOpen',{},p?'sm':'pink sm',!p&&!salesCanHire())}</div></div>`;}
function salesModal(){if(!S)return;const p=slP(),L=S.sales||{};
let h=`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('common.deals')}</div><h2 style="font-size:26px">${tr('sales.desk')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>`;
h+=`<p class="tagline">${tr('sales.intro')}</p>`;
if(!rule('clock'))h+=`<p class="why">${tr('ops.no_clock')}</p>`;else if(!salesCanHire()&&!p)h+=`<p class="why">${tr('sales.locked',{lv:SALES_LV})}</p>`;
h+=Object.entries(SALES).map(([id,P])=>{const here=p===id;
const act=here?(id==='ceo'?(L.vp?`<span class="tag st on">${tr('sales.vp_coming',{n:Math.max(0,L.vp-S.day)})}</span>`:btn(tr('sales.ask_vp',{cost:fmt$(SALES_VP)}),'salesVp',{},'ghost sm',S.cash<SALES_VP))
:btn(UI.confirm==='salesFire'?tr('ops.really_fire'):tr('ops.fire'),'salesFire',{},'ghost sm'))
:p?'':btn(id==='ceo'?tr('sales.let_ceo'):tr('ops.hire_mo',{price:fmt$(P.mo)}),'salesHire',{id},'pink sm',!salesCanHire()||!rule('clock')||S.cash<P.mo);
return `<div class="ops-o${here?' on':''}"><div class="ops-h"><span class="ops-i" aria-hidden="true">${P.i}</span><div class="grow"><div class="nm">${tr(P.n)}</div>
<div class="meta">${tr(P.d)}</div>${here&&id!=='ceo'?`<div class="meta">${tr('ops.salary',{price:fmt$(P.mo),d:dateStr(L.hired||0)})}</div>`:''}${act?`<div class="btns">${act}</div>`:''}</div></div></div>`;}).join('');
if(p&&p!=='ceo')h+=`<p class="note">${tr('sales.one_at_a_time')}</p>`;
openModal(h,'ops');}

View file

@ -3903,6 +3903,42 @@
"rules.rules_are_locked_for_this_network":"{rules}: rules are locked for this network.",
"rules.the_real_thing_your_pager_has":"The real thing. Your pager has opinions.",
"rules.your_pager_never_sleeps":"Your pager never sleeps.",
"sales.ask_vp":"Ask the board for a VP of Sales · {cost}",
"sales.at_desk":"{name} runs sales",
"sales.ceo_d":"Free, and sure of it. Every couple of months signs a huge deal on the golf course at 30% off, often with a promise nobody checked, and now and then signs an offer you declined. Has opinions. Cannot be fired.",
"sales.ceo_golf":"The CEO signed {name} on the golf course: {bw} in {city} for {price}/mo, 30% off list.",
"sales.ceo_n":"The CEO, who sells better than anyone",
"sales.ceo_override":"You declined {name}, but the CEO had already shaken hands on it. They are now a customer.",
"sales.ceo_promised":"He also promised: {req}.",
"sales.ceo_s":"the CEO",
"sales.ceo_say_airport":"Just landed. Signed nothing, but I had a very good feeling about the lounge Wi-Fi.",
"sales.ceo_say_blockchain":"Have we thought about putting the routing table on a blockchain?",
"sales.ceo_say_golf":"The best deals happen on the ninth hole. The NOC should play more golf.",
"sales.ceo_say_mbps":"Why do we sell gigabits? Megabits sound like more.",
"sales.ceo_say_napkin":"I priced the next deal on a napkin. Engineering can work out the details.",
"sales.ceo_say_synergy":"We don't sell bandwidth, we sell synergy. Put that on the website.",
"sales.ceo_says":"The CEO: “{say}”",
"sales.ceo_took_over":"{name} has taken over sales personally. He is sure he sells better than anyone.",
"sales.commission":"{name} signed. Commission for the shark: {cost}.",
"sales.desk":"Sales desk",
"sales.eng_booked":"{name} registered you for {conf} in {city} ({cost}). They already have the lanyard.",
"sales.eng_d":"Was a network engineer, now has a lanyard for every NOG. Books you into each one (you pay the ticket), brings plenty of small and mid deals but never the really big ones, and only sells what the network can do, so customers stay. The nerds love Dave. Haggles badly.",
"sales.eng_n":"The engineer turned salesdroid",
"sales.eng_s":"Dave",
"sales.fired":"{name} has cleared their desk. The sales desk is free.",
"sales.hire_sales":"Hire sales",
"sales.hired":"{name} joined sales. Expect deals in their style.",
"sales.intro":"One person runs sales at a time. Each brings deals in their own way, and the customers they sign remember it when their contract comes up.",
"sales.let_ceo":"Let the CEO run it",
"sales.locked":"The sales desk opens at customer level {lv}.",
"sales.one_at_a_time":"One at a time: let them go to hire someone else.",
"sales.pitch":"One salesperson brings in deals their own way. Pick who.",
"sales.shark_d":"Lands the biggest deals at a quarter more, and takes a month of each deal as commission. Oversells: half of them come with a promise your network does not keep yet, and those customers leave sooner. Ignores the nerds: no technical customers, no meetings, and peering desks want a quarter more traffic from you. Wins most haggles.",
"sales.shark_n":"The shark",
"sales.shark_s":"Chad",
"sales.vp_arrived":"The VP of Sales has started, and the CEO has gone back to strategy. The sales desk is free: hire someone.",
"sales.vp_asked":"The board agreed, after lunch. A VP of Sales starts in {n} days; until then the CEO keeps selling.",
"sales.vp_coming":"A VP of Sales takes over in {n} days.",
"save.cash_in_the_bank":"{cash} in the bank",
"save.import_failed_err":"<b>Import failed.</b><br>{err}",
"save.load_name":"Load {name}?",

118
tests/sales-desk.test.js Normal file
View file

@ -0,0 +1,118 @@
// The sales desk: one salesperson at a time, three kinds (the engineer turned salesdroid, the shark, the CEO), each
// bringing deals their own way and leaving their mark on the customers they sign.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const start = "ACT.start({});S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;for(const c of ['ams','lon','par','fra','nyc','ash'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=3;compute()";
// Offers as the day brings them, shaped by whoever is at the desk.
const offers = (ev, n = 600) => JSON.parse(ev(`(()=>{const out=[];for(let i=0;i<${n};i++){S.offers=[];spawnOffer();mktPrice(0);salesShape(0);out.push(...S.offers.map(o=>({t:o.type,by:o.by||null,bw:o.bw,rate:o.rate,reqs:(o.reqs||[]).length})));}return JSON.stringify(out);})()`));
test('one salesperson at a time, from customer level 2, with a salary; the CEO is free and cannot be fired', () => {
const { ev, errors } = load();
ev(start);
ev("S.lvl=1;ACT.salesHire({id:'eng'})");
assert.equal(ev('slP()'), null, 'level 1: the desk is not open yet');
ev("S.lvl=4;ACT.salesHire({id:'eng'})");
assert.equal(ev('slP()'), 'eng');
ev("ACT.salesHire({id:'shark'})");
assert.equal(ev('slP()'), 'eng', 'one at a time');
assert.equal(ev('salesMo()'), 9000, 'on the payroll');
ev('compute()');
assert.ok(ev('R.cost.extras') >= 9000);
ev('ACT.salesFire()'); ev('ACT.salesFire()');
assert.equal(ev('slP()'), null, 'let go after a confirmation');
ev("ACT.salesHire({id:'ceo'})");
assert.equal(ev('slP()'), 'ceo');
assert.equal(ev('salesMo()'), 0);
ev('ACT.salesFire()'); ev('ACT.salesFire()');
assert.equal(ev('slP()'), 'ceo', 'nobody fires the CEO');
const cash = ev('S.cash');
ev('ACT.salesVp()');
assert.equal(ev('S.cash'), cash - ev('SALES_VP'), 'a board meeting costs');
ev('for(let i=0;i<SALES_VP_DAYS;i++)salesDay(S.day+i+1)');
assert.equal(ev('slP()'), null, 'a month later the VP of Sales frees the desk');
assert.deepEqual(errors, []);
});
test('the engineer: more offers, never the huge deals, books every NOG at the usual price, and their customers stay', () => {
const { ev, errors } = load();
ev(start);
ev("ACT.salesHire({id:'eng'})");
const o = offers(ev);
assert.ok(o.length > 300);
assert.ok(o.every(x => !ev(`salesBig('${x.t}')`)), 'no mega AI, hyperscaler or AGI deals');
assert.ok(o.every(x => x.by === 'eng'), 'every offer is theirs');
assert.ok(ev('salesSpawn()') > 1, 'more offers come in');
// A meeting 30 days out: they register you and you pay the ticket.
const r = JSON.parse(ev(`(()=>{const cf=upcomingConfs(400).find(c=>!c.cap);S.day=cf.day-30;const cash=S.cash;salesDay(S.day);const n=upcomingConfs(30).filter(c=>!c.cap&&c.day===cf.day).length;return JSON.stringify({reg:!!S.confReg[cf.key],paid:cash-S.cash,n});})()`));
assert.equal(r.reg, true);
assert.equal(r.paid, r.n * ev('CONF_COST'), 'every meeting that day, each at the usual ticket price: not for free');
assert.equal(ev("salesLeaveMul({by:'eng',type:'hft'})"), 0.5, 'the nerds love them');
assert.ok(ev("salesLeaveMul({by:'eng',type:'dia'})") < 1);
assert.ok(ev('salesAsk()') < 0.8, 'and they haggle badly');
assert.deepEqual(errors, []);
});
test('the shark: bigger deals at a quarter more, oversold promises, no nerds, a commission, tougher peering', () => {
const { ev, errors } = load();
ev(start);
const plain = offers(ev);
ev("ACT.salesHire({id:'shark'})");
const o = offers(ev);
assert.ok(o.every(x => !ev(`SALES_NERDS.includes('${x.t}')`)), 'no technical customers');
const avg = (l, t) => { const x = l.filter(y => y.t === t); return x.reduce((a, y) => a + y.rate, 0) / Math.max(1, x.length); };
assert.ok(avg(o, 'dia') > avg(plain, 'dia') * 1.15, `priced higher (${avg(o, 'dia')} vs ${avg(plain, 'dia')})`);
const oversold = o.filter(x => x.reqs > 0).length / o.length, before = plain.filter(x => x.reqs > 0).length / plain.length;
assert.ok(oversold > before + 0.15, `oversold: ${Math.round(oversold * 100)}% with promises, ${Math.round(before * 100)}% without the shark`);
assert.equal(ev('salesPeerMul()'), 1.25);
assert.equal(ev('salesMeet()'), 0.9, 'wins most haggles');
assert.equal(ev("salesLeaveMul({by:'shark',type:'dia'})"), 1.5, 'and their customers leave sooner');
// Signing one of theirs pays the commission.
ev("S.offers=[];for(let i=0;i<200&&!S.offers.some(o=>o.by==='shark'&&bHas(o)&&!BIZ_T[o.type].event&&!BIZ_T[o.type].fiber);i++){spawnOffer();salesShape(0);}");
const r = JSON.parse(ev("(()=>{const o=S.offers.find(o=>o.by==='shark'&&bHas(o)&&!BIZ_T[o.type].event&&!BIZ_T[o.type].fiber);const cash=S.cash;ACT.accept({id:o.id});const b=S.biz.find(b=>b.id===o.id);return JSON.stringify({by:b&&b.by,paid:cash-S.cash,mo:b?bizMo(b):0});})()"));
assert.equal(r.by, 'shark', 'the customer remembers who signed it');
assert.equal(r.paid, Math.round(r.mo), 'a month of the deal as commission');
assert.deepEqual(errors, []);
});
test('the CEO: golf deals at 30% off, the odd declined offer signed anyway, opinions; all from hashes, not Math.random', () => {
const { ev, errors } = load();
ev(start);
ev("ACT.salesHire({id:'ceo'})");
ev('window.__r=0;window.__r0=Math.random;Math.random=()=>{__r++;return __r0();};');
const n0 = ev('S.biz.length');
ev('for(let i=1;i<=200;i++)salesDay(S.day+i)');
ev('Math.random=__r0');
assert.equal(ev('__r'), 0, 'no draws from the game\'s random stream');
const golf = JSON.parse(ev(`JSON.stringify(S.biz.slice(${n0}).map(b=>({by:b.by,t:b.type,bw:b.bw,rate:b.rate,list:BIZ_T[b.type].rate})))`));
assert.ok(golf.length >= 2 && golf.length <= 4, `a golf deal every 50–80 days (${golf.length} in 200 days)`);
for (const g of golf) {
assert.equal(g.by, 'ceo');
assert.ok(g.rate <= Math.round(g.list * 0.7 * ev('mkt()')) + 1, '30% off list');
}
assert.ok(ev("S.log.some(e=>/The CEO: /.test(e.t))"), 'and opinions');
// Declining: about one in three, he already shook hands.
const r = JSON.parse(ev(`(()=>{let over=0,n=0;for(let i=0;i<300;i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>bHas(o)&&!BIZ_T[o.type].event);if(!o)continue;n++;const b0=S.biz.length;ACT.decline({id:o.id});if(S.biz.length>b0)over++;}return JSON.stringify({over,n});})()`));
assert.ok(r.n > 50 && r.over / r.n > 0.2 && r.over / r.n < 0.45, `${r.over} of ${r.n} declines signed anyway`);
assert.deepEqual(errors, []);
});
test('the desk in Deals and its sheet, and saves that remember who is at the desk', () => {
const { ev, errors } = load();
ev(start);
ev("UI.left='deals';renderLeft()");
assert.match(ev("document.getElementById('left').innerHTML"), /data-act="salesOpen"/);
ev('ACT.salesOpen()');
const m = ev("document.getElementById('modal').innerHTML");
for (const id of ['eng', 'shark', 'ceo']) assert.match(m, new RegExp(`data-act="salesHire" data-args="\\{&quot;id&quot;:&quot;${id}&quot;\\}"`));
ev("ACT.salesHire({id:'shark'})");
const s = JSON.parse(ev('JSON.stringify(packSave(S))'));
s.offers = [{ id: 'o1', city: 'ams', name: 'X', type: 'dia', bw: 1, rate: 600, reqs: [], exp: 99, by: 'pirate' }];
const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})))`));
assert.equal(out.sales.p, 'shark');
assert.equal(out.offers[0].by, undefined, 'only real salespeople');
s.sales = { p: 'intern', hired: 'yesterday' };
assert.equal(JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})).sales)`)).p, null);
assert.deepEqual(errors, []);
});